From 18189f0d42f7375660762dc6c885cf31683ae562 Mon Sep 17 00:00:00 2001 From: Pascal Rapicault Date: Wed, 13 Jan 2010 17:29:41 +0000 Subject: Merging api branch back to HEAD --- .../.classpath | 4 +- .../.settings/org.eclipse.jdt.core.prefs | 15 +- .../META-INF/MANIFEST.MF | 15 +- .../build.properties | 2 + .../p2/artifact/optimizers/AbstractDeltaStep.java | 12 +- .../optimizers/VersionlessArtifactKey.java | 4 +- .../artifact/optimizers/jardelta/Application.java | 10 +- .../optimizers/jardelta/DeltaComputer.java | 34 +- .../optimizers/jardelta/JarDeltaOptimizerStep.java | 4 +- .../p2/artifact/optimizers/jardelta/Optimizer.java | 78 +- .../p2/artifact/optimizers/jbdiff/Application.java | 11 +- .../p2/artifact/optimizers/jbdiff/JBDiffStep.java | 4 +- .../artifact/optimizers/jbdiff/JBDiffZipStep.java | 4 +- .../p2/artifact/optimizers/jbdiff/Optimizer.java | 59 +- .../artifact/optimizers/pack200/Application.java | 11 +- .../p2/artifact/optimizers/pack200/Optimizer.java | 26 +- .../META-INF/MANIFEST.MF | 7 +- .../processors/AbstractDeltaProcessorStep.java | 13 +- .../processors/jardelta/JarDeltaProcessorStep.java | 2 +- .../p2/artifact/processors/jbdiff/JBPatchStep.java | 2 +- .../artifact/processors/jbdiff/JBPatchZipStep.java | 2 +- .../.classpath | 3 +- ...p2.artifact.repository buildAntTasks.xml.launch | 18 - .../.project | 10 - .../.settings/org.eclipse.jdt.core.prefs | 14 +- .../META-INF/MANIFEST.MF | 54 +- .../OSGI-INF/repositoryManager.xml | 2 +- .../build.properties | 8 +- .../buildAntTasks.xml | 9 - .../plugin.xml | 48 +- .../internal/p2/artifact/mirror/FileMirrorLog.java | 125 -- .../p2/artifact/mirror/IArtifactMirrorLog.java | 26 - .../p2/artifact/mirror/MirrorApplication.java | 263 --- .../internal/p2/artifact/mirror/Mirroring.java | 273 --- .../internal/p2/artifact/mirror/XMLMirrorLog.java | 166 -- .../processors/md5/MD5ArtifactComparator.java | 41 - .../p2/artifact/processors/md5/MD5Verifier.java | 9 +- .../processors/pack200/Pack200ProcessorStep.java | 7 +- .../internal/p2/artifact/repository/Activator.java | 61 +- .../repository/ArtifactRepositoryComponent.java | 12 +- .../repository/ArtifactRepositoryManager.java | 43 +- .../p2/artifact/repository/ArtifactRequest.java | 8 +- .../repository/CompositeArtifactRepository.java | 301 +-- .../CompositeArtifactRepositoryFactory.java | 25 +- .../p2/artifact/repository/FlatteningIterator.java | 64 + .../internal/p2/artifact/repository/Messages.java | 1 + .../p2/artifact/repository/MirrorRequest.java | 62 +- .../p2/artifact/repository/MirrorSelector.java | 17 +- .../p2/artifact/repository/RawMirrorRequest.java | 4 +- .../p2/artifact/repository/SignatureVerifier.java | 4 +- .../p2/artifact/repository/messages.properties | 1 + .../p2/artifact/repository/simple/BlobStore.java | 9 +- .../p2/artifact/repository/simple/DownloadJob.java | 8 +- .../p2/artifact/repository/simple/Mapper.java | 4 +- .../simple/SimpleArtifactDescriptor.java | 84 + .../simple/SimpleArtifactRepository.java | 185 +- .../simple/SimpleArtifactRepositoryFactory.java | 133 ++ .../simple/SimpleArtifactRepositoryIO.java | 70 +- .../repository/ArtifactComparatorFactory.java | 52 - .../p2/artifact/repository/ArtifactDescriptor.java | 191 -- .../artifact/repository/IArtifactComparator.java | 31 - .../artifact/repository/IArtifactDescriptor.java | 62 - .../artifact/repository/IArtifactRepository.java | 133 -- .../repository/IArtifactRepositoryManager.java | 149 -- .../p2/artifact/repository/IArtifactRequest.java | 33 - .../repository/IFileArtifactRepository.java | 32 - .../repository/processing/ProcessingStep.java | 6 +- .../processing/ProcessingStepDescriptor.java | 89 - .../processing/ProcessingStepHandler.java | 24 +- .../repository/AbstractArtifactRepository.java | 78 - .../repository/ArtifactRepositoryFactory.java | 75 - .../SimpleArtifactRepositoryFactory.java | 129 -- .../p2/artifact/repository/ant/AddChildTask.java | 82 - .../p2/artifact/repository/ant/AntMirrorLog.java | 105 - .../ant/CreateCompositeArtifactRepositoryTask.java | 120 -- .../repository/ant/MirrorApplicationTask.java | 221 --- .../artifact/repository/ant/RemoveChildTask.java | 76 - .../p2/artifact/repository/ant/ValidateTask.java | 68 - bundles/org.eclipse.equinox.p2.console/.classpath | 4 +- .../.settings/org.eclipse.jdt.core.prefs | 15 +- .../META-INF/MANIFEST.MF | 21 +- .../build.properties | 2 + .../equinox/internal/p2/console/Activator.java | 23 +- .../internal/p2/console/ProvCommandProvider.java | 372 +++- .../internal/p2/console/ProvisioningHelper.java | 170 +- bundles/org.eclipse.equinox.p2.core/.classpath | 2 +- .../.settings/org.eclipse.jdt.core.prefs | 346 ---- .../.settings/org.eclipse.pde.api.tools.prefs | 11 +- .../META-INF/MANIFEST.MF | 21 +- .../org.eclipse.equinox.p2.core/build.properties | 2 + .../equinox/internal/p2/core/Activator.java | 45 +- .../equinox/internal/p2/core/AgentLocation.java | 35 + .../equinox/internal/p2/core/BasicLocation.java | 56 - .../internal/p2/core/DefaultAgentProvider.java | 21 +- .../internal/p2/core/ProvisioningAgent.java | 56 +- .../equinox/internal/p2/core/StringPool.java | 6 +- .../internal/p2/core/helpers/CollectionUtils.java | 263 +++ .../internal/p2/core/helpers/FileUtils.java | 42 +- .../internal/p2/core/helpers/LogHelper.java | 8 +- .../p2/core/helpers/OrderedProperties.java | 88 +- .../internal/p2/core/helpers/StringHelper.java | 4 +- .../equinox/internal/p2/core/helpers/TarFile.java | 6 +- .../internal/provisional/p2/core/IServiceUI.java | 5 + .../provisional/p2/core/ProvisionException.java | 133 -- .../p2/core/location/AgentLocation.java | 41 - .../eclipse/equinox/p2/core/IAgentLocation.java | 44 + .../equinox/p2/core/IProvisioningAgent.java | 35 +- .../p2/core/IProvisioningAgentProvider.java | 9 +- .../equinox/p2/core/ProvisionException.java | 134 ++ .../equinox/p2/core/spi/IAgentServiceFactory.java | 2 +- .../org.eclipse.equinox.p2.director.app/.classpath | 2 +- .../.settings/org.eclipse.jdt.core.prefs | 14 +- .../META-INF/MANIFEST.MF | 21 +- .../build.properties | 2 + .../org.eclipse.equinox.p2.director.app/plugin.xml | 7 + .../internal/p2/director/app/Application.java | 144 +- .../p2/director/app/DirectorApplication.java | 422 ++-- .../equinox/internal/p2/director/app/ILog.java | 14 + .../equinox/internal/p2/director/app/Messages.java | 9 +- .../internal/p2/director/app/messages.properties | 12 +- .../equinox/p2/director/app/ant/DirectorTask.java | 256 ++- bundles/org.eclipse.equinox.p2.director/.classpath | 2 +- .../.settings/org.eclipse.jdt.core.prefs | 12 +- .../META-INF/MANIFEST.MF | 25 +- .../build.properties | 2 + .../internal/p2/director/ApplicablePatchQuery.java | 23 +- .../internal/p2/director/AttachmentHelper.java | 58 +- .../internal/p2/director/DirectorComponent.java | 16 +- .../equinox/internal/p2/director/Explanation.java | 32 +- .../internal/p2/director/HasMatchCollector.java | 30 - .../equinox/internal/p2/director/Messages.java | 1 + .../internal/p2/director/OperationGenerator.java | 107 +- .../internal/p2/director/PermissiveSlicer.java | 18 +- .../internal/p2/director/PlannerComponent.java | 4 +- .../equinox/internal/p2/director/Projector.java | 463 +++-- .../internal/p2/director/QueryableArray.java | 97 +- .../internal/p2/director/SimpleDirector.java | 10 +- .../internal/p2/director/SimplePlanner.java | 467 +++-- .../equinox/internal/p2/director/Slicer.java | 127 +- .../equinox/internal/p2/director/TwoTierMap.java | 354 ---- .../internal/p2/director/messages.properties | 3 +- .../equinox/internal/p2/rollback/FormerState.java | 78 +- .../provisional/p2/director/IDirector.java | 4 +- .../internal/provisional/p2/director/IPlanner.java | 9 +- .../p2/director/PlanExecutionHelper.java | 11 +- .../provisional/p2/director/PlannerHelper.java | 2 +- .../p2/director/ProfileChangeRequest.java | 170 +- .../provisional/p2/director/ProvisioningPlan.java | 130 -- .../provisional/p2/director/RequestStatus.java | 39 +- .../.classpath | 2 +- .../.settings/org.eclipse.jdt.core.prefs | 594 +++--- .../META-INF/MANIFEST.MF | 21 +- .../build.properties | 2 + .../provisional/p2/directorywatcher/Activator.java | 9 +- .../CachingArtifactRepository.java | 79 +- .../p2/directorywatcher/DirectoryWatcher.java | 39 +- .../p2/directorywatcher/EntryAdvice.java | 32 +- .../p2/directorywatcher/RepositoryListener.java | 89 +- bundles/org.eclipse.equinox.p2.engine/.classpath | 2 +- .../.settings/.api_filters | 11 + .../.settings/org.eclipse.jdt.core.prefs | 14 +- .../ExtensionWizardPage.java | 121 ++ .../META-INF/MANIFEST.MF | 52 +- .../OSGI-INF/engine.xml | 2 +- .../OSGI-INF/profileRegistry.xml | 2 +- .../org.eclipse.equinox.p2.engine/build.properties | 2 + .../schema/actions.exsd | 34 +- .../schema/touchpoints.exsd | 2 +- .../equinox/internal/p2/engine/ActionManager.java | 22 +- .../equinox/internal/p2/engine/DebugHelper.java | 35 +- .../internal/p2/engine/DownloadManager.java | 52 +- .../eclipse/equinox/internal/p2/engine/Engine.java | 129 ++ .../internal/p2/engine/EngineActivator.java | 17 +- .../internal/p2/engine/EngineComponent.java | 9 +- .../equinox/internal/p2/engine/EngineSession.java | 399 ++++ .../internal/p2/engine/InstallableUnitPhase.java | 122 ++ .../internal/p2/engine/InstructionParser.java | 35 +- .../equinox/internal/p2/engine/Messages.java | 90 +- .../p2/engine/ParameterizedProvisioningAction.java | 27 +- .../eclipse/equinox/internal/p2/engine/Phase.java | 325 +++ .../equinox/internal/p2/engine/PhaseSet.java | 196 ++ .../equinox/internal/p2/engine/Profile.java | 111 +- .../p2/engine/ProfileMetadataRepository.java | 26 +- .../engine/ProfileMetadataRepositoryFactory.java | 10 +- .../equinox/internal/p2/engine/ProfileParser.java | 26 +- .../internal/p2/engine/ProfilePreferences.java | 134 +- .../p2/engine/ProfileRegistryComponent.java | 6 +- .../equinox/internal/p2/engine/ProfileWriter.java | 27 +- .../internal/p2/engine/ProfileXMLConstants.java | 11 +- .../internal/p2/engine/SimpleProfileRegistry.java | 177 +- .../p2/engine/SurrogateProfileHandler.java | 90 +- .../internal/p2/engine/TouchpointManager.java | 19 +- .../equinox/internal/p2/engine/messages.properties | 54 +- .../p2/engine/phases/CertificateChecker.java | 184 ++ .../internal/p2/engine/phases/CheckTrust.java | 84 + .../equinox/internal/p2/engine/phases/Collect.java | 85 + .../internal/p2/engine/phases/Configure.java | 56 + .../equinox/internal/p2/engine/phases/Install.java | 127 ++ .../internal/p2/engine/phases/Property.java | 159 ++ .../equinox/internal/p2/engine/phases/Sizing.java | 138 ++ .../internal/p2/engine/phases/Unconfigure.java | 61 + .../internal/p2/engine/phases/Uninstall.java | 125 ++ .../provisional/p2/engine/BeginOperationEvent.java | 20 - .../provisional/p2/engine/CertificateChecker.java | 173 -- .../p2/engine/CommitOperationEvent.java | 20 - .../provisional/p2/engine/DefaultPhaseSet.java | 63 - .../internal/provisional/p2/engine/Engine.java | 121 -- .../provisional/p2/engine/EngineSession.java | 367 ---- .../internal/provisional/p2/engine/IEngine.java | 26 - .../internal/provisional/p2/engine/IProfile.java | 131 -- .../provisional/p2/engine/IProfileRegistry.java | 132 -- .../p2/engine/ISurrogateProfileHandler.java | 27 - .../p2/engine/IUProfilePropertyQuery.java | 42 - .../p2/engine/InstallableUnitEvent.java | 84 - .../p2/engine/InstallableUnitOperand.java | 46 - .../p2/engine/InstallableUnitPhase.java | 120 -- .../p2/engine/InstallableUnitPropertyOperand.java | 43 - .../internal/provisional/p2/engine/Memento.java | 76 - .../internal/provisional/p2/engine/Messages.java | 67 - .../provisional/p2/engine/MissingAction.java | 46 - .../p2/engine/MissingActionsException.java | 49 - .../internal/provisional/p2/engine/Operand.java | 20 - .../internal/provisional/p2/engine/Phase.java | 318 --- .../internal/provisional/p2/engine/PhaseSet.java | 151 -- .../provisional/p2/engine/ProfileEvent.java | 39 - .../provisional/p2/engine/ProfileScope.java | 79 - .../provisional/p2/engine/PropertyOperand.java | 52 - .../provisional/p2/engine/ProvisioningAction.java | 37 - .../provisional/p2/engine/ProvisioningContext.java | 77 - .../p2/engine/RollbackOperationEvent.java | 28 - .../internal/provisional/p2/engine/Touchpoint.java | 54 - .../provisional/p2/engine/TransactionEvent.java | 31 - .../provisional/p2/engine/messages.properties | 51 - .../provisional/p2/engine/phases/CheckTrust.java | 78 - .../provisional/p2/engine/phases/Collect.java | 80 - .../provisional/p2/engine/phases/Configure.java | 52 - .../provisional/p2/engine/phases/Install.java | 120 -- .../provisional/p2/engine/phases/Messages.java | 37 - .../provisional/p2/engine/phases/Property.java | 157 -- .../provisional/p2/engine/phases/Sizing.java | 135 -- .../provisional/p2/engine/phases/Unconfigure.java | 57 - .../provisional/p2/engine/phases/Uninstall.java | 119 -- .../p2/engine/phases/messages.properties | 20 - .../equinox/p2/engine/BeginOperationEvent.java | 25 + .../equinox/p2/engine/CommitOperationEvent.java | 25 + .../eclipse/equinox/p2/engine/DefaultPhaseSet.java | 66 + .../src/org/eclipse/equinox/p2/engine/IEngine.java | 84 + .../org/eclipse/equinox/p2/engine/IPhaseSet.java | 73 + .../org/eclipse/equinox/p2/engine/IProfile.java | 133 ++ .../equinox/p2/engine/IProfileRegistry.java | 121 ++ .../equinox/p2/engine/IProvisioningPlan.java | 117 ++ .../p2/engine/ISurrogateProfileHandler.java | 31 + .../equinox/p2/engine/InstallableUnitEvent.java | 89 + .../equinox/p2/engine/InstallableUnitOperand.java | 49 + .../p2/engine/InstallableUnitPropertyOperand.java | 46 + .../eclipse/equinox/p2/engine/MissingAction.java | 50 + .../equinox/p2/engine/MissingActionsException.java | 53 + .../src/org/eclipse/equinox/p2/engine/Operand.java | 21 + .../eclipse/equinox/p2/engine/ProfileEvent.java | 40 + .../eclipse/equinox/p2/engine/ProfileScope.java | 110 ++ .../eclipse/equinox/p2/engine/PropertyOperand.java | 55 + .../equinox/p2/engine/ProvisioningContext.java | 82 + .../equinox/p2/engine/ProvisioningPlan.java | 162 ++ .../equinox/p2/engine/RollbackOperationEvent.java | 32 + .../equinox/p2/engine/TransactionEvent.java | 35 + .../src/org/eclipse/equinox/p2/engine/package.html | 22 + .../p2/engine/query/IUProfilePropertyQuery.java | 47 + .../p2/engine/query/UserVisibleRootQuery.java | 39 + .../org/eclipse/equinox/p2/engine/spi/Memento.java | 79 + .../equinox/p2/engine/spi/ProvisioningAction.java | 40 + .../eclipse/equinox/p2/engine/spi/Touchpoint.java | 58 + .../META-INF/MANIFEST.MF | 15 +- .../internal/p2/exemplarysetup/Activator.java | 178 +- .../.classpath | 2 +- .../.settings/org.eclipse.jdt.core.prefs | 14 +- .../META-INF/MANIFEST.MF | 24 +- .../build.properties | 2 + .../internal/p2/extensionlocation/Activator.java | 30 +- .../BundlePoolFilteredListener.java | 19 +- .../ExtensionLocationArtifactRepository.java | 34 +- ...ExtensionLocationArtifactRepositoryFactory.java | 24 +- .../ExtensionLocationMetadataRepository.java | 22 +- ...ExtensionLocationMetadataRepositoryFactory.java | 31 +- .../p2/extensionlocation/SiteListener.java | 42 +- .../.classpath | 4 +- .../.settings/org.eclipse.jdt.core.prefs | 16 +- .../META-INF/MANIFEST.MF | 12 +- .../build.properties | 2 + .../internal/p2/garbagecollector/Application.java | 8 +- .../p2/garbagecollector/CoreGarbageCollector.java | 31 +- .../internal/p2/garbagecollector/GCActivator.java | 8 +- .../p2/garbagecollector/GarbageCollector.java | 35 +- .../internal/p2/garbagecollector/MarkSet.java | 4 +- .../p2/garbagecollector/MarkSetProvider.java | 9 +- .../org.eclipse.equinox.p2.installer/.classpath | 4 +- .../.settings/org.eclipse.jdt.core.prefs | 16 +- .../META-INF/MANIFEST.MF | 5 +- .../build.properties | 2 + .../p2/installer/InstallDescriptionParser.java | 55 +- .../installer/InstallUpdateProductOperation.java | 55 +- .../equinox/internal/p2/installer/Messages.java | 1 - .../internal/p2/installer/messages.properties | 3 +- .../internal/p2/installer/ui/InstallDialog.java | 2 - .../internal/p2/installer/ui/ProxiesDialog.java | 8 +- .../p2/installer/InstallDescription.java | 9 +- .../equinox/internal/p2/jarprocessor/PackStep.java | 6 +- .../equinox/internal/p2/jarprocessor/Utils.java | 1 - .../p2/jarprocessor/verifier/Verifier.java | 1 + .../p2/jarprocessor/verifier/VerifyStep.java | 1 - .../equinox/p2/jarprocessor/JarProcessor.java | 168 +- .../p2/jarprocessor/ant/JarProcessorTask.java | 5 +- .../META-INF/MANIFEST.MF | 14 +- .../generator/EclipseGeneratorApplication.java | 90 +- .../p2/metadata/generator/ProductQuery.java | 34 +- .../EclipseInstallGeneratorInfoProvider.java | 45 +- .../p2/metadata/generator/FeatureEntry.java | 2 +- .../p2/metadata/generator/Generator.java | 85 +- .../p2/metadata/generator/IGeneratorInfo.java | 4 +- .../generator/MetadataGeneratorHelper.java | 161 +- .../.classpath | 2 +- ....p2.metadata.reposiroy buildAntTasks.xml.launch | 9 +- .../.settings/org.eclipse.jdt.core.prefs | 14 +- .../META-INF/MANIFEST.MF | 45 +- .../OSGI-INF/repositoryManager.xml | 2 +- .../build.properties | 2 + .../p2 tools - mirror metadata.launch | 24 - .../plugin.xml | 21 +- .../p2/metadata/mirror/MirrorApplication.java | 175 -- .../internal/p2/metadata/mirror/Mirroring.java | 64 - .../internal/p2/metadata/mirror/RangeQuery.java | 50 - .../p2/metadata/mirror/VersionRangedName.java | 53 - .../internal/p2/metadata/repository/Activator.java | 78 +- .../p2/metadata/repository/CacheManager.java | 34 +- .../repository/CompositeMetadataRepository.java | 79 +- .../CompositeMetadataRepositoryFactory.java | 32 +- .../internal/p2/metadata/repository/IUMap.java | 107 + .../repository/LocalMetadataRepository.java | 63 +- .../repository/MetadataRepositoryComponent.java | 9 +- .../metadata/repository/MetadataRepositoryIO.java | 41 +- .../repository/MetadataRepositoryManager.java | 72 +- .../SimpleMetadataRepositoryFactory.java | 164 ++ .../metadata/repository/URLMetadataRepository.java | 24 +- .../p2/metadata/repository/io/MetadataParser.java | 263 ++- .../p2/metadata/repository/io/MetadataWriter.java | 165 +- .../p2/metadata/repository/io/XMLConstants.java | 10 +- .../metadata/repository/IMetadataRepository.java | 80 - .../repository/IMetadataRepositoryManager.java | 156 -- .../repository/AbstractMetadataRepository.java | 74 - .../repository/MetadataRepositoryFactory.java | 100 - .../metadata/repository/RepositoryReference.java | 57 - .../SimpleMetadataRepositoryFactory.java | 161 -- .../p2/metadata/repository/ant/AddChildTask.java | 7 +- .../ant/CreateCompositeMetadataRepositoryTask.java | 12 +- .../repository/ant/MirrorApplicationTask.java | 128 -- .../metadata/repository/ant/RemoveChildTask.java | 7 +- bundles/org.eclipse.equinox.p2.metadata/.classpath | 4 +- .../.settings/org.eclipse.jdt.core.prefs | 16 +- .../META-INF/MANIFEST.MF | 39 +- .../build.properties | 2 + .../equinox/internal/p2/metadata/ArtifactKey.java | 15 +- .../equinox/internal/p2/metadata/BasicVersion.java | 83 + .../equinox/internal/p2/metadata/Copyright.java | 2 +- .../internal/p2/metadata/IRequiredCapability.java | 45 + .../internal/p2/metadata/InstallableUnit.java | 132 +- .../p2/metadata/InstallableUnitFragment.java | 27 +- .../internal/p2/metadata/InstallableUnitPatch.java | 36 +- .../equinox/internal/p2/metadata/License.java | 16 +- .../equinox/internal/p2/metadata/Messages.java | 25 +- .../internal/p2/metadata/NotRequirement.java | 69 - .../internal/p2/metadata/ORRequirement.java | 85 - .../equinox/internal/p2/metadata/OSGiVersion.java | 213 ++ .../equinox/internal/p2/metadata/OmniVersion.java | 247 +++ .../internal/p2/metadata/ProvidedCapability.java | 13 +- .../internal/p2/metadata/RequiredCapability.java | 247 ++- .../internal/p2/metadata/RequirementChange.java | 43 +- .../p2/metadata/ResolvedInstallableUnit.java | 149 +- .../internal/p2/metadata/TouchpointData.java | 18 +- .../p2/metadata/TouchpointInstruction.java | 18 +- .../internal/p2/metadata/TouchpointType.java | 5 +- .../internal/p2/metadata/TranslationSupport.java | 299 +++ .../internal/p2/metadata/UpdateDescriptor.java | 5 +- .../internal/p2/metadata/VersionFormat.java | 345 ++++ .../internal/p2/metadata/VersionFormatParser.java | 1548 +++++++++++++++ .../internal/p2/metadata/VersionParser.java | 388 ++++ .../internal/p2/metadata/VersionVector.java | 325 +++ .../equinox/internal/p2/metadata/VersionedId.java | 104 + .../internal/p2/metadata/expression/All.java | 42 + .../internal/p2/metadata/expression/And.java | 50 + .../internal/p2/metadata/expression/At.java | 96 + .../internal/p2/metadata/expression/Binary.java | 135 ++ .../p2/metadata/expression/CoercingComparator.java | 392 ++++ .../p2/metadata/expression/CollectionFilter.java | 85 + .../internal/p2/metadata/expression/Compare.java | 60 + .../internal/p2/metadata/expression/Equals.java | 52 + .../p2/metadata/expression/EvaluationContext.java | 161 ++ .../internal/p2/metadata/expression/Exists.java | 42 + .../p2/metadata/expression/Expression.java | 341 ++++ .../p2/metadata/expression/ExpressionFactory.java | 125 ++ .../metadata/expression/IExpressionConstants.java | 58 + .../metadata/expression/IRepeatableIterator.java | 25 + .../p2/metadata/expression/LDAPApproximation.java | 77 + .../p2/metadata/expression/LDAPFilter.java | 69 + .../p2/metadata/expression/LambdaExpression.java | 72 + .../internal/p2/metadata/expression/Literal.java | 123 ++ .../p2/metadata/expression/MatchExpression.java | 83 + .../internal/p2/metadata/expression/Matches.java | 95 + .../internal/p2/metadata/expression/Member.java | 178 ++ .../p2/metadata/expression/MemberProvider.java | 139 ++ .../internal/p2/metadata/expression/NAry.java | 59 + .../internal/p2/metadata/expression/Not.java | 48 + .../internal/p2/metadata/expression/Or.java | 50 + .../internal/p2/metadata/expression/Parameter.java | 64 + .../p2/metadata/expression/RepeatableIterator.java | 237 +++ .../internal/p2/metadata/expression/Unary.java | 57 + .../internal/p2/metadata/expression/Variable.java | 79 + .../expression/parser/ExpressionParser.java | 617 ++++++ .../expression/parser/LDAPFilterParser.java | 268 +++ .../internal/p2/metadata/messages.properties | 13 +- .../p2/metadata/query/IUPropertyQuery.java | 48 + .../p2/metadata/query/LatestIUVersionQuery.java | 48 + .../p2/metadata/query/ObjectMatchQuery.java | 22 + .../internal/p2/metadata/query/UpdateQuery.java | 48 + .../equinox/internal/p2/query/QueryHelpers.java | 58 + .../provisional/p2/metadata/FormatException.java | 24 - .../provisional/p2/metadata/IArtifactKey.java | 50 - .../provisional/p2/metadata/ICopyright.java | 38 - .../provisional/p2/metadata/IInstallableUnit.java | 278 --- .../p2/metadata/IInstallableUnitFragment.java | 19 - .../p2/metadata/IInstallableUnitPatch.java | 48 - .../internal/provisional/p2/metadata/ILicense.java | 60 - .../p2/metadata/IProvidedCapability.java | 61 - .../p2/metadata/IRequiredCapability.java | 90 - .../p2/metadata/IRequirementChange.java | 35 - .../provisional/p2/metadata/ITouchpointData.java | 50 - .../p2/metadata/ITouchpointInstruction.java | 72 - .../provisional/p2/metadata/ITouchpointType.java | 54 - .../provisional/p2/metadata/IUpdateDescriptor.java | 53 - .../provisional/p2/metadata/IVersionedId.java | 30 - .../provisional/p2/metadata/MetadataFactory.java | 170 +- .../internal/provisional/p2/metadata/Version.java | 504 ----- .../provisional/p2/metadata/VersionFormat.java | 1247 ------------ .../p2/metadata/VersionFormatParser.java | 530 ----- .../provisional/p2/metadata/VersionParser.java | 366 ---- .../provisional/p2/metadata/VersionRange.java | 500 ----- .../provisional/p2/metadata/VersionVector.java | 367 ---- .../provisional/p2/metadata/VersionedId.java | 101 - .../p2/metadata/query/CapabilityQuery.java | 61 - .../provisional/p2/metadata/query/Collector.java | 137 -- .../p2/metadata/query/CompositeQuery.java | 64 - .../p2/metadata/query/CompoundQuery.java | 218 --- .../p2/metadata/query/CompoundQueryable.java | 122 -- .../p2/metadata/query/ContextQuery.java | 61 - .../provisional/p2/metadata/query/IMatchQuery.java | 58 - .../provisional/p2/metadata/query/IQueryable.java | 37 - .../p2/metadata/query/IUPropertyQuery.java | 50 - .../p2/metadata/query/InstallableUnitQuery.java | 103 - .../p2/metadata/query/LatestIUVersionQuery.java | 51 - .../provisional/p2/metadata/query/MatchQuery.java | 105 - .../provisional/p2/metadata/query/Query.java | 50 - .../p2/metadata/query/QueryHelpers.java | 51 - .../provisional/p2/metadata/query/UpdateQuery.java | 38 - .../eclipse/equinox/p2/metadata/IArtifactKey.java | 50 + .../eclipse/equinox/p2/metadata/ICopyright.java | 39 + .../equinox/p2/metadata/IInstallableUnit.java | 293 +++ .../p2/metadata/IInstallableUnitFragment.java | 20 + .../equinox/p2/metadata/IInstallableUnitPatch.java | 51 + .../org/eclipse/equinox/p2/metadata/ILicense.java | 58 + .../equinox/p2/metadata/IProvidedCapability.java | 41 + .../eclipse/equinox/p2/metadata/IRequirement.java | 38 + .../equinox/p2/metadata/IRequirementChange.java | 38 + .../equinox/p2/metadata/ITouchpointData.java | 52 + .../p2/metadata/ITouchpointInstruction.java | 73 + .../equinox/p2/metadata/ITouchpointType.java | 54 + .../equinox/p2/metadata/IUpdateDescriptor.java | 53 + .../equinox/p2/metadata/IVersionFormat.java | 48 + .../eclipse/equinox/p2/metadata/IVersionedId.java | 33 + .../org/eclipse/equinox/p2/metadata/Version.java | 229 +++ .../p2/metadata/VersionFormatException.java | 24 + .../eclipse/equinox/p2/metadata/VersionRange.java | 481 +++++ .../expression/ExpressionParseException.java | 28 + .../p2/metadata/expression/ExpressionUtil.java | 179 ++ .../p2/metadata/expression/IEvaluationContext.java | 39 + .../p2/metadata/expression/IExpression.java | 67 + .../p2/metadata/expression/IExpressionFactory.java | 206 ++ .../p2/metadata/expression/IExpressionParser.java | 26 + .../p2/metadata/expression/IExpressionVisitor.java | 26 + .../p2/metadata/expression/IFilterExpression.java | 48 + .../p2/metadata/expression/IMatchExpression.java | 53 + .../p2/metadata/expression/SimplePattern.java | 159 ++ .../p2/metadata/query/CategoryMemberQuery.java | 56 + .../equinox/p2/metadata/query/CategoryQuery.java | 44 + .../equinox/p2/metadata/query/ExpressionQuery.java | 46 + .../equinox/p2/metadata/query/FragmentQuery.java | 48 + .../equinox/p2/metadata/query/GroupQuery.java | 44 + .../p2/metadata/query/InstallableUnitQuery.java | 106 + .../equinox/p2/metadata/query/PatchQuery.java | 44 + .../org/eclipse/equinox/p2/query/Collector.java | 172 ++ .../eclipse/equinox/p2/query/CompoundQuery.java | 252 +++ .../equinox/p2/query/CompoundQueryable.java | 147 ++ .../org/eclipse/equinox/p2/query/ContextQuery.java | 60 + .../eclipse/equinox/p2/query/ICompositeQuery.java | 27 + .../org/eclipse/equinox/p2/query/IMatchQuery.java | 60 + .../src/org/eclipse/equinox/p2/query/IQuery.java | 46 + .../org/eclipse/equinox/p2/query/IQueryResult.java | 57 + .../org/eclipse/equinox/p2/query/IQueryable.java | 36 + .../org/eclipse/equinox/p2/query/LimitQuery.java | 57 + .../org/eclipse/equinox/p2/query/MatchQuery.java | 107 + .../org/eclipse/equinox/p2/query/PipedQuery.java | 66 + .../org.eclipse.equinox.p2.operations/.classpath | 7 + .../org.eclipse.equinox.p2.operations/.cvsignore | 1 + bundles/org.eclipse.equinox.p2.operations/.project | 34 + .../.settings/org.eclipse.jdt.core.prefs | 329 ++++ .../.settings/org.eclipse.jdt.ui.prefs | 57 + .../.settings/org.eclipse.pde.core.prefs | 4 + .../META-INF/MANIFEST.MF | 35 + .../org.eclipse.equinox.p2.operations/about.html | 28 + .../build.properties | 19 + .../plugin.properties | 12 + .../equinox/internal/p2/operations/Activator.java | 34 + .../internal/p2/operations/DownloadPhaseSet.java | 25 + .../internal/p2/operations/IStatusCodes.java | 51 + .../equinox/internal/p2/operations/Messages.java | 76 + .../internal/p2/operations/PlanAnalyzer.java | 154 ++ .../p2/operations/PlannerResolutionJob.java | 84 + .../internal/p2/operations/ResolutionResult.java | 125 ++ .../internal/p2/operations/SizingPhaseSet.java | 32 + .../internal/p2/operations/messages.properties | 44 + .../equinox/p2/operations/IProfileChangeJob.java | 29 + .../equinox/p2/operations/InstallOperation.java | 145 ++ .../p2/operations/ProfileChangeOperation.java | 353 ++++ .../p2/operations/ProfileModificationJob.java | 114 ++ .../equinox/p2/operations/ProvisioningJob.java | 227 +++ .../equinox/p2/operations/ProvisioningSession.java | 317 +++ .../equinox/p2/operations/RepositoryTracker.java | 275 +++ .../equinox/p2/operations/UninstallOperation.java | 85 + .../org/eclipse/equinox/p2/operations/Update.java | 72 + .../equinox/p2/operations/UpdateOperation.java | 277 +++ .../org/eclipse/equinox/p2/operations/package.html | 33 + .../.classpath | 2 +- .../.settings/org.eclipse.jdt.core.prefs | 14 +- .../META-INF/MANIFEST.MF | 19 +- .../build.properties | 2 + .../internal/p2/reconciler/dropins/Activator.java | 96 +- .../dropins/DropinsRepositoryListener.java | 93 +- .../p2/reconciler/dropins/PlatformXmlListener.java | 49 +- .../p2/reconciler/dropins/ProfileSynchronizer.java | 238 ++- .../.classpath | 2 +- .../.settings/org.eclipse.jdt.core.prefs | 18 +- .../META-INF/MANIFEST.MF | 39 +- .../build.properties | 5 +- .../plugin.xml | 155 +- ...lipse.equinox.p2.repository.tools.verifier.exsd | 109 ++ .../internal/repository/comparator/Annotation.java | 90 - .../repository/comparator/AnnotationComponent.java | 60 - .../comparator/AnnotationComponentValue.java | 277 --- .../comparator/AnnotationDefaultAttribute.java | 35 - .../comparator/AttributeNamesConstants.java | 142 -- .../repository/comparator/CharOperation.java | 602 ------ .../repository/comparator/ClassFileAttribute.java | 47 - .../repository/comparator/ClassFileReader.java | 468 ----- .../repository/comparator/ClassFileStruct.java | 82 - .../comparator/ClassFormatException.java | 59 - .../repository/comparator/CodeAttribute.java | 1114 ----------- .../repository/comparator/ConstantPool.java | 104 - .../comparator/ConstantPoolConstant.java | 39 - .../repository/comparator/ConstantPoolEntry.java | 396 ---- .../comparator/ConstantValueAttribute.java | 37 - .../comparator/DefaultBytecodeVisitor.java | 2071 -------------------- .../repository/comparator/Disassembler.java | 1149 ----------- .../comparator/EnclosingMethodAttribute.java | 101 - .../repository/comparator/ExceptionAttribute.java | 61 - .../repository/comparator/ExceptionTableEntry.java | 70 - .../internal/repository/comparator/FieldInfo.java | 170 -- .../repository/comparator/IModifierConstants.java | 104 - .../repository/comparator/IOpcodeMnemonics.java | 220 --- .../comparator/InnerClassesAttribute.java | 56 - .../comparator/InnerClassesAttributeEntry.java | 100 - .../repository/comparator/JarComparator.java | 17 +- .../comparator/MD5ArtifactComparator.java | 44 + .../internal/repository/comparator/Messages.java | 107 - .../internal/repository/comparator/MethodInfo.java | 213 -- .../repository/comparator/OpcodeStringValues.java | 222 --- .../repository/comparator/ParameterAnnotation.java | 63 - .../RuntimeInvisibleAnnotationsAttribute.java | 56 - ...timeInvisibleParameterAnnotationsAttribute.java | 56 - .../RuntimeVisibleAnnotationsAttribute.java | 56 - ...untimeVisibleParameterAnnotationsAttribute.java | 56 - .../internal/repository/comparator/Signature.java | 1163 ----------- .../repository/comparator/SignatureAttribute.java | 42 - .../repository/comparator/SourceFileAttribute.java | 49 - .../repository/comparator/TypeConstants.java | 153 -- .../p2/internal/repository/comparator/Utility.java | 689 ------- .../repository/comparator/java/Annotation.java | 90 + .../comparator/java/AnnotationComponent.java | 60 + .../comparator/java/AnnotationComponentValue.java | 277 +++ .../java/AnnotationDefaultAttribute.java | 35 + .../comparator/java/AttributeNamesConstants.java | 142 ++ .../repository/comparator/java/CharOperation.java | 602 ++++++ .../comparator/java/ClassFileAttribute.java | 47 + .../comparator/java/ClassFileReader.java | 468 +++++ .../comparator/java/ClassFileStruct.java | 82 + .../comparator/java/ClassFormatException.java | 59 + .../repository/comparator/java/CodeAttribute.java | 1114 +++++++++++ .../repository/comparator/java/ConstantPool.java | 104 + .../comparator/java/ConstantPoolConstant.java | 39 + .../comparator/java/ConstantPoolEntry.java | 396 ++++ .../comparator/java/ConstantValueAttribute.java | 37 + .../comparator/java/DefaultBytecodeVisitor.java | 2071 ++++++++++++++++++++ .../repository/comparator/java/Disassembler.java | 1145 +++++++++++ .../comparator/java/EnclosingMethodAttribute.java | 101 + .../comparator/java/ExceptionAttribute.java | 61 + .../comparator/java/ExceptionTableEntry.java | 70 + .../repository/comparator/java/FieldInfo.java | 170 ++ .../comparator/java/IModifierConstants.java | 104 + .../comparator/java/IOpcodeMnemonics.java | 220 +++ .../comparator/java/InnerClassesAttribute.java | 56 + .../java/InnerClassesAttributeEntry.java | 100 + .../repository/comparator/java/Messages.java | 107 + .../repository/comparator/java/MethodInfo.java | 213 ++ .../comparator/java/OpcodeStringValues.java | 222 +++ .../comparator/java/ParameterAnnotation.java | 63 + .../java/RuntimeInvisibleAnnotationsAttribute.java | 56 + ...timeInvisibleParameterAnnotationsAttribute.java | 56 + .../java/RuntimeVisibleAnnotationsAttribute.java | 56 + ...untimeVisibleParameterAnnotationsAttribute.java | 56 + .../repository/comparator/java/Signature.java | 1163 +++++++++++ .../comparator/java/SignatureAttribute.java | 42 + .../comparator/java/SourceFileAttribute.java | 49 + .../repository/comparator/java/TypeConstants.java | 153 ++ .../repository/comparator/java/Utility.java | 689 +++++++ .../repository/comparator/java/messages.properties | 98 + .../repository/comparator/messages.properties | 98 - .../repository/mirroring/FileMirrorLog.java | 125 ++ .../repository/mirroring/IArtifactMirrorLog.java | 26 + .../internal/repository/mirroring/Mirroring.java | 291 +++ .../repository/mirroring/XMLMirrorLog.java | 166 ++ .../repository/tools/AbstractApplication.java | 116 +- .../p2/internal/repository/tools/Activator.java | 15 +- .../tools/ArtifactRepositoryValidator.java | 85 + .../tools/CompositeRepositoryApplication.java | 65 +- .../p2/internal/repository/tools/Messages.java | 18 +- .../repository/tools/MirrorApplication.java | 213 +- .../tools/RecreateRepositoryApplication.java | 73 +- .../internal/repository/tools/Repo2Runnable.java | 98 +- .../tools/RepositoryAnalyzerApplication.java | 68 + .../repository/tools/RepositoryDescriptor.java | 2 +- .../internal/repository/tools/SlicingOptions.java | 10 +- .../tools/analyzer/CopyrightAnalyzer.java | 43 + .../tools/analyzer/HostCheckAnalyzer.java | 54 + .../repository/tools/analyzer/IUCounting.java | 57 + .../repository/tools/analyzer/LicenseAnalyzer.java | 51 + .../tools/analyzer/UniqueIUAnalyzer.java | 38 + .../tools/analyzer/UnzipFeatureJarAnalyzer.java | 49 + .../repository/tools/analyzer/VersionAnalyzer.java | 43 + .../internal/repository/tools/messages.properties | 23 +- .../p2/repository/tools/analyzer/IIUAnalyzer.java | 38 + .../p2/repository/tools/analyzer/IUAnalyzer.java | 46 + .../tools/analyzer/RepositoryAnalyzer.java | 72 + .../comparator/ArtifactComparatorFactory.java | 52 + .../tools/comparator/IArtifactComparator.java | 35 + .../tools/tasks/AbstractRepositoryTask.java | 49 +- .../repository/tools/tasks/AntMirrorLog.java | 106 + .../tools/tasks/CompositeRepositoryTask.java | 46 +- .../CreateCompositeArtifactRepositoryTask.java | 121 ++ .../repository/tools/tasks/IUDescription.java | 40 +- .../tools/tasks/MirrorArtifactsTask.java | 180 ++ .../repository/tools/tasks/MirrorMetadataTask.java | 95 + .../repository/tools/tasks/MirrorTask.java | 7 +- .../repository/tools/tasks/ProcessRepoTask.java | 15 +- .../repository/tools/tasks/RemoveIUTask.java | 50 +- .../repository/tools/tasks/Repo2RunnableTask.java | 11 +- .../repository/tools/tasks/RepositoryFileSet.java | 5 +- .../repository/tools/tasks/RepositoryList.java | 9 +- .../repository/tools/tasks/SlicingOption.java | 6 +- .../repository/tools/tasks/ValidateTask.java | 73 + .../org.eclipse.equinox.p2.repository/.classpath | 2 +- .../.settings/org.eclipse.jdt.core.prefs | 14 +- .../META-INF/MANIFEST.MF | 27 +- .../build.properties | 2 + .../internal/p2/persistence/CompositeParser.java | 28 +- .../p2/persistence/CompositeRepositoryIO.java | 3 +- .../p2/persistence/CompositeRepositoryState.java | 6 +- .../internal/p2/persistence/CompositeWriter.java | 5 +- .../equinox/internal/p2/persistence/XMLParser.java | 9 +- .../equinox/internal/p2/persistence/XMLWriter.java | 19 +- .../equinox/internal/p2/repository/Activator.java | 19 +- .../internal/p2/repository/CacheManager.java | 34 +- .../internal/p2/repository/Credentials.java | 39 +- .../internal/p2/repository/ProgressStatistics.java | 39 +- .../internal/p2/repository/RepositoryStatus.java | 3 +- .../p2/repository/RepositoryStatusHelper.java | 5 +- .../p2/repository/RepositoryTransport.java | 3 +- .../helpers/AbstractRepositoryManager.java | 178 +- .../p2/repository/helpers/DebugHelper.java | 9 +- .../p2/repository/helpers/RepositoryHelper.java | 4 +- .../p2/repository/ICompositeRepository.java | 41 - .../provisional/p2/repository/IRepository.java | 188 -- .../p2/repository/IRepositoryManager.java | 211 -- .../p2/repository/RepositoryCreationException.java | 21 - .../provisional/p2/repository/RepositoryEvent.java | 1 + .../spi/p2/repository/AbstractRepository.java | 134 -- .../p2/repository/ICompositeRepository.java | 44 + .../eclipse/equinox/p2/repository/IRepository.java | 190 ++ .../equinox/p2/repository/IRepositoryManager.java | 217 ++ .../artifact/ArtifactDescriptorQuery.java | 101 + .../p2/repository/artifact/ArtifactKeyQuery.java | 81 + .../repository/artifact/IArtifactDescriptor.java | 109 ++ .../repository/artifact/IArtifactRepository.java | 142 ++ .../artifact/IArtifactRepositoryManager.java | 150 ++ .../p2/repository/artifact/IArtifactRequest.java | 44 + .../artifact/IFileArtifactRepository.java | 35 + .../artifact/IProcessingStepDescriptor.java | 45 + .../artifact/spi/AbstractArtifactRepository.java | 89 + .../artifact/spi/ArtifactDescriptor.java | 145 ++ .../artifact/spi/ArtifactRepositoryFactory.java | 99 + .../artifact/spi/ProcessingStepDescriptor.java | 103 + .../repository/metadata/IMetadataRepository.java | 78 + .../metadata/IMetadataRepositoryManager.java | 157 ++ .../metadata/spi/AbstractMetadataRepository.java | 74 + .../metadata/spi/MetadataRepositoryFactory.java | 119 ++ .../p2/repository/spi/AbstractRepository.java | 136 ++ .../p2/repository/spi/RepositoryReference.java | 58 + .../META-INF/MANIFEST.MF | 1 - .../tests/artifact/optimizers/JBDiffStepTest.java | 17 +- .../artifact/optimizers/JBDiffZipStepTest.java | 17 +- .../artifact/optimizers/JarDeltaOptimizerTest.java | 19 +- .../processors/ArtifactRepositoryMock.java | 4 +- .../tests/artifact/processors/JBPatchStepTest.java | 17 +- .../artifact/processors/JBPatchZipStepTest.java | 17 +- .../artifact/processors/JarDeltaProcessorTest.java | 17 +- .../All p2 UI tests.launch | 16 +- .../META-INF/MANIFEST.MF | 7 +- .../p2/tests/ui/AbstractProvisioningUITest.java | 75 +- .../p2/tests/ui/actions/ElementUtilsTest.java | 57 +- .../p2/tests/ui/actions/InstallActionTest.java | 7 +- .../ui/actions/ProfileModificationActionTest.java | 3 +- .../RemoveColocatedRepositoryActionTest.java | 8 +- .../p2/tests/ui/actions/UninstallActionTest.java | 7 +- .../p2/tests/ui/actions/UpdateActionTest.java | 7 +- .../p2/tests/ui/dialogs/IUPropertyPagesTest.java | 12 +- .../p2/tests/ui/dialogs/InstallWizardTest.java | 117 +- .../ui/dialogs/InstallationHistoryPageTest.java | 6 +- .../ui/dialogs/InstalledSoftwarePageTest.java | 4 +- .../ui/dialogs/RepositoryManipulationPageTest.java | 2 +- .../p2/tests/ui/dialogs/UninstallWizardTest.java | 57 +- .../p2/tests/ui/dialogs/UpdateWizardTest.java | 157 +- .../equinox/p2/tests/ui/dialogs/WizardTest.java | 15 +- .../AddColocatedRepositoryOperationTest.java | 50 - .../ui/operations/AddProfileOperationTest.java | 55 - .../equinox/p2/tests/ui/operations/AllTests.java | 4 - .../tests/ui/operations/ProvisioningUtilTest.java | 60 - .../RemoveColocatedRepositoryOperationTest.java | 50 - .../ui/operations/RemoveProfilesOperationTest.java | 67 - .../equinox/p2/tests/ui/operations/SizingTest.java | 52 +- .../p2/tests/ui/planning/UpdatePlanning.java | 104 +- .../p2/tests/ui/query/AbstractQueryTest.java | 28 +- .../equinox/p2/tests/ui/query/AllTests.java | 2 +- .../tests/ui/query/AnyRequiredCapabilityTest.java | 36 +- .../p2/tests/ui/query/AvailableIUWrapperTest.java | 21 +- .../tests/ui/query/CategoryElementWrapperTest.java | 12 +- .../p2/tests/ui/query/IUPropertyUtilsTest.java | 144 -- .../query/LatestIUVersionElementWrapperTest.java | 53 +- .../p2/tests/ui/query/MockQueryProvider.java | 18 +- .../p2/tests/ui/query/QueryDescriptorTest.java | 15 +- .../QueryableArtifactRepositoryManagerTest.java | 17 +- .../QueryableMetadataRepositoryManagerTest.java | 107 +- .../p2/tests/ui/query/TranslationSupportTests.java | 159 ++ .../ui/repohandling/SiteImportExportTest.java | 2 +- .../.settings/org.eclipse.jdt.core.prefs | 2 +- .../META-INF/MANIFEST.MF | 5 +- .../p2/tests/verifier/VerifierApplication.java | 10 +- .../.externalToolBuilders/New_Builder.launch | 11 + .../.settings/org.eclipse.jdt.core.prefs | 4 +- .../All p2 Tests.launch | 8 +- .../META-INF/MANIFEST.MF | 37 +- .../org.eclipse.equinox.p2.tests/build.properties | 4 +- .../rawData/Test Data Generator.launch | 5 +- .../p2/tests/AbstractAntProvisioningTest.java | 41 +- .../equinox/p2/tests/AbstractProvisioningTest.java | 394 ++-- .../tests/AbstractWrappedArtifactRepository.java | 23 +- .../eclipse/equinox/p2/tests/AutomatedTests.java | 2 + .../p2/tests/FailingMetadataRepositoryFactory.java | 6 +- .../eclipse/equinox/p2/tests/IUPropertyUtils.java | 231 --- .../eclipse/equinox/p2/tests/MockQueryable.java | 6 +- .../eclipse/equinox/p2/tests/TestActivator.java | 6 +- .../equinox/p2/tests/TestArtifactRepository.java | 28 +- .../equinox/p2/tests/TestMetadataRepository.java | 22 +- .../p2/tests/ant/CompositeRepositoryTaskTest.java | 12 +- .../equinox/p2/tests/ant/MirrorTaskTest.java | 107 +- .../p2/tests/ant/Repo2RunnableTaskTests.java | 43 +- .../equinox/p2/tests/ant/RepoTasksTests.java | 15 +- .../processors/ArtifactRepositoryMock.java | 4 +- .../repository/ArtifactOutputStreamTest.java | 10 +- .../repository/ArtifactRepositoryManagerTest.java | 46 +- .../ArtifactRepositoryMissingSizeData.java | 38 +- ...ArtifactRepositoryWithReferenceDescriptors.java | 20 +- .../p2/tests/artifact/repository/Bug252308.java | 14 +- .../p2/tests/artifact/repository/Bug265577.java | 33 +- .../CompositeArtifactRepositoryTest.java | 152 +- .../p2/tests/artifact/repository/CorruptedJar.java | 11 +- .../artifact/repository/FoldersRepositoryTest.java | 26 +- .../repository/JarURLArtifactRepositoryTest.java | 12 +- .../p2/tests/artifact/repository/MD5Tests.java | 32 +- .../artifact/repository/MirrorRequestTest.java | 46 +- .../repository/SimpleArtifactRepositoryTest.java | 151 +- .../artifact/repository/processing/Adder.java | 6 +- .../repository/processing/ByteShifter.java | 8 +- .../artifact/repository/processing/Counter.java | 8 +- .../artifact/repository/processing/Multiplier.java | 6 +- .../processing/ProcessingStepHandlerTest.java | 35 +- .../equinox/p2/tests/core/AggregateQueryTest.java | 202 +- .../equinox/p2/tests/core/CollectorTest.java | 51 +- .../p2/tests/core/CompoundQueryableTest.java | 240 +-- .../p2/tests/core/PropertyLookupQuery1.java | 2 +- .../p2/tests/core/PropertyLookupQuery2.java | 6 +- .../eclipse/equinox/p2/tests/core/QueryTest.java | 150 +- .../p2/tests/director/AutomatedDirectorTest.java | 32 +- .../equinox/p2/tests/director/Bug203637.java | 8 +- .../equinox/p2/tests/director/DirectorAppTest.java | 27 +- .../p2/tests/director/DirectorApplicationTest.java | 31 +- .../p2/tests/director/OperationGenerationTest.java | 270 +-- .../equinox/p2/tests/director/OracleTest.java | 18 +- .../equinox/p2/tests/director/OracleTest2.java | 17 +- .../equinox/p2/tests/director/ReplacePlanTest.java | 26 +- .../equinox/p2/tests/director/RollbackTest.java | 72 +- .../equinox/p2/tests/director/SingletonTest.java | 18 +- .../equinox/p2/tests/director/UninstallTest.java | 4 +- .../equinox/p2/tests/director/UpdateTest.java | 23 +- .../directorywatcher/ProfileSynchronizerTest.java | 8 +- .../directorywatcher/RepositoryListenerTest.java | 17 +- .../directorywatcher/TestRepositoryWatcher.java | 22 +- .../equinox/p2/tests/engine/ActionManagerTest.java | 11 +- .../p2/tests/engine/CertificateCheckerTest.java | 37 +- .../p2/tests/engine/DownloadManagerTest.java | 36 +- .../equinox/p2/tests/engine/EngineTest.java | 254 +-- .../p2/tests/engine/InstructionParserTest.java | 55 +- .../ParameterizedProvisioningActionTest.java | 2 +- .../p2/tests/engine/PhaseApplicabilityTest.java | 32 +- .../equinox/p2/tests/engine/PhaseSetTest.java | 5 +- .../eclipse/equinox/p2/tests/engine/PhaseTest.java | 45 +- .../engine/ProfileMetadataRepositoryTest.java | 40 +- .../p2/tests/engine/ProfilePreferencesTest.java | 42 +- .../p2/tests/engine/ProfileRegistryTest.java | 53 +- .../equinox/p2/tests/engine/ProfileTest.java | 266 +-- .../tests/engine/SurrogateProfileHandlerTest.java | 41 +- .../p2/tests/engine/TouchpointManagerTest.java | 3 +- .../equinox/p2/tests/engine/TouchpointTest.java | 18 +- ...nsionLocationArtifactRepositoryFactoryTest.java | 14 +- ...nsionLocationMetadataRepositoryFactoryTest.java | 17 +- .../eclipse/equinox/p2/tests/full/AllTests.java | 4 +- .../equinox/p2/tests/full/DirectorTest.java | 54 +- .../eclipse/equinox/p2/tests/full/End2EndTest.java | 116 +- .../equinox/p2/tests/full/RepoValidator.java | 27 +- .../p2/tests/generator/EclipseSDK33Test.java | 11 +- .../equinox/p2/tests/generator/FeatureToIU.java | 2 +- .../p2/tests/generator/PatchIUGeneration.java | 33 +- .../p2/tests/generator/TestGeneratorInfo.java | 6 +- .../installer/InstallDescriptionParserTest.java | 9 +- .../p2/tests/metadata/ArtifactKeyParsingTest.java | 18 +- .../p2/tests/metadata/FragmentMethodTest.java | 78 +- .../equinox/p2/tests/metadata/FragmentTest.java | 55 +- .../p2/tests/metadata/IUPatchPersistenceTest.java | 67 +- .../p2/tests/metadata/IUPersistenceTest.java | 113 +- .../p2/tests/metadata/InstallableUnitTest.java | 9 +- .../equinox/p2/tests/metadata/LatestIUTest.java | 32 +- .../equinox/p2/tests/metadata/LicenseTest.java | 6 +- .../tests/metadata/MultipleIUAndFragmentTest.java | 19 +- .../p2/tests/metadata/ProvidedCapabilityTest.java | 6 +- .../p2/tests/metadata/expression/AllTests.java | 27 + .../tests/metadata/expression/ExpressionTest.java | 67 + .../p2/tests/metadata/expression/FilterTest.java | 267 +++ .../p2/tests/metadata/repository/AuthTest.java | 6 +- .../CompositeMetadataRepositoryTest.java | 79 +- .../tests/metadata/repository/HttpStatusTest.java | 6 +- .../repository/JarURLMetadataRepositoryTest.java | 32 +- .../repository/LocalMetadataRepositoryTest.java | 41 +- .../MetadataRepositoryManagerExceptionsTest.java | 11 +- .../repository/MetadataRepositoryManagerTest.java | 43 +- .../p2/tests/metadata/repository/NoFailOver.java | 2 +- .../metadata/repository/ResumeDownloadTest.java | 6 +- .../repository/SPIMetadataRepositoryTest.java | 283 +-- .../p2/tests/metadata/repository/TimeoutTest.java | 6 +- .../mirror/ArtifactMirrorApplicationTest.java | 144 +- .../mirror/ArtifactRepositoryCleanupTest.java | 6 +- .../mirror/MetadataMirrorApplicationTest.java | 84 +- .../mirror/MetadataRepositoryCleanupTest.java | 6 +- .../mirror/NewMirrorApplicationArtifactTest.java | 81 +- .../mirror/NewMirrorApplicationMetadataTest.java | 32 +- .../p2/tests/omniVersion/CommonPatternsTest.java | 26 +- .../equinox/p2/tests/omniVersion/FormatATest.java | 3 +- .../p2/tests/omniVersion/FormatArrayTest.java | 3 +- .../equinox/p2/tests/omniVersion/FormatDTest.java | 3 +- .../equinox/p2/tests/omniVersion/FormatNTest.java | 3 +- .../equinox/p2/tests/omniVersion/FormatPTest.java | 3 +- .../p2/tests/omniVersion/FormatProcessingTest.java | 3 +- .../equinox/p2/tests/omniVersion/FormatQTest.java | 3 +- .../equinox/p2/tests/omniVersion/FormatRTest.java | 3 +- .../p2/tests/omniVersion/FormatRangeTest.java | 6 +- .../equinox/p2/tests/omniVersion/FormatSTest.java | 3 +- .../equinox/p2/tests/omniVersion/FormatTest.java | 3 +- .../p2/tests/omniVersion/IntersectionTest.java | 5 +- .../p2/tests/omniVersion/MultiplicityTest.java | 3 +- .../p2/tests/omniVersion/OSGiRangeTest.java | 18 +- .../p2/tests/omniVersion/OSGiVersionTest.java | 4 +- .../p2/tests/omniVersion/PerformanceTest.java | 13 +- .../equinox/p2/tests/omniVersion/RawRangeTest.java | 4 +- .../omniVersion/RawRangeWithOriginalTest.java | 19 +- .../p2/tests/omniVersion/RawVersionTest.java | 614 +++--- .../p2/tests/omniVersion/RawWithOriginalTest.java | 6 +- .../p2/tests/omniVersion/VersionTesting.java | 54 +- .../perf/MetadataRepositoryPerformanceTest.java | 69 + .../p2/tests/perf/ProvisioningPerformanceTest.java | 31 + .../p2/tests/perf/PublisherPerformanceTest.java | 53 + .../equinox/p2/tests/planner/AbsolutePlanTest.java | 80 + .../p2/tests/planner/ActualChangeRequestTest.java | 29 +- .../p2/tests/planner/ActualChangeRequestTest2.java | 37 +- .../equinox/p2/tests/planner/AddIUProperty.java | 50 +- .../p2/tests/planner/AdditionalConstraints.java | 27 +- .../planner/AgentPlanTestInExternalInstance.java | 151 +- ...tPlanTestInExternalInstanceForCohostedMode.java | 150 +- .../planner/AgentPlanTestInRunningInstance.java | 153 +- .../equinox/p2/tests/planner/AllOptional.java | 30 +- .../eclipse/equinox/p2/tests/planner/AllOrbit.java | 55 +- .../eclipse/equinox/p2/tests/planner/AllTests.java | 4 + .../equinox/p2/tests/planner/AnotherSingleton.java | 20 +- .../equinox/p2/tests/planner/Bug207319.java | 21 +- .../equinox/p2/tests/planner/Bug249605.java | 44 +- .../equinox/p2/tests/planner/Bug252638.java | 18 +- .../equinox/p2/tests/planner/Bug252682.java | 24 +- .../p2/tests/planner/Bug254481dataSet1.java | 23 +- .../p2/tests/planner/Bug254481dataSet2.java | 21 +- .../equinox/p2/tests/planner/Bug255984.java | 36 +- .../equinox/p2/tests/planner/Bug262580.java | 6 +- .../equinox/p2/tests/planner/Bug270656.java | 22 +- .../equinox/p2/tests/planner/Bug270683.java | 25 +- .../equinox/p2/tests/planner/Bug271067.java | 55 +- .../equinox/p2/tests/planner/Bug271954.java | 33 +- .../equinox/p2/tests/planner/Bug272251.java | 23 +- .../equinox/p2/tests/planner/Bug278668.java | 34 +- .../equinox/p2/tests/planner/DependencyOnSelf.java | 10 +- .../p2/tests/planner/DisabledExplanation.java | 18 +- .../equinox/p2/tests/planner/DropinsScenario.java | 26 +- .../p2/tests/planner/ExplanationDeepConflict.java | 29 +- .../ExplanationForOptionalDependencies.java | 21 +- .../planner/ExplanationForPartialInstallation.java | 34 +- .../p2/tests/planner/ExplanationLargeConflict.java | 45 +- .../ExplanationSeveralConflictingRoots.java | 32 +- .../planner/FindingPatchesThroughUpdates.java | 38 +- .../p2/tests/planner/GreedyRequirement.java | 20 +- .../equinox/p2/tests/planner/IUProperties.java | 32 +- .../p2/tests/planner/IUPropertyRemoval.java | 34 +- .../equinox/p2/tests/planner/IUWithFilter.java | 14 +- .../equinox/p2/tests/planner/IUWithFilter2.java | 10 +- .../p2/tests/planner/InclusionRuleTest.java | 109 +- .../p2/tests/planner/InclusionRuleTest2.java | 41 +- .../equinox/p2/tests/planner/MinimalInstall.java | 16 +- .../p2/tests/planner/MissingDependency.java | 23 +- .../p2/tests/planner/MissingDependency2.java | 18 +- .../p2/tests/planner/MissingDependency3.java | 18 +- .../tests/planner/MissingNonGreedyRequirement.java | 25 +- .../planner/MissingNonGreedyRequirement2.java | 23 +- .../equinox/p2/tests/planner/MissingOptional.java | 18 +- .../MissingOptionalNonGreedyRequirement.java | 18 +- .../planner/MissingOptionalWithDependencies.java | 18 +- .../planner/MissingOptionalWithDependencies2.java | 22 +- .../planner/MissingOptionalWithDependencies3.java | 22 +- .../equinox/p2/tests/planner/MultipleProvider.java | 20 +- .../p2/tests/planner/MultipleSingleton.java | 68 +- .../equinox/p2/tests/planner/NegationTesting.java | 127 +- .../equinox/p2/tests/planner/NoRequirements.java | 10 +- .../equinox/p2/tests/planner/NonMinimalState.java | 36 +- .../equinox/p2/tests/planner/NonMinimalState2.java | 33 +- .../equinox/p2/tests/planner/ORTesting.java | 150 -- .../p2/tests/planner/PP2ShouldFailToInstall.java | 24 +- .../p2/tests/planner/PatchFailingToInstall.java | 24 +- .../equinox/p2/tests/planner/PatchTest1.java | 20 +- .../equinox/p2/tests/planner/PatchTest10.java | 32 +- .../equinox/p2/tests/planner/PatchTest11.java | 21 +- .../equinox/p2/tests/planner/PatchTest12.java | 28 +- .../equinox/p2/tests/planner/PatchTest13.java | 24 +- .../equinox/p2/tests/planner/PatchTest1b.java | 22 +- .../equinox/p2/tests/planner/PatchTest1c.java | 24 +- .../equinox/p2/tests/planner/PatchTest2.java | 53 +- .../equinox/p2/tests/planner/PatchTest3.java | 40 +- .../equinox/p2/tests/planner/PatchTest4.java | 42 +- .../equinox/p2/tests/planner/PatchTest5.java | 26 +- .../equinox/p2/tests/planner/PatchTest6.java | 38 +- .../equinox/p2/tests/planner/PatchTest7.java | 32 +- .../equinox/p2/tests/planner/PatchTest7b.java | 32 +- .../equinox/p2/tests/planner/PatchTest8.java | 30 +- .../equinox/p2/tests/planner/PatchTest9.java | 32 +- .../p2/tests/planner/PatchTestMultiplePatch.java | 26 +- .../p2/tests/planner/PatchTestMultiplePatch2.java | 78 + .../p2/tests/planner/PatchTestMultiplePatch3.java | 78 + .../p2/tests/planner/PatchTestOptional.java | 22 +- .../p2/tests/planner/PatchTestOptional2.java | 20 +- .../p2/tests/planner/PatchTestOptional3.java | 20 +- .../p2/tests/planner/PatchTestUninstall.java | 24 +- .../equinox/p2/tests/planner/PatchTestUpdate.java | 34 +- .../equinox/p2/tests/planner/PatchTestUpdate2.java | 28 +- .../equinox/p2/tests/planner/PatchTestUpdate3.java | 28 +- .../equinox/p2/tests/planner/PatchTestUpdate4.java | 26 +- .../equinox/p2/tests/planner/PatchTestUpdate5.java | 24 +- .../p2/tests/planner/PermissiveSlicerTest.java | 76 +- .../tests/planner/ProvisioningPlanQueryTest.java | 28 +- .../equinox/p2/tests/planner/SDKPatchingTest1.java | 23 +- .../equinox/p2/tests/planner/SDKPatchingTest2.java | 31 +- .../equinox/p2/tests/planner/SWTFragment.java | 34 +- .../tests/planner/SeveralOptionalDependencies.java | 22 +- .../planner/SeveralOptionalDependencies2.java | 22 +- .../planner/SeveralOptionalDependencies3.java | 16 +- .../planner/SeveralOptionalDependencies4.java | 22 +- .../planner/SeveralOptionalDependencies5.java | 22 +- .../p2/tests/planner/SimpleOptionalTest.java | 18 +- .../p2/tests/planner/SimpleOptionalTest2.java | 34 +- .../p2/tests/planner/SimpleOptionalTest3.java | 30 +- .../p2/tests/planner/SimpleOptionalTest4.java | 24 +- .../equinox/p2/tests/planner/SimpleSingleton.java | 24 +- .../tests/planner/SimulatedSharedInstallTest.java | 86 +- .../p2/tests/planner/TopLevelFilterTest.java | 6 +- .../p2/tests/planner/TwoVersionsOfWSDL.java | 22 +- .../p2/tests/planner/UninstallEverything.java | 13 +- .../equinox/p2/tests/planner/UpdateQueryTest.java | 49 + .../p2/tests/publisher/TestArtifactRepository.java | 65 +- .../actions/AbstractPublisherActionTest.java | 54 +- .../actions/AccumulateConfigDataActionTest.java | 14 +- .../p2/tests/publisher/actions/ActionTest.java | 44 +- .../publisher/actions/AdviceFileParserTest.java | 271 +-- .../p2/tests/publisher/actions/AdviceMatcher.java | 2 +- .../tests/publisher/actions/BundlesActionTest.java | 82 +- .../publisher/actions/ConfigCUsActionTest.java | 33 +- .../publisher/actions/DefaultCUsActionTest.java | 11 +- .../actions/EquinoxExecutableActionTest.java | 51 +- .../actions/EquinoxLauncherCUActionTest.java | 27 +- .../publisher/actions/FeaturesActionTest.java | 57 +- .../p2/tests/publisher/actions/JREActionTest.java | 35 +- .../actions/LocalUpdateSiteActionTest.java | 13 +- .../tests/publisher/actions/LocalizationTests.java | 340 ++-- .../tests/publisher/actions/MD5GenerationTest.java | 16 +- .../tests/publisher/actions/ProductActionTest.java | 81 +- .../publisher/actions/ProductActionTestMac.java | 3 +- .../actions/ProductActionWithAdviceFileTest.java | 40 +- .../publisher/actions/ProductFileAdviceTest.java | 5 +- .../tests/publisher/actions/ProductFileTest.java | 15 +- .../publisher/actions/RootFilesActionTest.java | 14 +- .../tests/publisher/actions/RootIUActionTest.java | 37 +- .../tests/publisher/actions/VersionAdviceTest.java | 46 +- .../org/eclipse/equinox/p2/tests/ql/AllTests.java | 28 + .../eclipse/equinox/p2/tests/ql/EvaluatorTest.java | 338 ++++ .../equinox/p2/tests/ql/PerformanceTest.java | 187 ++ .../p2/tests/ql/TestQueryReimplementation.java | 146 ++ .../reconciler/dropins/AbstractReconcilerTest.java | 25 +- .../p2/tests/reconciler/dropins/BasicTests.java | 2 +- .../reconciler/dropins/ConfigurationTests.java | 2 +- .../equinox/p2/tests/repository/NTLMTest.java | 6 +- .../equinox/p2/tests/repository/TimeoutTest.java | 2 +- .../eclipse/AddJVMArgumentActionTest.java | 7 +- .../eclipse/AddProgramArgumentActionTest.java | 35 +- .../eclipse/AddRepositoryActionTest.java | 63 +- .../eclipse/AddSourceBundleActionTest.java | 17 +- .../p2/tests/touchpoint/eclipse/AllTests.java | 4 +- .../touchpoint/eclipse/CheckTrustActionTest.java | 19 +- .../tests/touchpoint/eclipse/ChmodActionTest.java | 25 +- .../touchpoint/eclipse/CollectActionTest.java | 26 +- .../touchpoint/eclipse/EclipseTouchpointTest.java | 60 +- .../eclipse/InstallBundleActionTest.java | 17 +- .../eclipse/InstallFeatureActionTest.java | 30 +- .../eclipse/JVMArgumentActionLogicTest.java | 7 +- .../tests/touchpoint/eclipse/LinkActionTest.java | 25 +- .../touchpoint/eclipse/MarkStartedActionTest.java | 27 +- .../eclipse/RemoveJVMArgumentActionTest.java | 7 +- .../eclipse/RemoveProgramArgumentActionTest.java | 27 +- .../eclipse/RemoveRepositoryActionTest.java | 4 +- .../eclipse/RemoveSourceBundleActionTest.java | 17 +- .../SetFrameworkDependentPropertyActionTest.java | 7 +- .../SetFrameworkIndependentPropertyActionTest.java | 7 +- .../eclipse/SetLauncherNameActionTest.java | 13 +- .../eclipse/SetProgramPropertyActionTest.java | 25 +- .../eclipse/SetStartLevelActionTest.java | 27 +- .../eclipse/UninstallBundleActionTest.java | 17 +- .../eclipse/UninstallFeatureActionTest.java | 21 +- .../p2/tests/touchpoint/eclipse/UtilTest.java | 22 +- .../tests/touchpoint/natives/ChmodActionTest.java | 4 +- .../touchpoint/natives/CleanupzipActionTest.java | 12 +- .../touchpoint/natives/CollectActionTest.java | 24 +- .../tests/touchpoint/natives/CopyActionTest.java | 10 +- .../tests/touchpoint/natives/LinkActionTest.java | 4 +- .../tests/touchpoint/natives/MkdirActionTest.java | 4 +- .../touchpoint/natives/NativeTouchpointTest.java | 4 +- .../tests/touchpoint/natives/RemoveActionTest.java | 4 +- .../tests/touchpoint/natives/RmdirActionTest.java | 4 +- .../tests/touchpoint/natives/UnzipActionTest.java | 14 +- .../p2/tests/updatechecker/UpdateCheckerTest.java | 17 +- .../p2/tests/updatesite/CategoryXMLActionTest.java | 13 +- .../p2/tests/updatesite/DoesNotCacheStaleData.java | 18 +- .../p2/tests/updatesite/LocalUpdatesiteTest.java | 14 +- .../p2/tests/updatesite/SiteXMLActionTest.java | 22 +- .../p2/tests/updatesite/UpdateSiteTest.java | 93 +- .../.settings/org.eclipse.equinox.p2.ui.sdk.prefs | 4 + .../TestProfile.profile/1345.profile.gz | 0 .../TestProfile.profile/1345.profile.gz | 0 .../META-INF/MANIFEST.MF | 3 +- .../equinox/p2/testserver/SecureAction.java | 6 +- .../.classpath | 2 +- .../.settings/org.eclipse.jdt.core.prefs | 14 +- .../META-INF/MANIFEST.MF | 28 +- .../build.properties | 2 + .../eclipse/AggregatedBundleRepository.java | 57 +- .../p2/touchpoint/eclipse/DirectorUtil.java | 6 +- .../touchpoint/eclipse/EclipseMarkSetProvider.java | 84 +- .../p2/touchpoint/eclipse/EclipseTouchpoint.java | 72 +- .../p2/touchpoint/eclipse/LazyManipulator.java | 16 +- .../eclipse/PlatformConfigurationWrapper.java | 16 +- .../p2/touchpoint/eclipse/PublisherUtil.java | 7 +- .../p2/touchpoint/eclipse/SourceManipulator.java | 15 +- .../internal/p2/touchpoint/eclipse/Util.java | 85 +- .../eclipse/actions/ActionConstants.java | 1 + .../eclipse/actions/AddJVMArgumentAction.java | 15 +- .../eclipse/actions/AddProgramArgumentAction.java | 6 +- .../eclipse/actions/AddRepositoryAction.java | 25 +- .../eclipse/actions/AddSourceBundleAction.java | 29 +- .../eclipse/actions/CheckTrustAction.java | 28 +- .../p2/touchpoint/eclipse/actions/ChmodAction.java | 11 +- .../touchpoint/eclipse/actions/CollectAction.java | 58 +- .../eclipse/actions/InstallBundleAction.java | 32 +- .../eclipse/actions/InstallFeatureAction.java | 29 +- .../p2/touchpoint/eclipse/actions/LinkAction.java | 6 +- .../eclipse/actions/MarkStartedAction.java | 32 +- .../eclipse/actions/RemoveJVMArgumentAction.java | 8 +- .../actions/RemoveProgramArgumentAction.java | 10 +- .../eclipse/actions/RemoveRepositoryAction.java | 25 +- .../eclipse/actions/RemoveSourceBundleAction.java | 29 +- .../eclipse/actions/RepositoryAction.java | 62 +- .../eclipse/actions/SetLauncherNameAction.java | 6 +- .../eclipse/actions/SetProgramPropertyAction.java | 6 +- .../eclipse/actions/SetStartLevelAction.java | 32 +- .../eclipse/actions/UninstallBundleAction.java | 32 +- .../eclipse/actions/UninstallFeatureAction.java | 23 +- .../equinox/internal/p2/update/Configuration.java | 14 +- .../internal/p2/update/ConfigurationCache.java | 70 + .../internal/p2/update/ConfigurationIO.java | 74 + .../internal/p2/update/ConfigurationParser.java | 22 +- .../internal/p2/update/ConfigurationWriter.java | 18 +- .../eclipse/equinox/internal/p2/update/Site.java | 14 +- .../equinox/internal/p2/update/XMLWriter.java | 12 +- .../touchpoint/eclipse/query/OSGiBundleQuery.java | 42 + .../p2/touchpoint/eclipse/query/package.html | 18 + .../.classpath | 4 +- .../.settings/org.eclipse.jdt.core.prefs | 16 +- .../META-INF/MANIFEST.MF | 15 +- .../build.properties | 2 + .../p2/touchpoint/natives/BackupStore.java | 12 +- .../p2/touchpoint/natives/NativeTouchpoint.java | 24 +- .../internal/p2/touchpoint/natives/Util.java | 41 +- .../natives/actions/ActionConstants.java | 1 + .../p2/touchpoint/natives/actions/ChmodAction.java | 8 +- .../natives/actions/CleanupcopyAction.java | 17 +- .../natives/actions/CleanupzipAction.java | 22 +- .../touchpoint/natives/actions/CollectAction.java | 38 +- .../p2/touchpoint/natives/actions/CopyAction.java | 20 +- .../p2/touchpoint/natives/actions/LinkAction.java | 6 +- .../p2/touchpoint/natives/actions/MkdirAction.java | 6 +- .../touchpoint/natives/actions/RemoveAction.java | 8 +- .../p2/touchpoint/natives/actions/RmdirAction.java | 6 +- .../p2/touchpoint/natives/actions/UnzipAction.java | 12 +- .../ProvAdminUI.launch | 76 +- .../ui/admin/rcp/ApplicationWorkbenchAdvisor.java | 6 +- bundles/org.eclipse.equinox.p2.ui.admin/.classpath | 4 +- .../.settings/org.eclipse.jdt.core.prefs | 16 +- .../META-INF/MANIFEST.MF | 32 +- .../build.properties | 5 +- bundles/org.eclipse.equinox.p2.ui.admin/plugin.xml | 8 +- .../ui/admin/AddArtifactRepositoryOperation.java | 46 - .../ui/admin/AddMetadataRepositoryOperation.java | 46 - .../internal/p2/ui/admin/AddProfileJob.java | 44 + .../p2/ui/admin/ArtifactRepositoriesView.java | 40 +- .../p2/ui/admin/ArtifactRepositoryTracker.java | 83 + .../p2/ui/admin/MetadataRepositoriesView.java | 72 +- .../p2/ui/admin/MetadataRepositoryTracker.java | 84 + .../internal/p2/ui/admin/ProfileFactory.java | 80 + .../equinox/internal/p2/ui/admin/ProfilesView.java | 83 +- .../internal/p2/ui/admin/ProvAdminUIActivator.java | 100 +- .../internal/p2/ui/admin/ProvAdminUIMessages.java | 9 - .../equinox/internal/p2/ui/admin/ProvView.java | 40 +- .../RefreshArtifactRepositoriesOperation.java | 50 - .../RefreshMetadataRepositoriesOperation.java | 52 - .../admin/RemoveArtifactRepositoryOperation.java | 38 - .../admin/RemoveMetadataRepositoryOperation.java | 38 - .../internal/p2/ui/admin/RemoveProfilesJob.java | 37 + .../internal/p2/ui/admin/RepositoriesView.java | 62 +- .../admin/dialogs/AddArtifactRepositoryDialog.java | 109 +- .../admin/dialogs/AddMetadataRepositoryDialog.java | 23 +- .../p2/ui/admin/dialogs/AddProfileDialog.java | 17 +- .../internal/p2/ui/admin/dialogs/IUGroup.java | 6 +- .../p2/ui/admin/dialogs/IUImplementationGroup.java | 37 +- .../dialogs/IUImplementationPropertyPage.java | 6 +- .../ui/admin/dialogs/IUProfilePropertiesGroup.java | 20 +- .../p2/ui/admin/dialogs/IUPropertiesGroup.java | 5 +- .../ui/admin/dialogs/InstalledIUPropertyPage.java | 2 +- .../internal/p2/ui/admin/dialogs/ProfileGroup.java | 21 +- .../p2/ui/admin/dialogs/ProfilePropertyPage.java | 6 +- .../RepositoryImplementationPropertyPage.java | 21 +- .../internal/p2/ui/admin/messages.properties | 9 - .../META-INF/MANIFEST.MF | 19 +- .../build.properties | 1 + .../icons/tool/close.gif | Bin 0 -> 73 bytes .../icons/tool/close_hot.gif | Bin 0 -> 852 bytes .../icons/tool/update.gif | Bin 0 -> 600 bytes .../icons/tool/update_problems.gif | Bin 0 -> 1005 bytes .../p2/ui/sdk/scheduler/AutomaticUpdateAction.java | 157 -- .../ui/sdk/scheduler/AutomaticUpdateMessages.java | 2 - .../p2/ui/sdk/scheduler/AutomaticUpdatePlugin.java | 50 +- .../ui/sdk/scheduler/AutomaticUpdateScheduler.java | 21 +- .../p2/ui/sdk/scheduler/AutomaticUpdater.java | 432 ++-- .../p2/ui/sdk/scheduler/AutomaticUpdatesPopup.java | 5 +- .../scheduler/AutomaticUpdatesPreferencePage.java | 11 +- .../p2/ui/sdk/scheduler/DownloadPhaseSet.java | 25 + .../p2/ui/sdk/scheduler/PreferenceInitializer.java | 17 +- .../p2/ui/sdk/scheduler/messages.properties | 2 - .../META-INF/MANIFEST.MF | 28 +- .../OSGI-INF/licenseManager_component.xml | 7 + .../OSGI-INF/policy_component.xml | 2 +- .../OSGI-INF/serviceui_component.xml | 7 - bundles/org.eclipse.equinox.p2.ui.sdk/plugin.xml | 41 +- .../p2/ui/sdk/InstallNewSoftwareHandler.java | 31 +- .../p2/ui/sdk/PreloadingRepositoryHandler.java | 63 +- .../internal/p2/ui/sdk/ProvSDKMessages.java | 5 +- .../internal/p2/ui/sdk/ProvSDKUIActivator.java | 79 +- .../equinox/internal/p2/ui/sdk/SDKPolicy.java | 98 +- .../internal/p2/ui/sdk/SimpleLicenseManager.java | 118 ++ .../equinox/internal/p2/ui/sdk/UpdateHandler.java | 69 +- .../equinox/internal/p2/ui/sdk/messages.properties | 6 +- .../p2/ui/sdk/prefs/PreferenceInitializer.java | 9 +- bundles/org.eclipse.equinox.p2.ui/.classpath | 4 +- bundles/org.eclipse.equinox.p2.ui/.project | 5 + .../.settings/org.eclipse.jdt.core.prefs | 15 +- .../org.eclipse.equinox.p2.ui/META-INF/MANIFEST.MF | 80 +- .../OSGI-INF/repositoryTracker_component.xml | 7 + .../OSGI-INF/serviceui_component.xml | 7 + bundles/org.eclipse.equinox.p2.ui/build.properties | 7 +- .../org.eclipse.equinox.p2.ui/icons/tool/close.gif | Bin 73 -> 0 bytes .../icons/tool/close_hot.gif | Bin 852 -> 0 bytes .../icons/tool/update.gif | Bin 600 -> 0 bytes .../icons/tool/update_problems.gif | Bin 1005 -> 0 bytes bundles/org.eclipse.equinox.p2.ui/plugin.xml | 47 +- .../internal/p2/ui/BatchChangeBeginningEvent.java | 36 - .../internal/p2/ui/BatchChangeCompleteEvent.java | 41 - .../internal/p2/ui/ColocatedRepositoryTracker.java | 167 ++ .../p2/ui/DefaultMetadataURLValidator.java | 85 - .../internal/p2/ui/DefaultQueryProvider.java | 189 -- .../internal/p2/ui/ElementQueryDescriptor.java | 81 + .../equinox/internal/p2/ui/ElementWrapper.java | 58 + .../internal/p2/ui/IProvHelpContextIds.java | 44 + .../equinox/internal/p2/ui/PlanAnalyzer.java | 179 -- .../org/eclipse/equinox/internal/p2/ui/ProvUI.java | 248 +++ .../equinox/internal/p2/ui/ProvUIActivator.java | 94 +- .../internal/p2/ui/ProvUIAdapterFactory.java | 16 +- .../equinox/internal/p2/ui/ProvUIImages.java | 75 + .../equinox/internal/p2/ui/ProvUIMessages.java | 68 +- .../internal/p2/ui/ProvUIProvisioningListener.java | 196 ++ .../p2/ui/ProvisioningOperationRunner.java | 143 ++ .../equinox/internal/p2/ui/QueryProvider.java | 200 ++ .../p2/ui/QueryableArtifactRepositoryManager.java | 57 + .../p2/ui/QueryableMetadataRepositoryManager.java | 56 + .../internal/p2/ui/QueryableRepositoryManager.java | 172 ++ .../internal/p2/ui/RepositoryLocationQuery.java | 64 + .../p2/ui/RepositoryOperationBeginningEvent.java | 35 + .../p2/ui/RepositoryOperationEndingEvent.java | 79 + .../internal/p2/ui/SimpleLicenseManager.java | 120 -- .../equinox/internal/p2/ui/UIRepositoryEvent.java | 36 - .../internal/p2/ui/UpdateManagerCompatibility.java | 291 +++ .../internal/p2/ui/ValidationDialogServiceUI.java | 189 ++ .../p2/ui/actions/ColocatedRepositoryAction.java | 41 + .../p2/ui/actions/ExistingIUInProfileAction.java | 97 + .../internal/p2/ui/actions/InstallAction.java | 68 + .../p2/ui/actions/ProfileModificationAction.java | 212 ++ .../p2/ui/actions/PropertyDialogAction.java | 37 + .../internal/p2/ui/actions/ProvisioningAction.java | 91 + .../internal/p2/ui/actions/RefreshAction.java | 63 + .../actions/RemoveColocatedRepositoryAction.java | 28 + .../internal/p2/ui/actions/UninstallAction.java | 54 + .../internal/p2/ui/actions/UpdateAction.java | 70 + .../p2/ui/dialogs/AddRepositoryDialog.java | 146 ++ .../p2/ui/dialogs/ApplyProfileChangesDialog.java | 2 +- .../internal/p2/ui/dialogs/AvailableIUGroup.java | 475 +++++ .../p2/ui/dialogs/AvailableIUPatternFilter.java | 7 +- .../internal/p2/ui/dialogs/AvailableIUsPage.java | 71 +- .../p2/ui/dialogs/ComboAutoCompleteField.java | 8 +- .../p2/ui/dialogs/ContainerCheckedTreeViewer.java | 10 +- .../internal/p2/ui/dialogs/CopyHandler.java | 1 + .../equinox/internal/p2/ui/dialogs/CopyPopup.java | 1 + .../equinox/internal/p2/ui/dialogs/CopyUtils.java | 1 + .../p2/ui/dialogs/DelayedFilterCheckboxTree.java | 53 +- .../equinox/internal/p2/ui/dialogs/ICopyable.java | 23 - .../ui/dialogs/IRepositorySelectionListener.java | 29 + .../ui/dialogs/IResolutionErrorReportingPage.java | 6 +- .../p2/ui/dialogs/IUCopyrightPropertyPage.java | 80 + .../internal/p2/ui/dialogs/IUDetailsGroup.java | 2 +- .../p2/ui/dialogs/IUGeneralInfoPropertyPage.java | 141 ++ .../p2/ui/dialogs/IULicensePropertyPage.java | 83 + .../internal/p2/ui/dialogs/IUPropertyPage.java | 6 +- .../internal/p2/ui/dialogs/InstallWizard.java | 144 ++ .../internal/p2/ui/dialogs/InstallWizardPage.java | 10 +- .../internal/p2/ui/dialogs/InstalledIUGroup.java | 111 ++ .../p2/ui/dialogs/PreselectedIUInstallWizard.java | 85 + .../p2/ui/dialogs/ProvisioningOperationWizard.java | 223 +-- .../p2/ui/dialogs/ProvisioningWizardDialog.java | 62 + .../p2/ui/dialogs/ProvisioningWizardPage.java | 24 +- .../dialogs/RepositoryManipulatorDropTarget.java | 29 +- .../dialogs/RepositoryNameAndLocationDialog.java | 44 +- .../p2/ui/dialogs/RepositorySelectionGroup.java | 610 ++++++ .../p2/ui/dialogs/ResolutionResultsWizardPage.java | 87 +- .../p2/ui/dialogs/ResolutionStatusPage.java | 48 +- .../internal/p2/ui/dialogs/SelectableIUsPage.java | 64 +- .../p2/ui/dialogs/SizeComputingWizardPage.java | 57 +- .../internal/p2/ui/dialogs/StructuredIUGroup.java | 35 +- .../internal/p2/ui/dialogs/UninstallWizard.java | 91 + .../p2/ui/dialogs/UninstallWizardPage.java | 17 +- .../internal/p2/ui/dialogs/UpdateWizard.java | 146 ++ .../internal/p2/ui/dialogs/UpdateWizardPage.java | 15 +- .../internal/p2/ui/dialogs/WizardWithLicenses.java | 85 +- .../equinox/internal/p2/ui/messages.properties | 80 +- .../internal/p2/ui/model/ArtifactElement.java | 5 +- .../internal/p2/ui/model/ArtifactRepositories.java | 42 + .../p2/ui/model/ArtifactRepositoryElement.java | 99 +- .../internal/p2/ui/model/AvailableIUElement.java | 50 +- .../p2/ui/model/AvailableUpdateElement.java | 22 +- .../internal/p2/ui/model/CategoryElement.java | 39 +- .../equinox/internal/p2/ui/model/ElementUtils.java | 71 +- .../equinox/internal/p2/ui/model/IIUElement.java | 25 +- .../internal/p2/ui/model/IRepositoryElement.java | 35 + .../internal/p2/ui/model/IUElementListRoot.java | 57 + .../internal/p2/ui/model/InstalledIUElement.java | 129 ++ .../internal/p2/ui/model/MetadataRepositories.java | 101 + .../p2/ui/model/MetadataRepositoryElement.java | 84 +- .../internal/p2/ui/model/ProfileElement.java | 82 + .../internal/p2/ui/model/ProfileSnapshots.java | 44 +- .../equinox/internal/p2/ui/model/Profiles.java | 46 + .../equinox/internal/p2/ui/model/ProvElement.java | 5 +- .../internal/p2/ui/model/QueriedElement.java | 38 +- .../p2/ui/model/QueriedElementWrapper.java | 36 +- .../internal/p2/ui/model/RemoteQueriedElement.java | 2 +- .../p2/ui/model/RollbackProfileElement.java | 30 +- .../equinox/internal/p2/ui/model/RootElement.java | 28 +- .../equinox/internal/p2/ui/model/Updates.java | 61 + .../p2/ui/query/AnyRequiredCapabilityQuery.java | 43 - .../internal/p2/ui/query/ArtifactKeyWrapper.java | 46 + .../ui/query/ArtifactRepositoryElementWrapper.java | 50 + .../internal/p2/ui/query/AvailableIUWrapper.java | 26 +- .../p2/ui/query/CategoryElementWrapper.java | 31 +- .../internal/p2/ui/query/IUViewQueryContext.java | 169 ++ .../p2/ui/query/InstalledIUElementWrapper.java | 10 +- .../ui/query/MetadataRepositoryElementWrapper.java | 8 +- .../p2/ui/query/ProfileElementWrapper.java | 4 +- .../p2/ui/query/QueryableProfileRegistry.java | 33 +- .../internal/p2/ui/query/QueryableUpdates.java | 33 +- .../ui/viewers/DeferredQueryContentProvider.java | 9 +- .../internal/p2/ui/viewers/IUColumnConfig.java | 172 ++ .../internal/p2/ui/viewers/IUComparator.java | 82 + .../p2/ui/viewers/IUDetailsLabelProvider.java | 29 +- .../internal/p2/ui/viewers/IUDragAdapter.java | 128 ++ .../p2/ui/viewers/InstallIUDropAdapter.java | 216 ++ .../p2/ui/viewers/ProvElementComparer.java | 77 + .../p2/ui/viewers/ProvElementContentProvider.java | 162 ++ .../p2/ui/viewers/ProvElementLabelProvider.java | 146 ++ .../p2/ui/viewers/RepositoryContentProvider.java | 35 + .../ui/viewers/RepositoryDetailsLabelProvider.java | 28 +- .../StructuredViewerProvisioningListener.java | 173 ++ .../provisional/p2/ui/ElementQueryDescriptor.java | 80 - .../internal/provisional/p2/ui/ElementWrapper.java | 57 - .../provisional/p2/ui/IProvHelpContextIds.java | 45 - .../internal/provisional/p2/ui/IStatusCodes.java | 48 - .../provisional/p2/ui/IUPropertyUtils.java | 241 --- .../internal/provisional/p2/ui/ProfileFactory.java | 81 - .../equinox/internal/provisional/p2/ui/ProvUI.java | 319 --- .../internal/provisional/p2/ui/ProvUIImages.java | 81 - .../p2/ui/ProvUIProvisioningListener.java | 194 -- .../p2/ui/ProvisioningOperationRunner.java | 251 --- .../p2/ui/QueryableArtifactRepositoryManager.java | 72 - .../p2/ui/QueryableMetadataRepositoryManager.java | 97 - .../p2/ui/QueryableRepositoryManager.java | 238 --- .../provisional/p2/ui/RepositoryLocationQuery.java | 68 - .../provisional/p2/ui/ResolutionResult.java | 127 -- .../p2/ui/UpdateManagerCompatibility.java | 300 --- .../p2/ui/ValidationDialogServiceUI.java | 192 -- .../p2/ui/actions/ColocatedRepositoryAction.java | 49 - .../p2/ui/actions/ExistingIUInProfileAction.java | 129 -- .../provisional/p2/ui/actions/InstallAction.java | 158 -- .../p2/ui/actions/ProfileModificationAction.java | 304 --- .../p2/ui/actions/PropertyDialogAction.java | 37 - .../p2/ui/actions/ProvisioningAction.java | 74 - .../provisional/p2/ui/actions/RefreshAction.java | 62 - .../actions/RemoveColocatedRepositoryAction.java | 29 - .../provisional/p2/ui/actions/UninstallAction.java | 73 - .../provisional/p2/ui/actions/UpdateAction.java | 99 - .../p2/ui/dialogs/AcceptLicensesWizardPage.java | 418 ---- .../p2/ui/dialogs/AddRepositoryDialog.java | 163 -- .../p2/ui/dialogs/AvailableIUGroup.java | 481 ----- .../ui/dialogs/IRepositorySelectionListener.java | 29 - .../p2/ui/dialogs/IUCopyrightPropertyPage.java | 82 - .../p2/ui/dialogs/IUGeneralInfoPropertyPage.java | 143 -- .../p2/ui/dialogs/IULicensePropertyPage.java | 81 - .../provisional/p2/ui/dialogs/InstallWizard.java | 137 -- .../p2/ui/dialogs/InstalledIUGroup.java | 115 -- .../p2/ui/dialogs/InstalledSoftwarePage.java | 239 --- .../p2/ui/dialogs/PreselectedIUInstallWizard.java | 93 - .../p2/ui/dialogs/ProvisioningWizardDialog.java | 63 - .../p2/ui/dialogs/RepositoryManipulationPage.java | 912 --------- .../p2/ui/dialogs/RepositorySelectionGroup.java | 634 ------ .../p2/ui/dialogs/RevertProfilePage.java | 547 ------ .../provisional/p2/ui/dialogs/UninstallWizard.java | 97 - .../provisional/p2/ui/dialogs/UpdateWizard.java | 265 --- .../p2/ui/model/ArtifactRepositories.java | 43 - .../p2/ui/model/IRepositoryElement.java | 35 - .../provisional/p2/ui/model/IUElementListRoot.java | 58 - .../p2/ui/model/InstalledIUElement.java | 128 -- .../p2/ui/model/MetadataRepositories.java | 102 - .../provisional/p2/ui/model/ProfileElement.java | 91 - .../internal/provisional/p2/ui/model/Profiles.java | 47 - .../internal/provisional/p2/ui/model/Updates.java | 62 - .../AddColocatedRepositoryOperation.java | 51 - .../p2/ui/operations/AddProfileOperation.java | 37 - .../p2/ui/operations/AddRepositoryOperation.java | 66 - .../p2/ui/operations/DownloadPhaseSet.java | 24 - .../ui/operations/PlannerResolutionOperation.java | 85 - .../operations/ProfileModificationOperation.java | 87 - .../p2/ui/operations/ProvisioningOperation.java | 86 - .../p2/ui/operations/ProvisioningUtil.java | 450 ----- .../RemoveColocatedRepositoryOperation.java | 39 - .../p2/ui/operations/RemoveProfilesOperation.java | 37 - .../ui/operations/RemoveRepositoryOperation.java | 26 - .../p2/ui/operations/RepositoryOperation.java | 56 - .../p2/ui/operations/SizingPhaseSet.java | 31 - .../ui/policy/ColocatedRepositoryManipulator.java | 166 -- .../provisional/p2/ui/policy/IProfileChooser.java | 29 - .../p2/ui/policy/IUViewQueryContext.java | 210 -- .../provisional/p2/ui/policy/LicenseManager.java | 47 - .../provisional/p2/ui/policy/PlanValidator.java | 45 - .../internal/provisional/p2/ui/policy/Policy.java | 289 --- .../provisional/p2/ui/policy/QueryProvider.java | 31 - .../p2/ui/policy/RepositoryLocationValidator.java | 56 - .../p2/ui/policy/RepositoryManipulator.java | 100 - .../provisional/p2/ui/viewers/IUColumnConfig.java | 172 -- .../provisional/p2/ui/viewers/IUComparator.java | 84 - .../provisional/p2/ui/viewers/IUDragAdapter.java | 128 -- .../p2/ui/viewers/InstallIUDropAdapter.java | 218 --- .../p2/ui/viewers/ProvElementComparer.java | 79 - .../p2/ui/viewers/ProvElementContentProvider.java | 160 -- .../p2/ui/viewers/ProvElementLabelProvider.java | 147 -- .../p2/ui/viewers/RepositoryContentProvider.java | 36 - .../StructuredViewerProvisioningListener.java | 168 -- .../equinox/p2/ui/AcceptLicensesWizardPage.java | 484 +++++ .../src/org/eclipse/equinox/p2/ui/ICopyable.java | 30 + .../equinox/p2/ui/InstalledSoftwarePage.java | 255 +++ .../org/eclipse/equinox/p2/ui/LicenseManager.java | 85 + .../equinox/p2/ui/LoadMetadataRepositoryJob.java | 177 ++ .../src/org/eclipse/equinox/p2/ui/Policy.java | 355 ++++ .../org/eclipse/equinox/p2/ui/ProvisioningUI.java | 442 +++++ .../equinox/p2/ui/RepositoryManipulationPage.java | 868 ++++++++ .../eclipse/equinox/p2/ui/RevertProfilePage.java | 564 ++++++ .../src/org/eclipse/equinox/p2/ui/package.html | 39 + .../.classpath | 2 +- .../.settings/org.eclipse.jdt.core.prefs | 594 +++--- .../META-INF/MANIFEST.MF | 18 +- .../build.properties | 2 + .../internal/p2/updatechecker/UpdateChecker.java | 45 +- .../p2/updatechecker/IUpdateChecker.java | 7 +- .../provisional/p2/updatechecker/UpdateEvent.java | 2 +- .../org.eclipse.equinox.p2.updatesite/.classpath | 2 +- .../.settings/org.eclipse.jdt.core.prefs | 17 +- .../.settings/org.eclipse.jdt.launching.prefs | 3 + .../META-INF/MANIFEST.MF | 30 +- .../build.properties | 2 + .../internal/p2/updatesite/CategoryXMLAction.java | 3 +- .../internal/p2/updatesite/DefaultSiteParser.java | 20 +- .../internal/p2/updatesite/DigestParser.java | 4 +- .../p2/updatesite/LocalUpdateSiteAction.java | 6 +- .../p2/updatesite/RemoteFeaturesAction.java | 13 +- .../p2/updatesite/RemoteUpdateSiteAction.java | 6 +- .../internal/p2/updatesite/SiteCategory.java | 20 +- .../internal/p2/updatesite/SiteFeature.java | 8 +- .../equinox/internal/p2/updatesite/SiteModel.java | 36 +- .../internal/p2/updatesite/SiteXMLAction.java | 151 +- .../equinox/internal/p2/updatesite/UpdateSite.java | 23 +- .../artifact/UpdateSiteArtifactRepository.java | 26 +- .../UpdateSiteArtifactRepositoryFactory.java | 43 +- .../metadata/UpdateSiteMetadataRepository.java | 17 +- .../UpdateSiteMetadataRepositoryFactory.java | 20 +- .../.project | 5 + .../META-INF/MANIFEST.MF | 2 +- .../OSGI-INF/configurator.xml | 10 + .../build.properties | 17 +- .../manipulator/SimpleConfiguratorManipulator.java | 14 +- .../simpleconfigurator/manipulator/Activator.java | 47 - .../META-INF/MANIFEST.MF | 1 + .../simpleconfigurator/console/ApplyCommand.java | 1 - .../.settings/org.eclipse.jdt.core.prefs | 2 +- .../META-INF/MANIFEST.MF | 3 +- .../equinox/p2/examples/rcp/cloud/Activator.java | 3 +- .../p2/examples/rcp/cloud/p2/CloudPolicy.java | 13 +- .../rcp/cloud/p2/InstallNewSoftwareHandler.java | 53 +- .../equinox/p2/examples/rcp/cloud/p2/Messages.java | 25 - .../rcp/cloud/p2/PreloadingRepositoryHandler.java | 82 +- .../p2/examples/rcp/cloud/p2/UpdateHandler.java | 72 +- .../p2/examples/rcp/cloud/p2/messages.properties | 15 - .../.settings/org.eclipse.jdt.core.prefs | 2 +- .../META-INF/MANIFEST.MF | 12 +- .../ApplicationWorkbenchAdvisor.java | 57 +- .../p2/examples/rcp/prestartupdate/P2Util.java | 197 +- .../.settings/org.eclipse.jdt.core.prefs | 2 +- .../META-INF/MANIFEST.MF | 3 +- .../p2/AllIUsAreVisiblePolicy.java | 16 +- .../p2/InstallNewSoftwareHandler.java | 53 +- .../rcp/sdkbundlevisibility/p2/Messages.java | 1 - .../p2/PreloadingRepositoryHandler.java | 82 +- .../p2/ProvisioningPreferencePage.java | 9 +- .../rcp/sdkbundlevisibility/p2/UpdateHandler.java | 75 +- .../rcp/sdkbundlevisibility/p2/messages.properties | 1 - .../R3_6_api_cleanup_projectSet.psf | 66 + .../org.eclipse.equinox.p2.user.ui/feature.xml | 7 + org.eclipse.equinox.p2.releng/mylyn-discovery.psf | 16 + .../p2_users_R_3_6_api_cleanup_projectSet.psf | 15 + .../projectSet-extssh.psf | 2 +- org.eclipse.equinox.p2.releng/projectSet.psf | 2 +- 1524 files changed, 64335 insertions(+), 55149 deletions(-) delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/.externalToolBuilders/org.eclipse.equinox.p2.artifact.repository buildAntTasks.xml.launch delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/buildAntTasks.xml delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/FileMirrorLog.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/IArtifactMirrorLog.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/MirrorApplication.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/Mirroring.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/XMLMirrorLog.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/MD5ArtifactComparator.java create mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/FlatteningIterator.java create mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactDescriptor.java create mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryFactory.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/ArtifactComparatorFactory.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/ArtifactDescriptor.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactComparator.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactDescriptor.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactRepository.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactRepositoryManager.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactRequest.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IFileArtifactRepository.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStepDescriptor.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/artifact/repository/AbstractArtifactRepository.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/artifact/repository/ArtifactRepositoryFactory.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/artifact/repository/SimpleArtifactRepositoryFactory.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/AddChildTask.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/AntMirrorLog.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/CreateCompositeArtifactRepositoryTask.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/MirrorApplicationTask.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/RemoveChildTask.java delete mode 100644 bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/ValidateTask.java delete mode 100644 bundles/org.eclipse.equinox.p2.core/.settings/org.eclipse.jdt.core.prefs create mode 100644 bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/AgentLocation.java delete mode 100644 bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/BasicLocation.java create mode 100644 bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/CollectionUtils.java delete mode 100644 bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/provisional/p2/core/ProvisionException.java delete mode 100644 bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/provisional/p2/core/location/AgentLocation.java create mode 100644 bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/IAgentLocation.java create mode 100644 bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/ProvisionException.java create mode 100644 bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/ILog.java delete mode 100644 bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/HasMatchCollector.java delete mode 100644 bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/TwoTierMap.java delete mode 100644 bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/ProvisioningPlan.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/.settings/.api_filters create mode 100644 bundles/org.eclipse.equinox.p2.engine/ExtensionWizardPage.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Engine.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineSession.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/InstallableUnitPhase.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Phase.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/PhaseSet.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/CertificateChecker.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/CheckTrust.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Collect.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Configure.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Install.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Property.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Sizing.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Unconfigure.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Uninstall.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/BeginOperationEvent.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/CertificateChecker.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/CommitOperationEvent.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/DefaultPhaseSet.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Engine.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/EngineSession.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IEngine.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IProfile.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IProfileRegistry.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ISurrogateProfileHandler.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IUProfilePropertyQuery.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitEvent.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitOperand.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitPhase.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitPropertyOperand.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Memento.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Messages.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/MissingAction.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/MissingActionsException.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Operand.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Phase.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/PhaseSet.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProfileEvent.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProfileScope.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/PropertyOperand.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProvisioningAction.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProvisioningContext.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/RollbackOperationEvent.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Touchpoint.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/TransactionEvent.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/messages.properties delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/CheckTrust.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Collect.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Configure.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Install.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Messages.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Property.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Sizing.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Unconfigure.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Uninstall.java delete mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/messages.properties create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/BeginOperationEvent.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/CommitOperationEvent.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/DefaultPhaseSet.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IEngine.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IPhaseSet.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IProfile.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IProfileRegistry.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IProvisioningPlan.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ISurrogateProfileHandler.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/InstallableUnitEvent.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/InstallableUnitOperand.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/InstallableUnitPropertyOperand.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/MissingAction.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/MissingActionsException.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/Operand.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProfileEvent.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProfileScope.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/PropertyOperand.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningContext.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningPlan.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/RollbackOperationEvent.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/TransactionEvent.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/package.html create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/query/IUProfilePropertyQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/query/UserVisibleRootQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/spi/Memento.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/spi/ProvisioningAction.java create mode 100644 bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/spi/Touchpoint.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata.repository/p2 tools - mirror metadata.launch delete mode 100644 bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/mirror/MirrorApplication.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/mirror/Mirroring.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/mirror/RangeQuery.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/mirror/VersionRangedName.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/IUMap.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/SimpleMetadataRepositoryFactory.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/p2/metadata/repository/IMetadataRepository.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/p2/metadata/repository/IMetadataRepositoryManager.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/AbstractMetadataRepository.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/MetadataRepositoryFactory.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/RepositoryReference.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/SimpleMetadataRepositoryFactory.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/MirrorApplicationTask.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/BasicVersion.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/IRequiredCapability.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/NotRequirement.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ORRequirement.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/OSGiVersion.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/OmniVersion.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TranslationSupport.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionFormat.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionFormatParser.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionParser.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionVector.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionedId.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/All.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/And.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/At.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Binary.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/CoercingComparator.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/CollectionFilter.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Compare.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Equals.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/EvaluationContext.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Exists.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Expression.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/ExpressionFactory.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/IExpressionConstants.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/IRepeatableIterator.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/LDAPApproximation.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/LDAPFilter.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/LambdaExpression.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Literal.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/MatchExpression.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Matches.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Member.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/MemberProvider.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/NAry.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Not.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Or.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Parameter.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/RepeatableIterator.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Unary.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Variable.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/parser/ExpressionParser.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/parser/LDAPFilterParser.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/IUPropertyQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/LatestIUVersionQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/ObjectMatchQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/UpdateQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/query/QueryHelpers.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/FormatException.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IArtifactKey.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ICopyright.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IInstallableUnit.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IInstallableUnitFragment.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IInstallableUnitPatch.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ILicense.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IProvidedCapability.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IRequiredCapability.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IRequirementChange.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ITouchpointData.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ITouchpointInstruction.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ITouchpointType.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IUpdateDescriptor.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IVersionedId.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/Version.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionFormat.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionFormatParser.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionParser.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionRange.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionVector.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionedId.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CapabilityQuery.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/Collector.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CompositeQuery.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CompoundQuery.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CompoundQueryable.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/ContextQuery.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/IMatchQuery.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/IQueryable.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/IUPropertyQuery.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/InstallableUnitQuery.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/LatestIUVersionQuery.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/MatchQuery.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/Query.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/QueryHelpers.java delete mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/UpdateQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IArtifactKey.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ICopyright.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IInstallableUnit.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IInstallableUnitFragment.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IInstallableUnitPatch.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ILicense.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IProvidedCapability.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IRequirement.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IRequirementChange.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ITouchpointData.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ITouchpointInstruction.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ITouchpointType.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IUpdateDescriptor.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IVersionFormat.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IVersionedId.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/Version.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/VersionFormatException.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/VersionRange.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/ExpressionParseException.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/ExpressionUtil.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IEvaluationContext.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpression.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpressionFactory.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpressionParser.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpressionVisitor.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IFilterExpression.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IMatchExpression.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/SimplePattern.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/CategoryMemberQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/CategoryQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/ExpressionQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/FragmentQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/GroupQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/InstallableUnitQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/PatchQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/Collector.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/CompoundQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/CompoundQueryable.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/ContextQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/ICompositeQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IMatchQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IQueryResult.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IQueryable.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/LimitQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/MatchQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/PipedQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/.classpath create mode 100644 bundles/org.eclipse.equinox.p2.operations/.cvsignore create mode 100644 bundles/org.eclipse.equinox.p2.operations/.project create mode 100644 bundles/org.eclipse.equinox.p2.operations/.settings/org.eclipse.jdt.core.prefs create mode 100644 bundles/org.eclipse.equinox.p2.operations/.settings/org.eclipse.jdt.ui.prefs create mode 100644 bundles/org.eclipse.equinox.p2.operations/.settings/org.eclipse.pde.core.prefs create mode 100644 bundles/org.eclipse.equinox.p2.operations/META-INF/MANIFEST.MF create mode 100644 bundles/org.eclipse.equinox.p2.operations/about.html create mode 100644 bundles/org.eclipse.equinox.p2.operations/build.properties create mode 100644 bundles/org.eclipse.equinox.p2.operations/plugin.properties create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/Activator.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/DownloadPhaseSet.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/IStatusCodes.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/Messages.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/PlanAnalyzer.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/PlannerResolutionJob.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/ResolutionResult.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/SizingPhaseSet.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/messages.properties create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/IProfileChangeJob.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/InstallOperation.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProfileChangeOperation.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProfileModificationJob.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProvisioningJob.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProvisioningSession.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/RepositoryTracker.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/UninstallOperation.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/Update.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/UpdateOperation.java create mode 100644 bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/package.html create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/schema/org.eclipse.equinox.p2.repository.tools.verifier.exsd delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Annotation.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AnnotationComponent.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AnnotationComponentValue.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AnnotationDefaultAttribute.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AttributeNamesConstants.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/CharOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFileAttribute.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFileReader.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFileStruct.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFormatException.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/CodeAttribute.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantPool.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantPoolConstant.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantPoolEntry.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantValueAttribute.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/DefaultBytecodeVisitor.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Disassembler.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/EnclosingMethodAttribute.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ExceptionAttribute.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ExceptionTableEntry.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/FieldInfo.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/IModifierConstants.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/IOpcodeMnemonics.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/InnerClassesAttribute.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/InnerClassesAttributeEntry.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/MD5ArtifactComparator.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Messages.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/MethodInfo.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/OpcodeStringValues.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ParameterAnnotation.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeInvisibleAnnotationsAttribute.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeInvisibleParameterAnnotationsAttribute.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeVisibleAnnotationsAttribute.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeVisibleParameterAnnotationsAttribute.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Signature.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/SignatureAttribute.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/SourceFileAttribute.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/TypeConstants.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Utility.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Annotation.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AnnotationComponent.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AnnotationComponentValue.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AnnotationDefaultAttribute.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AttributeNamesConstants.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/CharOperation.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFileAttribute.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFileReader.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFileStruct.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFormatException.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/CodeAttribute.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantPool.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantPoolConstant.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantPoolEntry.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantValueAttribute.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/DefaultBytecodeVisitor.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Disassembler.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/EnclosingMethodAttribute.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ExceptionAttribute.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ExceptionTableEntry.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/FieldInfo.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/IModifierConstants.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/IOpcodeMnemonics.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/InnerClassesAttribute.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/InnerClassesAttributeEntry.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Messages.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/MethodInfo.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/OpcodeStringValues.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ParameterAnnotation.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeInvisibleAnnotationsAttribute.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeInvisibleParameterAnnotationsAttribute.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeVisibleAnnotationsAttribute.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeVisibleParameterAnnotationsAttribute.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Signature.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/SignatureAttribute.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/SourceFileAttribute.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/TypeConstants.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Utility.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/messages.properties delete mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/messages.properties create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/FileMirrorLog.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/IArtifactMirrorLog.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/Mirroring.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/XMLMirrorLog.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/ArtifactRepositoryValidator.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/RepositoryAnalyzerApplication.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/CopyrightAnalyzer.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/HostCheckAnalyzer.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/IUCounting.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/LicenseAnalyzer.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/UniqueIUAnalyzer.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/UnzipFeatureJarAnalyzer.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/VersionAnalyzer.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/analyzer/IIUAnalyzer.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/analyzer/IUAnalyzer.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/analyzer/RepositoryAnalyzer.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/comparator/ArtifactComparatorFactory.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/comparator/IArtifactComparator.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/AntMirrorLog.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/CreateCompositeArtifactRepositoryTask.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/MirrorArtifactsTask.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/MirrorMetadataTask.java create mode 100644 bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/ValidateTask.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/ICompositeRepository.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/IRepository.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/IRepositoryManager.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/RepositoryCreationException.java delete mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/repository/AbstractRepository.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/ICompositeRepository.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/IRepository.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/IRepositoryManager.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/ArtifactDescriptorQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/ArtifactKeyQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactDescriptor.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactRepository.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactRepositoryManager.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactRequest.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IFileArtifactRepository.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IProcessingStepDescriptor.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/AbstractArtifactRepository.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/ArtifactDescriptor.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/ArtifactRepositoryFactory.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/ProcessingStepDescriptor.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/IMetadataRepository.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/IMetadataRepositoryManager.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/spi/AbstractMetadataRepository.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/spi/MetadataRepositoryFactory.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/spi/AbstractRepository.java create mode 100644 bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/spi/RepositoryReference.java delete mode 100644 bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/AddColocatedRepositoryOperationTest.java delete mode 100644 bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/AddProfileOperationTest.java delete mode 100644 bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/ProvisioningUtilTest.java delete mode 100644 bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/RemoveColocatedRepositoryOperationTest.java delete mode 100644 bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/RemoveProfilesOperationTest.java delete mode 100644 bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/IUPropertyUtilsTest.java create mode 100644 bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/TranslationSupportTests.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/.externalToolBuilders/New_Builder.launch delete mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/IUPropertyUtils.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/AllTests.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/ExpressionTest.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/FilterTest.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/perf/MetadataRepositoryPerformanceTest.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/perf/ProvisioningPerformanceTest.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/perf/PublisherPerformanceTest.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AbsolutePlanTest.java delete mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ORTesting.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestMultiplePatch2.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestMultiplePatch3.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/UpdateQueryTest.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/AllTests.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/EvaluatorTest.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/PerformanceTest.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/TestQueryReimplementation.java create mode 100644 bundles/org.eclipse.equinox.p2.tests/testData/ProfilePreferencesTest/with(invalid)chars/org.eclipse.equinox.p2.engine/profileRegistry/TestProfile.profile/.data/.settings/org.eclipse.equinox.p2.ui.sdk.prefs create mode 100644 bundles/org.eclipse.equinox.p2.tests/testData/ProfilePreferencesTest/with(invalid)chars/org.eclipse.equinox.p2.engine/profileRegistry/TestProfile.profile/1345.profile.gz create mode 100644 bundles/org.eclipse.equinox.p2.tests/testData/ProfilePreferencesTest/with(invalid)chars/p2/org.eclipse.equinox.p2.engine/profileRegistry/TestProfile.profile/1345.profile.gz create mode 100644 bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationCache.java create mode 100644 bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationIO.java create mode 100644 bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/p2/touchpoint/eclipse/query/OSGiBundleQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/p2/touchpoint/eclipse/query/package.html delete mode 100644 bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/AddArtifactRepositoryOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/AddMetadataRepositoryOperation.java create mode 100644 bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/AddProfileJob.java create mode 100644 bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ArtifactRepositoryTracker.java create mode 100644 bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/MetadataRepositoryTracker.java create mode 100644 bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProfileFactory.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RefreshArtifactRepositoriesOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RefreshMetadataRepositoriesOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RemoveArtifactRepositoryOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RemoveMetadataRepositoryOperation.java create mode 100644 bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RemoveProfilesJob.java create mode 100644 bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/close.gif create mode 100644 bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/close_hot.gif create mode 100644 bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/update.gif create mode 100644 bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/update_problems.gif delete mode 100644 bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdateAction.java create mode 100644 bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/DownloadPhaseSet.java create mode 100644 bundles/org.eclipse.equinox.p2.ui.sdk/OSGI-INF/licenseManager_component.xml delete mode 100644 bundles/org.eclipse.equinox.p2.ui.sdk/OSGI-INF/serviceui_component.xml create mode 100644 bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/SimpleLicenseManager.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/OSGI-INF/repositoryTracker_component.xml create mode 100644 bundles/org.eclipse.equinox.p2.ui/OSGI-INF/serviceui_component.xml delete mode 100644 bundles/org.eclipse.equinox.p2.ui/icons/tool/close.gif delete mode 100644 bundles/org.eclipse.equinox.p2.ui/icons/tool/close_hot.gif delete mode 100644 bundles/org.eclipse.equinox.p2.ui/icons/tool/update.gif delete mode 100644 bundles/org.eclipse.equinox.p2.ui/icons/tool/update_problems.gif delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/BatchChangeBeginningEvent.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/BatchChangeCompleteEvent.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ColocatedRepositoryTracker.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/DefaultMetadataURLValidator.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/DefaultQueryProvider.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ElementQueryDescriptor.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ElementWrapper.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/IProvHelpContextIds.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/PlanAnalyzer.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUI.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIImages.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIProvisioningListener.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvisioningOperationRunner.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryProvider.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryableArtifactRepositoryManager.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryableMetadataRepositoryManager.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryableRepositoryManager.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/RepositoryLocationQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/RepositoryOperationBeginningEvent.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/RepositoryOperationEndingEvent.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/SimpleLicenseManager.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/UIRepositoryEvent.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/UpdateManagerCompatibility.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ValidationDialogServiceUI.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ColocatedRepositoryAction.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ExistingIUInProfileAction.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/InstallAction.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ProfileModificationAction.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/PropertyDialogAction.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ProvisioningAction.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/RefreshAction.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/RemoveColocatedRepositoryAction.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/UninstallAction.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/UpdateAction.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AddRepositoryDialog.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AvailableIUGroup.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ICopyable.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IRepositorySelectionListener.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUCopyrightPropertyPage.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUGeneralInfoPropertyPage.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IULicensePropertyPage.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/InstallWizard.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/InstalledIUGroup.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/PreselectedIUInstallWizard.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProvisioningWizardDialog.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/RepositorySelectionGroup.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UninstallWizard.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UpdateWizard.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ArtifactRepositories.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/IRepositoryElement.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/IUElementListRoot.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/InstalledIUElement.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/MetadataRepositories.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ProfileElement.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/Profiles.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/Updates.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/AnyRequiredCapabilityQuery.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/ArtifactKeyWrapper.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/ArtifactRepositoryElementWrapper.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/IUViewQueryContext.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUColumnConfig.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUComparator.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUDragAdapter.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/InstallIUDropAdapter.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/ProvElementComparer.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/ProvElementContentProvider.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/ProvElementLabelProvider.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/RepositoryContentProvider.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/StructuredViewerProvisioningListener.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ElementQueryDescriptor.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ElementWrapper.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/IProvHelpContextIds.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/IStatusCodes.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/IUPropertyUtils.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProfileFactory.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvUI.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvUIImages.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvUIProvisioningListener.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvisioningOperationRunner.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/QueryableArtifactRepositoryManager.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/QueryableMetadataRepositoryManager.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/QueryableRepositoryManager.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/RepositoryLocationQuery.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ResolutionResult.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/UpdateManagerCompatibility.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ValidationDialogServiceUI.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ColocatedRepositoryAction.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ExistingIUInProfileAction.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/InstallAction.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ProfileModificationAction.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/PropertyDialogAction.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ProvisioningAction.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/RefreshAction.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/RemoveColocatedRepositoryAction.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/UninstallAction.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/UpdateAction.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/AcceptLicensesWizardPage.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/AddRepositoryDialog.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/AvailableIUGroup.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IRepositorySelectionListener.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IUCopyrightPropertyPage.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IUGeneralInfoPropertyPage.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IULicensePropertyPage.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/InstallWizard.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/InstalledIUGroup.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/InstalledSoftwarePage.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/PreselectedIUInstallWizard.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/ProvisioningWizardDialog.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RepositoryManipulationPage.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RepositorySelectionGroup.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RevertProfilePage.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/UninstallWizard.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/UpdateWizard.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/ArtifactRepositories.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/IRepositoryElement.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/IUElementListRoot.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/InstalledIUElement.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/MetadataRepositories.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/ProfileElement.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/Profiles.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/Updates.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/AddColocatedRepositoryOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/AddProfileOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/AddRepositoryOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/DownloadPhaseSet.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/PlannerResolutionOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProfileModificationOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningUtil.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RemoveColocatedRepositoryOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RemoveProfilesOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RemoveRepositoryOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RepositoryOperation.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/SizingPhaseSet.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/ColocatedRepositoryManipulator.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/IProfileChooser.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/IUViewQueryContext.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/LicenseManager.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/PlanValidator.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/Policy.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/QueryProvider.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/RepositoryLocationValidator.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/RepositoryManipulator.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/IUColumnConfig.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/IUComparator.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/IUDragAdapter.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/InstallIUDropAdapter.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/ProvElementComparer.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/ProvElementContentProvider.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/ProvElementLabelProvider.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/RepositoryContentProvider.java delete mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/StructuredViewerProvisioningListener.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/AcceptLicensesWizardPage.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/ICopyable.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/InstalledSoftwarePage.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/LicenseManager.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/LoadMetadataRepositoryJob.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/Policy.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/ProvisioningUI.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/RepositoryManipulationPage.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/RevertProfilePage.java create mode 100644 bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/package.html create mode 100644 bundles/org.eclipse.equinox.p2.updatesite/.settings/org.eclipse.jdt.launching.prefs create mode 100644 bundles/org.eclipse.equinox.simpleconfigurator.manipulator/OSGI-INF/configurator.xml delete mode 100644 bundles/org.eclipse.equinox.simpleconfigurator.manipulator/src/org/eclipse/equinox/internal/simpleconfigurator/manipulator/Activator.java delete mode 100644 examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/Messages.java delete mode 100644 examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/messages.properties create mode 100644 org.eclipse.equinox.p2.releng/R3_6_api_cleanup_projectSet.psf create mode 100644 org.eclipse.equinox.p2.releng/mylyn-discovery.psf create mode 100644 org.eclipse.equinox.p2.releng/p2_users_R_3_6_api_cleanup_projectSet.psf diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/.classpath b/bundles/org.eclipse.equinox.p2.artifact.optimizers/.classpath index 7cdeb7319..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/.classpath +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/.classpath @@ -1,7 +1,7 @@ - - + + diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.artifact.optimizers/.settings/org.eclipse.jdt.core.prefs index d1e9ee398..f8cf8a7e7 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Mon Nov 05 16:53:31 EST 2007 +#Wed Dec 30 08:04:56 CET 2009 eclipse.preferences.version=1 instance/org.eclipse.core.net/org.eclipse.core.net.hasMigrated=true org.eclipse.jdt.core.builder.cleanOutputFolder=clean @@ -8,24 +8,24 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=warning @@ -83,7 +83,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enab org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 @@ -155,7 +155,6 @@ org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.artifact.optimizers/META-INF/MANIFEST.MF index e0b0eaeab..935450d76 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/META-INF/MANIFEST.MF @@ -11,19 +11,24 @@ Import-Package: ie.wombat.jbdiff, org.eclipse.equinox.internal.p2.core.helpers, org.eclipse.equinox.internal.p2.metadata, org.eclipse.equinox.internal.p2.sar, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing, - org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.repository, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.artifact.spi, org.eclipse.internal.provisional.equinox.p2.jarprocessor, org.eclipse.osgi.util;version="1.1.0", org.osgi.framework;version="1.3.0" Bundle-ActivationPolicy: lazy Require-Bundle: org.eclipse.equinox.common, org.eclipse.equinox.p2.artifact.repository -Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, - J2SE-1.4 +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 Export-Package: org.eclipse.equinox.internal.p2.artifact.optimizers;x-friends:="org.eclipse.equinox.p2.artifact.processors", org.eclipse.equinox.internal.p2.artifact.optimizers.jardelta;x-internal:=true, org.eclipse.equinox.internal.p2.artifact.optimizers.jbdiff;x-internal:=true, diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/build.properties b/bundles/org.eclipse.equinox.p2.artifact.optimizers/build.properties index 48a852fb1..d72e993c0 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/build.properties +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/build.properties @@ -14,3 +14,5 @@ bin.includes = META-INF/,\ .,\ plugin.xml,\ plugin.properties +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/AbstractDeltaStep.java b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/AbstractDeltaStep.java index ca7040f95..70e2966db 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/AbstractDeltaStep.java +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/AbstractDeltaStep.java @@ -11,14 +11,16 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.optimizers; +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; + import java.io.*; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.artifact.processing.AbstractBufferingStep; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; /** * The AbstractDeltaDiffStep is an abstract processing step that @@ -40,12 +42,12 @@ public abstract class AbstractDeltaStep extends AbstractBufferingStep { this.repository = repository; } - public void initialize(ProcessingStepDescriptor descriptor, IArtifactDescriptor context) { + public void initialize(IProcessingStepDescriptor descriptor, IArtifactDescriptor context) { super.initialize(descriptor, context); readArtifactKey(descriptor); } - protected void readArtifactKey(ProcessingStepDescriptor descriptor) { + protected void readArtifactKey(IProcessingStepDescriptor descriptor) { try { key = ArtifactKey.parse(descriptor.getData()); } catch (IllegalArgumentException e) { diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/VersionlessArtifactKey.java b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/VersionlessArtifactKey.java index 33a674532..d6d7d0213 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/VersionlessArtifactKey.java +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/VersionlessArtifactKey.java @@ -11,10 +11,10 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.optimizers; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; public class VersionlessArtifactKey extends ArtifactKey { diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/Application.java b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/Application.java index c66d2a8c2..d7ff5de5d 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/Application.java +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/Application.java @@ -15,9 +15,9 @@ import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.equinox.internal.p2.artifact.optimizers.Activator; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; /** * The optimizer Application for JBDiff based optimizations. @@ -29,7 +29,7 @@ public class Application implements IApplication { private int depth = 1; public Object start(IApplicationContext context) throws Exception { - Map args = context.getArguments(); + Map args = context.getArguments(); initializeFromArguments((String[]) args.get("application.args")); //$NON-NLS-1$ IArtifactRepository repository = setupRepository(artifactRepositoryLocation); new Optimizer(repository, width, depth).run(); @@ -37,7 +37,7 @@ public class Application implements IApplication { } private IArtifactRepository setupRepository(URI location) throws ProvisionException { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); + IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); if (manager == null) // TODO log here return null; diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/DeltaComputer.java b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/DeltaComputer.java index 099283bd5..62955636f 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/DeltaComputer.java +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/DeltaComputer.java @@ -20,9 +20,9 @@ public class DeltaComputer { private File destination; private ZipFile baseJar; private ZipFile targetJar; - private Set baseEntries; - private ArrayList additions; - private ArrayList changes; + private Set baseEntries; + private ArrayList additions; + private ArrayList changes; private ZipFile manifestJar = null; public DeltaComputer(File base, File target, File destination) { @@ -53,14 +53,14 @@ public class DeltaComputer { // write out the removals. These are all the entries left in the baseEntries // since they were not seen in the targetJar. Here just write out an empty // entry with a name that signals the delta processor to delete. - for (Iterator i = baseEntries.iterator(); i.hasNext();) - writeEntry(result, new ZipEntry(((String) i.next()) + ".delete"), null, false); + for (String baseEntry : baseEntries) + writeEntry(result, new ZipEntry(baseEntry + ".delete"), null, false); // write out the additions. - for (Iterator i = additions.iterator(); i.hasNext();) - writeEntry(result, (ZipEntry) i.next(), targetJar, false); + for (ZipEntry entry : additions) + writeEntry(result, entry, targetJar, false); // write out the changes. - for (Iterator i = changes.iterator(); i.hasNext();) - writeEntry(result, (ZipEntry) i.next(), targetJar, false); + for (ZipEntry entry : changes) + writeEntry(result, entry, targetJar, false); } finally { if (result != null) result.close(); @@ -116,12 +116,12 @@ public class DeltaComputer { } private void computeDelta() throws IOException { - changes = new ArrayList(); - additions = new ArrayList(); + changes = new ArrayList(); + additions = new ArrayList(); // start out assuming that all the base entries are being removed baseEntries = getEntries(baseJar); - for (Enumeration e = targetJar.entries(); e.hasMoreElements();) - check((ZipEntry) e.nextElement(), targetJar); + for (Enumeration e = targetJar.entries(); e.hasMoreElements();) + check(e.nextElement(), targetJar); } private boolean openJars() { @@ -188,10 +188,10 @@ public class DeltaComputer { return true; } - private Set getEntries(ZipFile jar) { - HashSet result = new HashSet(jar.size()); - for (Enumeration e = jar.entries(); e.hasMoreElements();) { - ZipEntry entry = (ZipEntry) e.nextElement(); + private Set getEntries(ZipFile jar) { + HashSet result = new HashSet(jar.size()); + for (Enumeration e = jar.entries(); e.hasMoreElements();) { + ZipEntry entry = e.nextElement(); checkForManifest(entry, jar); result.add(entry.getName()); } diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/JarDeltaOptimizerStep.java b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/JarDeltaOptimizerStep.java index f26de9b8e..b238be76b 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/JarDeltaOptimizerStep.java +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/JarDeltaOptimizerStep.java @@ -17,8 +17,8 @@ import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.artifact.optimizers.AbstractDeltaStep; import org.eclipse.equinox.internal.p2.artifact.optimizers.Activator; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; /** * The JAR delta expects an input containing normal ".jar" data. diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/Optimizer.java b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/Optimizer.java index 24d9e84ee..8caceffb1 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/Optimizer.java +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jardelta/Optimizer.java @@ -11,7 +11,13 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.optimizers.jardelta; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.p2.query.IQueryResult; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; import java.io.IOException; import java.io.OutputStream; @@ -19,10 +25,11 @@ import java.util.*; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; +import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepHandler; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; public class Optimizer { @@ -33,8 +40,8 @@ public class Optimizer { private static final String JAR_DELTA_FORMAT = "jarDelta"; //$NON-NLS-1$ private static final String JAR_DELTA_PATCH_STEP = "org.eclipse.equinox.p2.processing.JarDeltaPatchStep"; //$NON-NLS-1$ - private static final Comparator ARTIFACT_DESCRIPTOR_VERSION_COMPARATOR = new ArtifactDescriptorVersionComparator(); - private static final Comparator ARTIFACT_KEY_VERSION_COMPARATOR = new ArtifactKeyVersionComparator(); + private static final Comparator ARTIFACT_DESCRIPTOR_VERSION_COMPARATOR = new ArtifactDescriptorVersionComparator(); + private static final Comparator ARTIFACT_KEY_VERSION_COMPARATOR = new ArtifactKeyVersionComparator(); /** * This optimizer performs delta generation based on (currently) jbdiff. @@ -72,8 +79,9 @@ public class Optimizer { } public void run() { - System.out.println("Starting delta (jardelta) optimizations (width=" + width + ", depth=" + depth + ")"); - IArtifactKey[][] keys = getSortedRelatedArtifactKeys(repository.getArtifactKeys()); + System.out.println("Starting delta (jardelta) optimizations (width=" + width + ", depth=" + depth + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + IQueryResult queryResult = repository.query(ArtifactKeyQuery.ALL_KEYS, null); + IArtifactKey[][] keys = getSortedRelatedArtifactKeys(queryResult); for (int i = 0; i < keys.length; i++) { if (keys[i].length < 2) // Nothing to diff here! @@ -85,7 +93,7 @@ public class Optimizer { optimize(keys[i], key); } } - System.out.println("Done."); + System.out.println("Done."); //$NON-NLS-1$ } @@ -125,50 +133,50 @@ public class Optimizer { * @param artifactKeys * @return the sorted artifact keys */ - private IArtifactKey[][] getSortedRelatedArtifactKeys(IArtifactKey[] artifactKeys) { - Map map = new HashMap(); - for (int i = 0; i < artifactKeys.length; i++) { - IArtifactKey freeKey = getVersionlessKey(artifactKeys[i]); - List values = (List) map.get(freeKey); + private IArtifactKey[][] getSortedRelatedArtifactKeys(IQueryResult artifactKeys) { + Map> map = new HashMap>(); + for (Iterator iter = artifactKeys.iterator(); iter.hasNext();) { + IArtifactKey nxt = iter.next(); + IArtifactKey freeKey = getVersionlessKey(nxt); + List values = map.get(freeKey); if (values == null) { - values = new ArrayList(); + values = new ArrayList(); map.put(freeKey, values); } - values.add(artifactKeys[i]); + values.add(nxt); } IArtifactKey[][] lists = new IArtifactKey[map.size()][]; int i = 0; - for (Iterator iterator = map.values().iterator(); iterator.hasNext();) { - List artifactKeyList = (List) iterator.next(); - IArtifactKey[] relatedArtifactKeys = (IArtifactKey[]) artifactKeyList.toArray(new IArtifactKey[artifactKeyList.size()]); + for (List artifactKeyList : map.values()) { + IArtifactKey[] relatedArtifactKeys = artifactKeyList.toArray(new IArtifactKey[artifactKeyList.size()]); Arrays.sort(relatedArtifactKeys, ARTIFACT_KEY_VERSION_COMPARATOR); lists[i++] = relatedArtifactKeys; } int candidates = 0; for (int ii = 0; ii < lists.length; ii++) { for (int jj = 0; jj < lists[ii].length; jj++) { - System.out.println(lists[ii][jj] + ", "); + System.out.println(lists[ii][jj] + ", "); //$NON-NLS-1$ } - System.out.println(""); + System.out.println(""); //$NON-NLS-1$ if (lists[ii].length > 1) candidates++; } - System.out.println("Candidates found: " + candidates); + System.out.println("Candidates found: " + candidates); //$NON-NLS-1$ return lists; } private void optimize(IArtifactDescriptor canonical, IArtifactKey[] relatedArtifactKeys) { - System.out.println("Optimizing " + canonical); + System.out.println("Optimizing " + canonical); //$NON-NLS-1$ IArtifactDescriptor[] descriptors = getSortedCompletePredecessors(canonical.getArtifactKey(), relatedArtifactKeys); int minDepth = Math.min(depth, descriptors.length); for (int i = 0; i < minDepth; i++) { - System.out.println("\t with jar delta against " + descriptors[i].getArtifactKey()); + System.out.println("\t with jar delta against " + descriptors[i].getArtifactKey()); //$NON-NLS-1$ String predecessorData = descriptors[i].getArtifactKey().toExternalForm(); ArtifactDescriptor newDescriptor = new ArtifactDescriptor(canonical); - ProcessingStepDescriptor patchStep = new ProcessingStepDescriptor(JAR_DELTA_PATCH_STEP, predecessorData, true); - ProcessingStepDescriptor[] steps = new ProcessingStepDescriptor[] {patchStep}; + IProcessingStepDescriptor patchStep = new ProcessingStepDescriptor(JAR_DELTA_PATCH_STEP, predecessorData, true); + IProcessingStepDescriptor[] steps = new IProcessingStepDescriptor[] {patchStep}; newDescriptor.setProcessingSteps(steps); newDescriptor.setProperty(IArtifactDescriptor.FORMAT, JAR_DELTA_FORMAT); OutputStream repositoryStream = null; @@ -211,7 +219,7 @@ public class Optimizer { private IArtifactDescriptor[] getSortedCompletePredecessors(IArtifactKey artifactKey, IArtifactKey[] relatedArtifactKeys) { // get all artifact keys - List completeDescriptors = new ArrayList(relatedArtifactKeys.length); + List completeDescriptors = new ArrayList(relatedArtifactKeys.length); for (int i = 0; i < relatedArtifactKeys.length; i++) { // if we find ´our self´ skip if (relatedArtifactKeys[i].equals(artifactKey)) @@ -226,7 +234,7 @@ public class Optimizer { } } - IArtifactDescriptor[] completeSortedDescriptors = (IArtifactDescriptor[]) completeDescriptors.toArray(new IArtifactDescriptor[completeDescriptors.size()]); + IArtifactDescriptor[] completeSortedDescriptors = completeDescriptors.toArray(new IArtifactDescriptor[completeDescriptors.size()]); // Sort, so to allow a depth lookup! Arrays.sort(completeSortedDescriptors, ARTIFACT_DESCRIPTOR_VERSION_COMPARATOR); return completeSortedDescriptors; @@ -243,15 +251,15 @@ public class Optimizer { return descriptor.getProcessingSteps().length == 0; } - static final class ArtifactDescriptorVersionComparator implements Comparator { - public int compare(Object artifactDescriptor0, Object artifactDescriptor1) { - return -1 * ((IArtifactDescriptor) artifactDescriptor0).getArtifactKey().getVersion().compareTo(((IArtifactDescriptor) artifactDescriptor1).getArtifactKey().getVersion()); + static final class ArtifactDescriptorVersionComparator implements Comparator { + public int compare(IArtifactDescriptor artifactDescriptor0, IArtifactDescriptor artifactDescriptor1) { + return -1 * artifactDescriptor0.getArtifactKey().getVersion().compareTo(artifactDescriptor1.getArtifactKey().getVersion()); } } - static final class ArtifactKeyVersionComparator implements Comparator { - public int compare(Object artifactKey0, Object artifactKey1) { - return -1 * ((IArtifactKey) artifactKey0).getVersion().compareTo(((IArtifactKey) artifactKey1).getVersion()); + static final class ArtifactKeyVersionComparator implements Comparator { + public int compare(IArtifactKey artifactKey0, IArtifactKey artifactKey1) { + return -1 * artifactKey0.getVersion().compareTo(artifactKey1.getVersion()); } } } diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/Application.java b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/Application.java index c5289ea13..6d404aa3b 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/Application.java +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/Application.java @@ -9,15 +9,16 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.optimizers.jbdiff; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.net.URI; import java.util.Map; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.equinox.internal.p2.artifact.optimizers.Activator; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; /** * The optimizer Application for JBDiff based optimizations. @@ -30,7 +31,7 @@ public class Application implements IApplication { private boolean nosar; public Object start(IApplicationContext context) throws Exception { - Map args = context.getArguments(); + Map args = context.getArguments(); initializeFromArguments((String[]) args.get("application.args")); //$NON-NLS-1$ IArtifactRepository repository = setupRepository(artifactRepositoryLocation); new Optimizer(repository, width, depth, nosar).run(); @@ -38,7 +39,7 @@ public class Application implements IApplication { } private IArtifactRepository setupRepository(URI location) throws ProvisionException { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); + IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); if (manager == null) // TODO log here return null; diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/JBDiffStep.java b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/JBDiffStep.java index 63fca12cf..d8c726cf0 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/JBDiffStep.java +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/JBDiffStep.java @@ -16,8 +16,8 @@ import java.io.*; import org.eclipse.equinox.internal.p2.artifact.optimizers.AbstractDeltaStep; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; import org.eclipse.equinox.internal.p2.sar.DirectByteArrayOutputStream; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; /** * diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/JBDiffZipStep.java b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/JBDiffZipStep.java index 31ab41b60..2b926fdc5 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/JBDiffZipStep.java +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/JBDiffZipStep.java @@ -17,8 +17,8 @@ import java.io.IOException; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; import org.eclipse.equinox.internal.p2.sar.DirectByteArrayOutputStream; import org.eclipse.equinox.internal.p2.sar.SarUtil; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; public class JBDiffZipStep extends JBDiffStep { diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/Optimizer.java b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/Optimizer.java index 33b50566f..690e8216e 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/Optimizer.java +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/jbdiff/Optimizer.java @@ -17,10 +17,14 @@ import java.util.*; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.artifact.optimizers.VersionlessArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; +import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepHandler; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; public class Optimizer { @@ -32,8 +36,8 @@ public class Optimizer { private static final String JBPATCH_STEP_ID = "org.eclipse.equinox.p2.repository.JBPatchStep"; //$NON-NLS-1$ private static final String JBPATCH_STEP_ZIP_ID = "org.eclipse.equinox.p2.repository.JBPatchZipStep"; //$NON-NLS-1$ - private static final Comparator ARTIFACT_DESCRIPTOR_VERSION_COMPARATOR = new ArtifactDescriptorVersionComparator(); - private static final Comparator ARTIFACT_KEY_VERSION_COMPARATOR = new ArtifactKeyVersionComparator(); + private static final Comparator ARTIFACT_DESCRIPTOR_VERSION_COMPARATOR = new ArtifactDescriptorVersionComparator(); + private static final Comparator ARTIFACT_KEY_VERSION_COMPARATOR = new ArtifactKeyVersionComparator(); /** * This optimizer performs delta generation based on (currently) jbdiff. @@ -74,7 +78,8 @@ public class Optimizer { public void run() { System.out.println("Starting delta (jbdiff) optimizations (width=" + width + ", depth=" + depth + ", nosar=" + nosar + ")"); - IArtifactKey[][] keys = getSortedRelatedArtifactKeys(repository.getArtifactKeys()); + IQueryResult queryResult = repository.query(ArtifactKeyQuery.ALL_KEYS, null); + IArtifactKey[][] keys = getSortedRelatedArtifactKeys(queryResult); for (int i = 0; i < keys.length; i++) { if (keys[i].length < 2) // Nothing to diff here! @@ -136,22 +141,22 @@ public class Optimizer { * @param artifactKeys * @return the sorted artifact keys */ - private IArtifactKey[][] getSortedRelatedArtifactKeys(IArtifactKey[] artifactKeys) { - Map map = new HashMap(); - for (int i = 0; i < artifactKeys.length; i++) { - IArtifactKey freeKey = new VersionlessArtifactKey(artifactKeys[i]); - List values = (List) map.get(freeKey); + private IArtifactKey[][] getSortedRelatedArtifactKeys(IQueryResult artifactKeys) { + Map> map = new HashMap>(); + for (Iterator iter = artifactKeys.iterator(); iter.hasNext();) { + IArtifactKey nxt = iter.next(); + IArtifactKey freeKey = new VersionlessArtifactKey(nxt); + List values = map.get(freeKey); if (values == null) { - values = new ArrayList(); + values = new ArrayList(); map.put(freeKey, values); } - values.add(artifactKeys[i]); + values.add(nxt); } IArtifactKey[][] lists = new IArtifactKey[map.size()][]; int i = 0; - for (Iterator iterator = map.values().iterator(); iterator.hasNext();) { - List artifactKeyList = (List) iterator.next(); - IArtifactKey[] relatedArtifactKeys = (IArtifactKey[]) artifactKeyList.toArray(new IArtifactKey[artifactKeyList.size()]); + for (List artifactKeyList : map.values()) { + IArtifactKey[] relatedArtifactKeys = artifactKeyList.toArray(new IArtifactKey[artifactKeyList.size()]); Arrays.sort(relatedArtifactKeys, ARTIFACT_KEY_VERSION_COMPARATOR); lists[i++] = relatedArtifactKeys; } @@ -179,8 +184,8 @@ public class Optimizer { System.out.println("\t with " + strategy + " against " + descriptors[i].getArtifactKey()); String predecessorData = descriptors[i].getArtifactKey().toExternalForm(); ArtifactDescriptor newDescriptor = new ArtifactDescriptor(complete); - ProcessingStepDescriptor patchStep = new ProcessingStepDescriptor(strategy, predecessorData, true); - ProcessingStepDescriptor[] steps = new ProcessingStepDescriptor[] {patchStep}; + IProcessingStepDescriptor patchStep = new ProcessingStepDescriptor(strategy, predecessorData, true); + IProcessingStepDescriptor[] steps = new IProcessingStepDescriptor[] {patchStep}; newDescriptor.setProcessingSteps(steps); newDescriptor.setProperty(IArtifactDescriptor.FORMAT, strategy); OutputStream repositoryStream = null; @@ -229,7 +234,7 @@ public class Optimizer { private IArtifactDescriptor[] getSortedCompletePredecessors(IArtifactKey artifactKey, IArtifactKey[] relatedArtifactKeys) { // get all artifact keys - List completeDescriptors = new ArrayList(relatedArtifactKeys.length); + List completeDescriptors = new ArrayList(relatedArtifactKeys.length); for (int i = 0; i < relatedArtifactKeys.length; i++) { // if we find ´our self´ skip if (relatedArtifactKeys[i].equals(artifactKey)) @@ -244,7 +249,7 @@ public class Optimizer { } } - IArtifactDescriptor[] completeSortedDescriptors = (IArtifactDescriptor[]) completeDescriptors.toArray(new IArtifactDescriptor[completeDescriptors.size()]); + IArtifactDescriptor[] completeSortedDescriptors = completeDescriptors.toArray(new IArtifactDescriptor[completeDescriptors.size()]); // Sort, so to allow a depth lookup! Arrays.sort(completeSortedDescriptors, ARTIFACT_DESCRIPTOR_VERSION_COMPARATOR); return completeSortedDescriptors; @@ -261,15 +266,15 @@ public class Optimizer { return descriptor.getProcessingSteps().length == 0; } - static final class ArtifactDescriptorVersionComparator implements Comparator { - public int compare(Object artifactDescriptor0, Object artifactDescriptor1) { - return -1 * ((IArtifactDescriptor) artifactDescriptor0).getArtifactKey().getVersion().compareTo(((IArtifactDescriptor) artifactDescriptor1).getArtifactKey().getVersion()); + static final class ArtifactDescriptorVersionComparator implements Comparator { + public int compare(IArtifactDescriptor artifactDescriptor0, IArtifactDescriptor artifactDescriptor1) { + return -1 * artifactDescriptor0.getArtifactKey().getVersion().compareTo(artifactDescriptor1.getArtifactKey().getVersion()); } } - static final class ArtifactKeyVersionComparator implements Comparator { - public int compare(Object artifactKey0, Object artifactKey1) { - return -1 * ((IArtifactKey) artifactKey0).getVersion().compareTo(((IArtifactKey) artifactKey1).getVersion()); + static final class ArtifactKeyVersionComparator implements Comparator { + public int compare(IArtifactKey artifactKey0, IArtifactKey artifactKey1) { + return -1 * artifactKey0.getVersion().compareTo(artifactKey1.getVersion()); } } } diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/pack200/Application.java b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/pack200/Application.java index f6ddeb69f..b7adf678a 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/pack200/Application.java +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/pack200/Application.java @@ -9,15 +9,16 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.optimizers.pack200; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.net.URI; import java.util.Map; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.equinox.internal.p2.artifact.optimizers.Activator; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; public class Application implements IApplication { //Application return code @@ -30,7 +31,7 @@ public class Application implements IApplication { private URI artifactRepositoryLocation; public Object start(IApplicationContext context) throws Exception { - Map args = context.getArguments(); + Map args = context.getArguments(); initializeFromArguments((String[]) args.get("application.args")); //$NON-NLS-1$ IArtifactRepository repository = setupRepository(artifactRepositoryLocation); if (!repository.isModifiable()) @@ -40,7 +41,7 @@ public class Application implements IApplication { } private IArtifactRepository setupRepository(URI location) throws ProvisionException { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); + IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); if (manager == null) // TODO log here return null; diff --git a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/pack200/Optimizer.java b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/pack200/Optimizer.java index e2fa5ac37..9f91321b5 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/pack200/Optimizer.java +++ b/bundles/org.eclipse.equinox.p2.artifact.optimizers/src/org/eclipse/equinox/internal/p2/artifact/optimizers/pack200/Optimizer.java @@ -12,16 +12,20 @@ package org.eclipse.equinox.internal.p2.artifact.optimizers.pack200; import java.io.IOException; import java.io.OutputStream; +import java.util.Iterator; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; +import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepHandler; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; import org.eclipse.osgi.util.NLS; public class Optimizer { - private static final String PACKED_FORMAT = "packed"; //$NON-NLS-1$ private IArtifactRepository repository; public Optimizer(IArtifactRepository repository) { @@ -29,9 +33,9 @@ public class Optimizer { } public void run() { - IArtifactKey[] keys = repository.getArtifactKeys(); - for (int i = 0; i < keys.length; i++) { - IArtifactKey key = keys[i]; + IQueryResult keys = repository.query(ArtifactKeyQuery.ALL_KEYS, null); + for (Iterator iterator = keys.iterator(); iterator.hasNext();) { + IArtifactKey key = iterator.next(); if (!key.getClassifier().equals("plugin")) //$NON-NLS-1$ continue; IArtifactDescriptor[] descriptors = repository.getArtifactDescriptors(key); @@ -58,9 +62,9 @@ public class Optimizer { private void optimize(IArtifactDescriptor descriptor) { ArtifactDescriptor newDescriptor = new ArtifactDescriptor(descriptor); - ProcessingStepDescriptor[] steps = new ProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; //$NON-NLS-1$ + IProcessingStepDescriptor[] steps = new IProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; //$NON-NLS-1$ newDescriptor.setProcessingSteps(steps); - newDescriptor.setProperty(IArtifactDescriptor.FORMAT, PACKED_FORMAT); + newDescriptor.setProperty(IArtifactDescriptor.FORMAT, IArtifactDescriptor.FORMAT_PACKED); OutputStream repositoryStream = null; try { repositoryStream = repository.getOutputStream(newDescriptor); @@ -97,7 +101,7 @@ public class Optimizer { } private boolean isOptimized(IArtifactDescriptor descriptor) { - return PACKED_FORMAT.equals(descriptor.getProperty(IArtifactDescriptor.FORMAT)); + return IArtifactDescriptor.FORMAT_PACKED.equals(descriptor.getProperty(IArtifactDescriptor.FORMAT)); } } diff --git a/bundles/org.eclipse.equinox.p2.artifact.processors/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.artifact.processors/META-INF/MANIFEST.MF index a4a5c3ecb..440c0e880 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.processors/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.artifact.processors/META-INF/MANIFEST.MF @@ -12,11 +12,12 @@ Import-Package: ie.wombat.jbdiff, org.eclipse.equinox.internal.p2.artifact.optimizers, org.eclipse.equinox.internal.p2.core.helpers, org.eclipse.equinox.internal.p2.sar, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing, - org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.repository, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.artifact.spi, org.osgi.framework;version="1.4.0" Bundle-Vendor: %providerName Export-Package: org.eclipse.equinox.internal.p2.artifact.processors;x-internal:=true, diff --git a/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/AbstractDeltaProcessorStep.java b/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/AbstractDeltaProcessorStep.java index e4369e050..19a43cc41 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/AbstractDeltaProcessorStep.java +++ b/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/AbstractDeltaProcessorStep.java @@ -11,16 +11,17 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.processors; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; + +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; import java.net.URI; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.artifact.optimizers.AbstractDeltaStep; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.*; /** * The AbstractDeltaPatchStep is an abstract processing step that @@ -30,7 +31,7 @@ import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; */ public abstract class AbstractDeltaProcessorStep extends AbstractDeltaStep { - public void initialize(ProcessingStepDescriptor descriptor, IArtifactDescriptor context) { + public void initialize(IProcessingStepDescriptor descriptor, IArtifactDescriptor context) { super.initialize(descriptor, context); if (!getStatus().isOK()) return; @@ -43,7 +44,7 @@ public abstract class AbstractDeltaProcessorStep extends AbstractDeltaStep { private void fetchLocalArtifactRepository() { if (repository != null) return; - IArtifactRepositoryManager repoMgr = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); + IArtifactRepositoryManager repoMgr = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); if (repoMgr == null) { setStatus(new Status(IStatus.ERROR, Activator.ID, "Could not get artifact repository manager.")); return; diff --git a/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/jardelta/JarDeltaProcessorStep.java b/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/jardelta/JarDeltaProcessorStep.java index 42dda53ab..8c07924ff 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/jardelta/JarDeltaProcessorStep.java +++ b/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/jardelta/JarDeltaProcessorStep.java @@ -16,7 +16,7 @@ import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.artifact.processors.AbstractDeltaProcessorStep; import org.eclipse.equinox.internal.p2.artifact.processors.Activator; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; /** * Processor that takes a JAR delta and applies it. diff --git a/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/jbdiff/JBPatchStep.java b/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/jbdiff/JBPatchStep.java index 9ae9b2f92..c31b42309 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/jbdiff/JBPatchStep.java +++ b/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/jbdiff/JBPatchStep.java @@ -16,7 +16,7 @@ import java.io.*; import org.eclipse.equinox.internal.p2.artifact.processors.AbstractDeltaProcessorStep; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; import org.eclipse.equinox.internal.p2.sar.DirectByteArrayOutputStream; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; /** * The JBPatchStep patches a JBDiff based data. diff --git a/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/jbdiff/JBPatchZipStep.java b/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/jbdiff/JBPatchZipStep.java index 876a7e990..de4ff46ff 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/jbdiff/JBPatchZipStep.java +++ b/bundles/org.eclipse.equinox.p2.artifact.processors/src/org/eclipse/equinox/internal/p2/artifact/processors/jbdiff/JBPatchZipStep.java @@ -16,7 +16,7 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import org.eclipse.equinox.internal.p2.sar.DirectByteArrayOutputStream; import org.eclipse.equinox.internal.p2.sar.SarUtil; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; /** * The JBPatchZipStep patches a JBDiff based diff of zips/jars. diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/.classpath b/bundles/org.eclipse.equinox.p2.artifact.repository/.classpath index ef379494d..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/.classpath +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/.classpath @@ -1,8 +1,7 @@ - + - diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/.externalToolBuilders/org.eclipse.equinox.p2.artifact.repository buildAntTasks.xml.launch b/bundles/org.eclipse.equinox.p2.artifact.repository/.externalToolBuilders/org.eclipse.equinox.p2.artifact.repository buildAntTasks.xml.launch deleted file mode 100644 index c2ad0a0ec..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/.externalToolBuilders/org.eclipse.equinox.p2.artifact.repository buildAntTasks.xml.launch +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/.project b/bundles/org.eclipse.equinox.p2.artifact.repository/.project index ad19a3475..641a8f970 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/.project +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/.project @@ -20,16 +20,6 @@ - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.equinox.p2.artifact.repository buildAntTasks.xml.launch - - - org.eclipse.pde.api.tools.apiAnalysisBuilder diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.artifact.repository/.settings/org.eclipse.jdt.core.prefs index fc844dcb3..c75efa1c2 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Tue Dec 09 10:24:31 EST 2008 +#Tue Dec 22 19:31:57 CET 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.builder.cleanOutputFolder=clean org.eclipse.jdt.core.builder.duplicateResourceTask=warning @@ -7,17 +7,17 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning org.eclipse.jdt.core.compiler.problem.deadCode=warning @@ -26,7 +26,7 @@ org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=warning @@ -88,7 +88,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enab org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.artifact.repository/META-INF/MANIFEST.MF index 0f87eab08..f543187b6 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/META-INF/MANIFEST.MF @@ -5,34 +5,23 @@ Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-Localization: plugin Bundle-Version: 1.0.100.qualifier -Export-Package: org.eclipse.equinox.internal.p2.artifact.mirror;x-internal:=true, - org.eclipse.equinox.internal.p2.artifact.processing;x-friends:="org.eclipse.equinox.p2.artifact.processors,org.eclipse.equinox.p2.artifact.optimizers", +Export-Package: org.eclipse.equinox.internal.p2.artifact.processing;x-friends:="org.eclipse.equinox.p2.artifact.processors,org.eclipse.equinox.p2.artifact.optimizers", org.eclipse.equinox.internal.p2.artifact.processors.md5;x-internal:=true, org.eclipse.equinox.internal.p2.artifact.processors.pack200;x-friends:="org.eclipse.equinox.p2.artifact.processors,org.eclipse.equinox.p2.artifact.optimizers", - org.eclipse.equinox.internal.p2.artifact.repository;x-friends:="org.eclipse.equinox.p2.metadata.generator,org.eclipse.equinox.p2.publisher,org.eclipse.equinox.p2.reconciler.dropins", - org.eclipse.equinox.internal.p2.artifact.repository.simple;x-friends:="org.eclipse.equinox.p2.touchpoint.eclipse,org.eclipse.equinox.p2.tests", - org.eclipse.equinox.internal.provisional.p2.artifact.repository; - x-friends:="org.eclipse.equinox.p2.artifact.optimizers, - org.eclipse.equinox.p2.artifact.processors, - org.eclipse.equinox.p2.director.app, + org.eclipse.equinox.internal.p2.artifact.repository; + x-friends:="org.eclipse.equinox.p2.metadata.generator, + org.eclipse.equinox.p2.publisher, + org.eclipse.equinox.p2.reconciler.dropins, + org.eclipse.equinox.p2.ui, + org.eclipse.equinox.p2.directorywatcher, + org.eclipse.equinox.p2.repository.tools", + org.eclipse.equinox.internal.p2.artifact.repository.simple; + x-friends:="org.eclipse.equinox.p2.touchpoint.eclipse, + org.eclipse.equinox.p2.tests, org.eclipse.equinox.p2.directorywatcher, - org.eclipse.equinox.p2.metadata.generator, org.eclipse.equinox.p2.updatesite, - org.eclipse.equinox.p2.engine, - org.eclipse.equinox.p2.touchpoint.eclipse, - org.eclipse.equinox.p2.ui.admin, - org.eclipse.equinox.p2.console, - org.eclipse.equinox.p2.ui, - org.eclipse.equinox.p2.ui.sdk, - org.eclipse.equinox.p2.touchpoint.natives, - org.eclipse.equinox.p2.extensionlocation, - org.eclipse.equinox.p2.garbagecollector, - org.eclipse.equinox.p2.reconciler.dropins, - org.eclipse.equinox.p2.installer, org.eclipse.equinox.p2.publisher, - org.eclipse.pde.ui, - org.eclipse.equinox.p2.repository.tools, - org.eclipse.pde.core", + org.eclipse.equinox.p2.extensionlocation", org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing; x-friends:="org.eclipse.equinox.p2.artifact.processors, org.eclipse.equinox.p2.artifact.optimizers, @@ -40,11 +29,6 @@ Export-Package: org.eclipse.equinox.internal.p2.artifact.mirror;x-internal:=true org.eclipse.equinox.p2.metadata.generator, org.eclipse.equinox.p2.ui, org.eclipse.equinox.p2.publisher, - org.eclipse.equinox.p2.updatesite", - org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository; - x-friends:="org.eclipse.equinox.p2.touchpoint.eclipse, - org.eclipse.equinox.p2.touchpoint.natives, - org.eclipse.equinox.p2.extensionlocation, org.eclipse.equinox.p2.updatesite" Import-Package: javax.xml.parsers, org.eclipse.core.runtime.jobs, @@ -55,26 +39,30 @@ Import-Package: javax.xml.parsers, org.eclipse.equinox.internal.p2.persistence, org.eclipse.equinox.internal.p2.repository, org.eclipse.equinox.internal.p2.repository.helpers, - org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.core.eventbus, - org.eclipse.equinox.internal.provisional.p2.core.location, org.eclipse.equinox.internal.provisional.p2.metadata, org.eclipse.equinox.internal.provisional.p2.repository, - org.eclipse.equinox.internal.provisional.spi.p2.repository, org.eclipse.equinox.p2.core, org.eclipse.equinox.p2.core.spi, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.artifact.spi, + org.eclipse.equinox.p2.repository.spi, org.eclipse.internal.provisional.equinox.p2.jarprocessor;resolution:=optional, org.eclipse.osgi.framework.log;version="1.0.0", org.eclipse.osgi.signedcontent;version="1.0.0", org.eclipse.osgi.util;version="1.1.0", org.osgi.framework;version="1.3.0", + org.osgi.service.prefs;version="1.1.1", org.osgi.util.tracker;version="1.4.0", org.w3c.dom, org.xml.sax;resolution:=optional Bundle-Activator: org.eclipse.equinox.internal.p2.artifact.repository.Activator Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: J2SE-1.4, +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, CDC-1.1/Foundation-1.1 Require-Bundle: org.eclipse.equinox.common;bundle-version="[3.5.0,4.0.0)", - org.eclipse.equinox.registry + org.eclipse.equinox.registry, + org.eclipse.equinox.p2.metadata Service-Component: OSGI-INF/repositoryManager.xml diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/OSGI-INF/repositoryManager.xml b/bundles/org.eclipse.equinox.p2.artifact.repository/OSGI-INF/repositoryManager.xml index c85058f8c..62a650ed3 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/OSGI-INF/repositoryManager.xml +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/OSGI-INF/repositoryManager.xml @@ -4,5 +4,5 @@ - + \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/build.properties b/bundles/org.eclipse.equinox.p2.artifact.repository/build.properties index 6a66d4e05..57d41ddb0 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/build.properties +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/build.properties @@ -4,13 +4,9 @@ bin.includes = META-INF/,\ plugin.xml,\ about.html,\ plugin.properties,\ - ant_tasks/artifactRepository-ant.jar,\ OSGI-INF/ -jars.compile.order = .,\ - ant_tasks/artifactRepository-ant.jar -output.ant_tasks/artifactRepository-ant.jar = bin_ant/ src.includes = about.html,\ schema/ source.. = src/ -source.ant_tasks/artifactRepository-ant.jar = src_ant/ -jars.extra.classpath = platform:/plugin/org.apache.ant/lib/ant.jar +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/buildAntTasks.xml b/bundles/org.eclipse.equinox.p2.artifact.repository/buildAntTasks.xml deleted file mode 100644 index 78fb71d9e..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/buildAntTasks.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/plugin.xml b/bundles/org.eclipse.equinox.p2.artifact.repository/plugin.xml index 4a2c12a20..7025c7f08 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/plugin.xml +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/plugin.xml @@ -13,7 +13,7 @@ - + @@ -27,55 +27,9 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/FileMirrorLog.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/FileMirrorLog.java deleted file mode 100644 index a0602b4d2..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/FileMirrorLog.java +++ /dev/null @@ -1,125 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.artifact.mirror; - -import java.io.*; -import java.util.Date; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.p2.artifact.repository.Messages; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; - -public class FileMirrorLog implements IArtifactMirrorLog { - - private static final String INDENT = "\t"; //$NON-NLS-1$ - private static final String SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$ - private BufferedWriter out; - private boolean consoleMessage = false; - private int minSeverity = IStatus.OK; - private boolean hasRoot = false; - - public FileMirrorLog(String location, int minSeverity, String root) { - this.minSeverity = minSeverity; - try { - File log = new File(location); - if (log.getParentFile().exists() || log.getParentFile().mkdirs()) { - out = new BufferedWriter(new FileWriter(log, true)); - if (root != null) { - log(root + " - " + new Date()); //$NON-NLS-1$ - hasRoot = true; - } - } else - throw new IOException(Messages.exception_unableToCreateParentDir); - } catch (IOException e) { - exceptionOccurred(null, e); - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.artifact.mirror.IArtifactMirrorLog#log(org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor, org.eclipse.core.runtime.IStatus) - */ - public void log(IArtifactDescriptor descriptor, IStatus status) { - if (status.getSeverity() >= minSeverity) { - log(descriptor.toString()); - log(status, INDENT); - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.artifact.mirror.IArtifactMirrorLog#log(org.eclipse.core.runtime.IStatus) - */ - public void log(IStatus status) { - log(status, ""); //$NON-NLS-1$ - } - - /* - * Write a status to the log, indenting it based on status depth. - * @param status the status to log - * @param depth the depth of the status - */ - private void log(IStatus status, String prefix) { - if (status.getSeverity() >= minSeverity) { - // Write status to log - log(prefix + status.getMessage()); - - // Write exception to log if applicable - String exceptionMessage = status.getException() != null ? status.getException().getMessage() : null; - if (exceptionMessage != null) - log(prefix + exceptionMessage); - - // Write the children of the status to the log - IStatus[] nestedStatus = status.getChildren(); - if (nestedStatus != null) - for (int i = 0; i < nestedStatus.length; i++) - log(nestedStatus[i], prefix + INDENT); - } - } - - /* - * Write a message to the log - * @param message the message to write - */ - private void log(String message) { - try { - out.write((hasRoot ? INDENT : "") + message + SEPARATOR); //$NON-NLS-1$ - } catch (IOException e) { - exceptionOccurred((hasRoot ? INDENT : "") + message, e); //$NON-NLS-1$ - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.artifact.mirror.IArtifactMirrorLog#close() - */ - public void close() { - try { - if (out != null) - out.close(); - } catch (IOException e) { - exceptionOccurred(null, e); - } - } - - /* - * Show an error message if this the first time, and print status messages. - */ - private void exceptionOccurred(String message, Exception e) { - if (!consoleMessage) { - System.err.println(Messages.MirrorLog_Exception_Occurred); - e.printStackTrace(System.err); - System.err.println(Messages.MirrorLog_Console_Log); - consoleMessage = true; - } - if (message != null) - System.out.println(message); - } -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/IArtifactMirrorLog.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/IArtifactMirrorLog.java deleted file mode 100644 index 959a7a35d..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/IArtifactMirrorLog.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.artifact.mirror; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; - -public interface IArtifactMirrorLog { - - // Log a status associated with a descriptor - public void log(IArtifactDescriptor descriptor, IStatus status); - - // Log a status - public void log(IStatus status); - - // Notify that logging is completed & cleanup resources - public void close(); -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/MirrorApplication.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/MirrorApplication.java deleted file mode 100644 index 83983b520..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/MirrorApplication.java +++ /dev/null @@ -1,263 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.artifact.mirror; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Map; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.app.IApplication; -import org.eclipse.equinox.app.IApplicationContext; -import org.eclipse.equinox.internal.p2.artifact.processors.md5.MD5ArtifactComparator; -import org.eclipse.equinox.internal.p2.artifact.repository.*; -import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.repository.helpers.RepositoryHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.osgi.framework.log.FrameworkLog; -import org.eclipse.osgi.util.NLS; - -/** - * An application that performs mirroring of artifacts between repositories. - */ -public class MirrorApplication implements IApplication { - - private URI sourceLocation; - private URI destinationLocation; - private URI baselineLocation; - private IArtifactRepository source; - private IArtifactRepository destination; - private IArtifactRepository baseline; - private boolean append = true; - private boolean raw = false; - private boolean failOnError = true; - private boolean validate = false; - private boolean verbose = false; - private IArtifactRepositoryManager cachedManager; - private boolean sourceLoaded = false; - private boolean destinationLoaded = false; - private boolean baselineLoaded = false; - private boolean compare = false; - private String comparatorID = MD5ArtifactComparator.MD5_COMPARATOR_ID; //use MD5 as default - private String destinationName; - private IArtifactMirrorLog mirrorLog; - private IArtifactMirrorLog comparatorLog; - - /* (non-Javadoc) - * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext) - */ - public Object start(IApplicationContext context) throws Exception { - try { - Map args = context.getArguments(); - initializeFromArguments((String[]) args.get(IApplicationContext.APPLICATION_ARGS)); - setupRepositories(); - - Mirroring mirroring = new Mirroring(source, destination, raw); - mirroring.setCompare(compare); - mirroring.setComparatorId(comparatorID); - mirroring.setBaseline(baseline); - mirroring.setValidate(validate); - if (comparatorLog != null) - mirroring.setComparatorLog(comparatorLog); - - IStatus result = mirroring.run(failOnError, verbose); - if (!result.isOK()) { - //only noteworthy statuses should be resulted from mirroring.run - if (result.matches(IStatus.INFO)) - System.err.println("Mirroring completed. Please check log file for more information."); //$NON-NLS-1$ - else - System.err.println("Mirroring completed with warnings and/or errors. Please check log file for more information."); //$NON-NLS-1$ - log(result); - } - return IApplication.EXIT_OK; - } catch (Exception e) { - System.err.println(e.getMessage()); - throw e; - } finally { - cleanup(); - } - } - - /* - * Return the artifact repository manager. We need to check the service here - * as well as creating one manually in case we are running a stand-alone application - * in which no one has registered a manager yet. - */ - private IArtifactRepositoryManager getManager() { - if (cachedManager != null) - return cachedManager; - IArtifactRepositoryManager result = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); - // service not available... create one and hang onto it - if (result == null) { - cachedManager = new ArtifactRepositoryManager(); - result = cachedManager; - } - return result; - } - - private void setupRepositories() throws ProvisionException { - if (destinationLocation == null || sourceLocation == null) - throw new IllegalStateException(Messages.exception_needSourceDestination); - - //Check if repositories are already loaded - sourceLoaded = getManager().contains(sourceLocation); - destinationLoaded = getManager().contains(destinationLocation); - - //must execute before initializeDestination is called - source = getManager().loadRepository(sourceLocation, 0, null); - destination = initializeDestination(); - - if (baselineLocation != null) { - baselineLoaded = getManager().contains(baselineLocation); - try { - baseline = getManager().loadRepository(baselineLocation, 0, null); - } catch (ProvisionException e) { - // catch the exception and log it. we will continue without doing a baseline comparison - System.err.println("Error occurred while trying to load baseline repository."); - e.printStackTrace(); - } - } - } - - private IArtifactRepository initializeDestination() throws ProvisionException { - try { - IArtifactRepository repository = getManager().loadRepository(destinationLocation, IRepositoryManager.REPOSITORY_HINT_MODIFIABLE, null); - if (repository != null && repository.isModifiable()) { - if (destinationName != null) - repository.setName(destinationName); - if (!append) - repository.removeAll(); - return repository; - } - } catch (ProvisionException e) { - //fall through and create a new repository below - } - //This code assumes source has been successfully loaded before this point - //No existing repository; create a new repository at destinationLocation but with source's attributes. - // TODO for now create a Simple repo by default. - return (IArtifactRepository) RepositoryHelper.validDestinationRepository(getManager().createRepository(destinationLocation, destinationName == null ? source.getName() : destinationName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, source.getProperties())); - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.app.IApplication#stop() - */ - public void stop() { - // nothing to do - } - - public void initializeFromArguments(String[] args) throws Exception { - if (args == null) - return; - - String comparatorLogLocation = null; - String mirrorLogLocation = null; - - for (int i = 0; i < args.length; i++) { - // check for args without parameters (i.e., a flag arg) - if (args[i].equalsIgnoreCase("-raw")) //$NON-NLS-1$ - raw = true; - if (args[i].equalsIgnoreCase("-ignoreErrors")) //$NON-NLS-1$ - failOnError = false; - if (args[i].equalsIgnoreCase("-verbose")) //$NON-NLS-1$ - verbose = true; - if (args[i].equalsIgnoreCase("-compare")) //$NON-NLS-1$ - compare = true; - if (args[i].equalsIgnoreCase("-validate")) //$NON-NLS-1$ - validate = true; - - // check for args with parameters. If we are at the last argument or - // if the next one has a '-' as the first character, then we can't have - // an arg with a param so continue. - if (i == args.length - 1 || args[i + 1].startsWith("-")) //$NON-NLS-1$ - continue; - String arg = args[++i]; - - if (args[i - 1].equalsIgnoreCase("-comparator")) //$NON-NLS-1$ - comparatorID = arg; - if (args[i - 1].equalsIgnoreCase("-comparatorLog")) //$NON-NLS-1$ - comparatorLogLocation = arg; - if (args[i - 1].equalsIgnoreCase("-destinationName")) //$NON-NLS-1$ - destinationName = arg; - if (args[i - 1].equalsIgnoreCase("-writeMode")) //$NON-NLS-1$ - if (args[i].equalsIgnoreCase("clean")) //$NON-NLS-1$ - append = false; - if (args[i - 1].equalsIgnoreCase("-log")) //$NON-NLS-1$ - mirrorLogLocation = arg; - - try { - if (args[i - 1].equalsIgnoreCase("-source")) //$NON-NLS-1$ - sourceLocation = RepositoryHelper.localRepoURIHelper(URIUtil.fromString(arg)); - if (args[i - 1].equalsIgnoreCase("-destination")) //$NON-NLS-1$ - destinationLocation = RepositoryHelper.localRepoURIHelper(URIUtil.fromString(arg)); - if (args[i - 1].equalsIgnoreCase("-compareAgainst")) { //$NON-NLS-1$ - baselineLocation = RepositoryHelper.localRepoURIHelper(URIUtil.fromString(arg)); - compare = true; - } - } catch (URISyntaxException e) { - throw new IllegalArgumentException(NLS.bind(Messages.exception_malformedRepoURI, arg)); - } - } - // Create logs - if (mirrorLogLocation != null) - mirrorLog = getLog(mirrorLogLocation, "p2.artifact.mirror"); //$NON-NLS-1$ - if (comparatorLogLocation != null && comparatorID != null) - comparatorLog = getLog(comparatorLogLocation, comparatorID); - } - - public void setLog(IArtifactMirrorLog log) { - mirrorLog = log; - } - - /* - * Create a MirrorLog based on a filename - */ - private IArtifactMirrorLog getLog(String location, String root) { - if (location.toLowerCase().endsWith(".xml")) //$NON-NLS-1$ - return new XMLMirrorLog(location, verbose ? IStatus.INFO : IStatus.ERROR, root); - return new FileMirrorLog(location, verbose ? IStatus.INFO : IStatus.ERROR, root); - } - - /* - * Log the result of mirroring - */ - private void log(IStatus status) { - if (mirrorLog == null) { - FrameworkLog log = (FrameworkLog) ServiceHelper.getService(Activator.getContext(), FrameworkLog.class.getName()); - if (log != null) - System.err.println("Log file location: " + log.getFile()); //$NON-NLS-1$ - LogHelper.log(status); - } else - mirrorLog.log(status); - } - - /* - * Cleanup - */ - private void cleanup() { - //if the repository was not already loaded before the mirror application started, close it. - if (!sourceLoaded && sourceLocation != null) - getManager().removeRepository(sourceLocation); - if (!destinationLoaded && destinationLocation != null) - getManager().removeRepository(destinationLocation); - if (baselineLocation != null && !baselineLoaded) - getManager().removeRepository(baselineLocation); - - // Close logs - if (mirrorLog != null) - mirrorLog.close(); - if (comparatorLog != null) - comparatorLog.close(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/Mirroring.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/Mirroring.java deleted file mode 100644 index 45573693b..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/Mirroring.java +++ /dev/null @@ -1,273 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Compeople AG (Stefan Liebig) - various ongoing maintenance - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.artifact.mirror; - -import java.util.*; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.osgi.util.NLS; - -/** - * A utility class that performs mirroring of artifacts between repositories. - */ -public class Mirroring { - private IArtifactRepository source; - private IArtifactRepository destination; - private IArtifactRepository baseline; - private boolean raw; - private boolean compare = false; - private boolean validate = false; - private IArtifactComparator comparator; - private String comparatorID; - private IArtifactKey[] keysToMirror; - private IArtifactMirrorLog comparatorLog; - - private IArtifactComparator getComparator() { - if (comparator == null) - comparator = ArtifactComparatorFactory.getArtifactComparator(comparatorID); - return comparator; - } - - public Mirroring(IArtifactRepository source, IArtifactRepository destination, boolean raw) { - this.source = source; - this.destination = destination; - this.raw = raw; - } - - public void setCompare(boolean compare) { - this.compare = compare; - } - - public void setComparatorId(String id) { - this.comparatorID = id; - } - - public void setComparatorLog(IArtifactMirrorLog comparatorLog) { - this.comparatorLog = comparatorLog; - } - - public void setBaseline(IArtifactRepository baseline) { - this.baseline = baseline; - } - - public void setValidate(boolean validate) { - this.validate = validate; - } - - public MultiStatus run(boolean failOnError, boolean verbose) { - if (!destination.isModifiable()) - throw new IllegalStateException(NLS.bind(Messages.exception_destinationNotModifiable, destination.getLocation())); - if (compare) - getComparator(); //initialize the comparator. Only needed if we're comparing. Used to force error if comparatorID is invalid. - IArtifactKey[] keys = keysToMirror == null ? source.getArtifactKeys() : keysToMirror; - MultiStatus multiStatus = new MultiStatus(Activator.ID, IStatus.OK, Messages.message_mirroringStatus, null); - for (int i = 0; i < keys.length; i++) { - IArtifactKey key = keys[i]; - IArtifactDescriptor[] descriptors = source.getArtifactDescriptors(key); - for (int j = 0; j < descriptors.length; j++) { - IStatus result = mirror(descriptors[j], verbose); - //Only log INFO and WARNING if we want verbose logging. Always log ERRORs - if (!result.isOK() && (verbose || result.getSeverity() == IStatus.ERROR)) - multiStatus.add(result); - //stop mirroring as soon as we have an error - if (failOnError && multiStatus.getSeverity() == IStatus.ERROR) - return multiStatus; - } - } - if (validate) { - // Simple validation of the mirror - IStatus validation = validateMirror(verbose); - if (!validation.isOK() && (verbose || validation.getSeverity() == IStatus.ERROR)) - multiStatus.add(validation); - } - return multiStatus; - } - - private IStatus mirror(IArtifactDescriptor descriptor, boolean verbose) { - IArtifactDescriptor newDescriptor = raw ? descriptor : new ArtifactDescriptor(descriptor); - - if (verbose) - System.out.println("Mirroring: " + descriptor.getArtifactKey() + " (Descriptor: " + descriptor + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - - if (compare && baseline != null) - if (baseline.contains(descriptor)) { - // we have to create an output stream based on the descriptor found in the baseline otherwise all - // the properties will be copied over from the wrong descriptor and our repository will be inconsistent. - IArtifactDescriptor baselineDescriptor = getBaselineDescriptor(descriptor); - - // if we found a descriptor in the baseline then we'll use it to copy the artifact - if (baselineDescriptor != null) { - MultiStatus status = new MultiStatus(Activator.ID, IStatus.OK, NLS.bind(Messages.Mirroring_compareAndDownload, descriptor), null); - //Compare source against baseline - IStatus comparison = getComparator().compare(baseline, baselineDescriptor, source, descriptor); - if (comparatorLog != null) - comparatorLog.log(baselineDescriptor, comparison); - status.add(comparison); - if (destination.contains(baselineDescriptor)) - return compareToDestination(baselineDescriptor); - - //download artifact from baseline - status.add(downloadArtifact(baseline, baselineDescriptor, baselineDescriptor)); - return status; - } - } - - // Check if the destination already contains the file. - if (destination.contains(newDescriptor)) { - if (compare) - return compareToDestination(descriptor); - String message = NLS.bind(Messages.mirror_alreadyExists, descriptor, destination); - return new Status(IStatus.INFO, Activator.ID, ProvisionException.ARTIFACT_EXISTS, message, null); - } - - return downloadArtifact(source, newDescriptor, descriptor); - } - - /** - * Takes an IArtifactDescriptor descriptor and the ProvisionException that was thrown when destination.getOutputStream(descriptor) - * and compares descriptor to the duplicate descriptor in the destination. - * - * Callers should verify the ProvisionException was thrown due to the artifact existing in the destination before invoking this method. - * @param descriptor - * @return the status of the compare - */ - private IStatus compareToDestination(IArtifactDescriptor descriptor) { - IArtifactDescriptor[] destDescriptors = destination.getArtifactDescriptors(descriptor.getArtifactKey()); - IArtifactDescriptor destDescriptor = null; - for (int i = 0; destDescriptor == null && i < destDescriptors.length; i++) { - if (destDescriptors[i].equals(descriptor)) - destDescriptor = destDescriptors[i]; - } - if (destDescriptor == null) - return new Status(IStatus.INFO, Activator.ID, ProvisionException.ARTIFACT_EXISTS, Messages.Mirroring_NO_MATCHING_DESCRIPTOR, null); - return compare(source, descriptor, destination, destDescriptor); - } - - private IStatus compare(IArtifactRepository sourceRepository, IArtifactDescriptor sourceDescriptor, IArtifactRepository destRepository, IArtifactDescriptor destDescriptor) { - IStatus comparison = getComparator().compare(sourceRepository, sourceDescriptor, destRepository, destDescriptor); - if (comparatorLog != null) - comparatorLog.log(sourceDescriptor, comparison); - return comparison; - } - - /* - * Create, and execute a MirrorRequest for a given descriptor. - */ - private IStatus downloadArtifact(IArtifactRepository sourceRepo, IArtifactDescriptor destDescriptor, IArtifactDescriptor srcDescriptor) { - RawMirrorRequest request = new RawMirrorRequest(srcDescriptor, destDescriptor, destination); - request.setSourceRepository(sourceRepo); - - request.perform(new NullProgressMonitor()); - - return request.getResult(); - } - - public void setArtifactKeys(IArtifactKey[] keys) { - this.keysToMirror = keys; - } - - /* - * Get the equivalent descriptor from the baseline repository - */ - private IArtifactDescriptor getBaselineDescriptor(IArtifactDescriptor descriptor) { - IArtifactDescriptor[] baselineDescriptors = baseline.getArtifactDescriptors(descriptor.getArtifactKey()); - for (int i = 0; i < baselineDescriptors.length; i++) { - if (baselineDescriptors[i].equals(descriptor)) - return baselineDescriptors[i]; - } - return null; - } - - /* - * Simple validation of a mirror to see if all source descriptors are present in the destination - */ - private IStatus validateMirror(boolean verbose) { - MultiStatus status = new MultiStatus(Activator.ID, 0, Messages.Mirroring_ValidationError, null); - - // The keys that were mirrored in this session - IArtifactKey[] keys = keysToMirror == null ? source.getArtifactKeys() : keysToMirror; - - for (int i = 0; i < keys.length; i++) { - IArtifactDescriptor[] srcDescriptors = source.getArtifactDescriptors(keys[i]); - IArtifactDescriptor[] destDescriptors = destination.getArtifactDescriptors(keys[i]); - - Arrays.sort(srcDescriptors, new ArtifactDescriptorComparator()); - Arrays.sort(destDescriptors, new ArtifactDescriptorComparator()); - - int src = 0; - int dest = 0; - while (src < srcDescriptors.length && dest < destDescriptors.length) { - if (!destDescriptors[dest].equals(srcDescriptors[src])) { - if (destDescriptors[dest].toString().compareTo((srcDescriptors[src].toString())) > 0) { - // Missing an artifact - if (verbose) - System.out.println(NLS.bind(Messages.Mirroring_MISSING_DESCRIPTOR, srcDescriptors[src])); - status.add(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.Mirroring_MISSING_DESCRIPTOR, srcDescriptors[src++]))); - } else { - // Its okay if there are extra descriptors in the destination - dest++; - } - } else { - // check properties for differences - Map destMap = destDescriptors[dest].getProperties(); - Map srcProperties = null; - if (baseline != null) { - IArtifactDescriptor baselineDescriptor = getBaselineDescriptor(destDescriptors[dest]); - if (baselineDescriptor != null) - srcProperties = baselineDescriptor.getProperties(); - } - // Baseline not set, or could not find descriptor so we'll use the source descriptor - if (srcProperties == null) - srcProperties = srcDescriptors[src].getProperties(); - - // Cycle through properties of the originating descriptor & compare - for (Iterator iter = srcProperties.keySet().iterator(); iter.hasNext();) { - String key = (String) iter.next(); - if (!srcProperties.get(key).equals(destMap.get(key))) { - if (verbose) - System.out.println(NLS.bind(Messages.Mirroring_DIFFERENT_DESCRIPTOR_PROPERTY, new Object[] {destDescriptors[dest], key, srcProperties.get(key), destMap.get(key)})); - status.add(new Status(IStatus.WARNING, Activator.ID, NLS.bind(Messages.Mirroring_DIFFERENT_DESCRIPTOR_PROPERTY, new Object[] {destDescriptors[dest], key, srcProperties.get(key), destMap.get(key)}))); - } - } - src++; - dest++; - } - } - - // If there are still source descriptors they're missing from the destination repository - while (src < srcDescriptors.length) { - if (verbose) - System.out.println(NLS.bind(Messages.Mirroring_MISSING_DESCRIPTOR, srcDescriptors[src])); - status.add(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.Mirroring_MISSING_DESCRIPTOR, srcDescriptors[src++]))); - } - } - - return status; - } - - // Simple comparator for ArtifactDescriptors - protected class ArtifactDescriptorComparator implements Comparator { - - public int compare(Object arg0, Object arg1) { - if (arg0 != null && arg1 != null) - return arg0.toString().compareTo(arg1.toString()); - else if (arg1 == null && arg0 == null) - return 0; - else if (arg1 == null) - return 1; - return -1; - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/XMLMirrorLog.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/XMLMirrorLog.java deleted file mode 100644 index 81e56d5da..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/mirror/XMLMirrorLog.java +++ /dev/null @@ -1,166 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.artifact.mirror; - -import java.io.*; -import java.util.Date; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.p2.artifact.repository.Messages; -import org.eclipse.equinox.internal.p2.persistence.XMLWriter; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; - -public class XMLMirrorLog implements IArtifactMirrorLog { - private static final String DEFAULT_FORMAT = "canonical"; //$NON-NLS-1$ - // Constants used in XML tags - private static final String LOG = "log"; //$NON-NLS-1$ - private static final String TIME_ATTRIBUTE = "time"; //$NON-NLS-1$ - private static final String DESCRIPTOR_ELEMENT = "descriptor"; //$NON-NLS-1$ - private static final String DESCRIPTOR_CLASSIFIER_ATTRIBUTE = "classifier"; //$NON-NLS-1$ - private static final String DESCRIPTOR_FORMAT_ATTRIBUTE = "format"; //$NON-NLS-1$ - private static final String DESCRIPTOR_ID_ATTRIBUTE = "id"; //$NON-NLS-1$ - private static final String DESCRIPTOR_VERSION_ATTRIBUTE = "version"; //$NON-NLS-1$ - private static final String STATUS_ELEMENT = "status"; //$NON-NLS-1$ - private static final String STATUS_SEVERITY_ATTRIBUTE = "severity"; //$NON-NLS-1$ - private static final String STATUS_MESSAGE_ATTRIBUTE = "message"; //$NON-NLS-1$ - - private int minStatus = IStatus.OK; - private XMLWriter writer; - private OutputStream outputStream; - private boolean consoleMessage = false; - - public XMLMirrorLog(String location, int minStatus, String root) { - this.minStatus = minStatus; - - try { - outputStream = new FileOutputStream(location); - writer = new XMLWriter(outputStream, null); - if (root != null) - writer.start(root.toLowerCase()); - else - writer.start(LOG); - writer.attribute(TIME_ATTRIBUTE, new Date()); - } catch (UnsupportedEncodingException e) { - exceptionOccurred(e); - } catch (FileNotFoundException e) { - exceptionOccurred(e); - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.artifact.mirror.IArtifactMirrorLog#log(org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor, org.eclipse.core.runtime.IStatus) - */ - public void log(IArtifactDescriptor descriptor, IStatus status) { - if (status.getSeverity() < minStatus) - return; - // Start descriptor tag - if (writer != null) { - writer.start(DESCRIPTOR_ELEMENT); - writer.attribute(DESCRIPTOR_ID_ATTRIBUTE, descriptor.getArtifactKey().getId()); - writer.attribute(DESCRIPTOR_CLASSIFIER_ATTRIBUTE, descriptor.getArtifactKey().getClassifier()); - writer.attribute(DESCRIPTOR_VERSION_ATTRIBUTE, descriptor.getArtifactKey().getVersion()); - if (descriptor.getProperties().get(IArtifactDescriptor.FORMAT) != null) - writer.attribute(DESCRIPTOR_FORMAT_ATTRIBUTE, descriptor.getProperties().get(IArtifactDescriptor.FORMAT)); - else - writer.attribute(DESCRIPTOR_FORMAT_ATTRIBUTE, DEFAULT_FORMAT); - } else - // Creation of the XML writer failed, dump results to the console - System.out.println(descriptor); - - log(status); - - // Close descriptor tag - if (writer != null) - writer.end(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.artifact.mirror.IArtifactMirrorLog#log(org.eclipse.core.runtime.IStatus) - */ - public void log(IStatus status) { - if (status.getSeverity() < minStatus) - return; - - if (writer != null) { - // Start status tag - writer.start(STATUS_ELEMENT); - // Set severity attribute - switch (status.getSeverity()) { - case IStatus.OK : - writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "OK"); //$NON-NLS-1$ - break; - case IStatus.INFO : - writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "INFO"); //$NON-NLS-1$ - break; - case IStatus.WARNING : - writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "WARNING"); //$NON-NLS-1$ - break; - case IStatus.ERROR : - writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "ERROR"); //$NON-NLS-1$ - break; - case IStatus.CANCEL : - writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "CANCEL"); //$NON-NLS-1$ - break; - default : - writer.attribute(STATUS_SEVERITY_ATTRIBUTE, status.getSeverity()); - } - // Set message attribute - writer.attribute(STATUS_MESSAGE_ATTRIBUTE, status.getMessage()); - } else - // Creation of the XML writer failed, dump results to the console - System.out.println(status); - - // Log children statuses - IStatus[] nestedStatus = status.getChildren(); - if (nestedStatus != null) - for (int i = 0; i < nestedStatus.length; i++) - log(nestedStatus[i]); - - // Close status tag - if (writer != null) - writer.end(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.artifact.mirror.IArtifactMirrorLog#close() - */ - public void close() { - try { - if (writer != null) { - // Close opening tag & flush results - writer.end(); - writer.flush(); - } - } finally { - if (outputStream != null) - try { - // Close output stream - outputStream.close(); - } catch (IOException e) { - exceptionOccurred(e); - } - } - } - - /* - * Show an error message if this the first time - */ - private void exceptionOccurred(Exception e) { - if (!consoleMessage) { - System.err.println(Messages.MirrorLog_Exception_Occurred); - e.printStackTrace(System.err); - System.err.println(Messages.MirrorLog_Console_Log); - consoleMessage = true; - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/MD5ArtifactComparator.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/MD5ArtifactComparator.java deleted file mode 100644 index 52c61ad02..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/MD5ArtifactComparator.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.p2.artifact.processors.md5; - -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.artifact.repository.Activator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.osgi.util.NLS; - -public class MD5ArtifactComparator implements IArtifactComparator { - - public static String MD5_COMPARATOR_ID = "org.eclipse.equinox.artifact.md5.comparator"; //$NON-NLS-1$ - - public IStatus compare(IArtifactRepository source, IArtifactDescriptor sourceDescriptor, IArtifactRepository destination, IArtifactDescriptor destDescriptor) { - String sourceMD5 = sourceDescriptor.getProperty(IArtifactDescriptor.DOWNLOAD_MD5); - String destMD5 = destDescriptor.getProperty(IArtifactDescriptor.DOWNLOAD_MD5); - - if (sourceMD5 == null && destMD5 == null) - return new Status(IStatus.INFO, Activator.ID, NLS.bind(Messages.info_noMD5Infomation, sourceDescriptor)); - - if (sourceMD5 == null) - return new Status(IStatus.INFO, Activator.ID, NLS.bind(Messages.info_noMD5InRepository, source, sourceDescriptor)); - - if (destMD5 == null) - return new Status(IStatus.INFO, Activator.ID, NLS.bind(Messages.info_noMD5InRepository, destination, destDescriptor)); - - if (sourceMD5.equals(destMD5)) - return Status.OK_STATUS; - - return new Status(IStatus.WARNING, Activator.ID, NLS.bind(Messages.warning_differentMD5, new Object[] {URIUtil.toUnencodedString(sourceDescriptor.getRepository().getLocation()), URIUtil.toUnencodedString(destDescriptor.getRepository().getLocation()), sourceDescriptor})); - } -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/MD5Verifier.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/MD5Verifier.java index 3e102c43f..d79f88394 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/MD5Verifier.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/MD5Verifier.java @@ -11,15 +11,16 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.processors.md5; +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; + import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.artifact.repository.Activator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; import org.eclipse.osgi.util.NLS; public class MD5Verifier extends ProcessingStep { @@ -38,7 +39,7 @@ public class MD5Verifier extends ProcessingStep { } //This handle the case where the MD5 verification is initiated by a processing step - public void initialize(ProcessingStepDescriptor descriptor, IArtifactDescriptor context) { + public void initialize(IProcessingStepDescriptor descriptor, IArtifactDescriptor context) { super.initialize(descriptor, context); String data = descriptor.getData(); if (IArtifactDescriptor.DOWNLOAD_MD5.equals(data)) @@ -50,7 +51,7 @@ public class MD5Verifier extends ProcessingStep { basicInitialize(descriptor); } - private void basicInitialize(ProcessingStepDescriptor descriptor) { + private void basicInitialize(IProcessingStepDescriptor descriptor) { int code = (descriptor == null) ? IStatus.ERROR : descriptor.isRequired() ? IStatus.ERROR : IStatus.INFO; if (expectedMD5 == null || expectedMD5.length() != 32) setStatus(new Status(code, Activator.ID, NLS.bind(Messages.Error_invalid_hash, expectedMD5))); diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/pack200/Pack200ProcessorStep.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/pack200/Pack200ProcessorStep.java index 7ba8e6387..cf5778e67 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/pack200/Pack200ProcessorStep.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/pack200/Pack200ProcessorStep.java @@ -11,6 +11,8 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.processors.pack200; +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; + import java.io.*; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; @@ -18,8 +20,7 @@ import org.eclipse.equinox.internal.p2.artifact.processing.AbstractBufferingStep import org.eclipse.equinox.internal.p2.artifact.repository.Activator; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; import org.eclipse.equinox.internal.p2.jarprocessor.UnpackStep; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; import org.eclipse.internal.provisional.equinox.p2.jarprocessor.JarProcessorExecutor; import org.eclipse.internal.provisional.equinox.p2.jarprocessor.JarProcessorExecutor.Options; @@ -36,7 +37,7 @@ public class Pack200ProcessorStep extends AbstractBufferingStep { return new BufferedOutputStream(new FileOutputStream(incoming)); } - public void initialize(ProcessingStepDescriptor descriptor, IArtifactDescriptor context) { + public void initialize(IProcessingStepDescriptor descriptor, IArtifactDescriptor context) { super.initialize(descriptor, context); if (!UnpackStep.canUnpack()) setStatus(new Status(IStatus.ERROR, Activator.ID, "Unpack facility not configured")); //$NON-NLS-1$ diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Activator.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Activator.java index ee7fcd4a3..6a41d2d38 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Activator.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Activator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,8 +10,10 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.repository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; +import java.util.HashMap; +import java.util.Map; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; import org.osgi.framework.*; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; @@ -22,22 +24,28 @@ public class Activator implements BundleActivator, ServiceTrackerCustomizer { private static BundleContext context; private ServiceRegistration repositoryManagerRegistration; - private ArtifactRepositoryManager repositoryManager; - private ServiceTracker busTracker; + private static final Map createdManagers = new HashMap(); + private ServiceTracker agentTracker; public static BundleContext getContext() { return Activator.context; } + /** + * Remember an artifact repository manager so we can shut it down when the bundle stops + */ + static void addManager(ArtifactRepositoryManager manager, IProvisioningAgent agent) { + synchronized (createdManagers) { + createdManagers.put(manager, agent); + } + } + public void start(BundleContext aContext) throws Exception { Activator.context = aContext; - repositoryManager = new ArtifactRepositoryManager(); - repositoryManagerRegistration = aContext.registerService(IArtifactRepositoryManager.class.getName(), repositoryManager, null); - - // need to track event bus coming and going to make sure cache gets cleaned on - // repository removals - busTracker = new ServiceTracker(context, IProvisioningEventBus.SERVICE_NAME, this); - busTracker.open(); + // need to track agent so we can register global artifact repository manager + String filter = "(&(objectClass=" + IProvisioningAgent.SERVICE_NAME + ")(agent.current=true))"; //$NON-NLS-1$ //$NON-NLS-2$ + agentTracker = new ServiceTracker(context, aContext.createFilter(filter), this); + agentTracker.open(); } public void stop(BundleContext aContext) throws Exception { @@ -45,28 +53,33 @@ public class Activator implements BundleActivator, ServiceTrackerCustomizer { if (repositoryManagerRegistration != null) repositoryManagerRegistration.unregister(); repositoryManagerRegistration = null; - if (repositoryManager != null) { - repositoryManager.shutdown(); - repositoryManager = null; + synchronized (createdManagers) { + for (ArtifactRepositoryManager manager : createdManagers.keySet()) { + manager.shutdown(); + IProvisioningAgent agent = createdManagers.get(manager); + agent.unregisterService(IArtifactRepositoryManager.SERVICE_NAME, manager); + } + createdManagers.clear(); } - busTracker.close(); + agentTracker.close(); } public Object addingService(ServiceReference reference) { - IProvisioningEventBus bus = (IProvisioningEventBus) context.getService(reference); - if (repositoryManager != null) - repositoryManager.setEventBus(bus); - return bus; + //when someone registers the agent service, register a repository manager service + IProvisioningAgent agent = (IProvisioningAgent) context.getService(reference); + repositoryManagerRegistration = context.registerService(IArtifactRepositoryManager.SERVICE_NAME, agent.getService(IArtifactRepositoryManager.SERVICE_NAME), null); + return agent; } public void modifiedService(ServiceReference reference, Object service) { // ignored - } public void removedService(ServiceReference reference, Object service) { - if (repositoryManager != null) - repositoryManager.unsetEventBus((IProvisioningEventBus) service); + //the agent is going away so withdraw our service + if (repositoryManagerRegistration != null) { + repositoryManagerRegistration.unregister(); + repositoryManagerRegistration = null; + } } - } diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryComponent.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryComponent.java index 39f807b30..901457a8e 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryComponent.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryComponent.java @@ -10,9 +10,11 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.repository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; +import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; +import org.eclipse.equinox.p2.core.IAgentLocation; import org.eclipse.equinox.p2.core.IProvisioningAgent; import org.eclipse.equinox.p2.core.spi.IAgentServiceFactory; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; /** * Service factory providing {@link IArtifactRepositoryManager} instances. @@ -20,7 +22,11 @@ import org.eclipse.equinox.p2.core.spi.IAgentServiceFactory; public class ArtifactRepositoryComponent implements IAgentServiceFactory { public Object createService(IProvisioningAgent agent) { - return new ArtifactRepositoryManager(); + final ArtifactRepositoryManager manager = new ArtifactRepositoryManager(); + manager.setEventBus((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)); + manager.setAgentLocation((IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME)); + manager.setAgent(agent); + Activator.addManager(manager, agent); + return manager; } - } diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryManager.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryManager.java index 46811e78f..21e54aa6f 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryManager.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. + * Copyright (c) 2007, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,17 +12,18 @@ package org.eclipse.equinox.internal.p2.artifact.repository; import java.net.URI; -import java.util.*; +import java.util.HashMap; +import java.util.Map; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.ArtifactRepositoryFactory; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactRepositoryFactory; /** * Default implementation of {@link IArtifactRepositoryManager}. @@ -30,7 +31,7 @@ import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.Artif * TODO the current assumption that the "location" is the dir/root limits us to * having just one repository in a given URL.. */ -public class ArtifactRepositoryManager extends AbstractRepositoryManager implements IArtifactRepositoryManager { +public class ArtifactRepositoryManager extends AbstractRepositoryManager implements IArtifactRepositoryManager { public ArtifactRepositoryManager() { super(); @@ -40,25 +41,31 @@ public class ArtifactRepositoryManager extends AbstractRepositoryManager impleme super.addRepository(repository, true, null); } - public IArtifactRequest createMirrorRequest(IArtifactKey key, IArtifactRepository destination, Properties destinationDescriptorProperties, Properties destinationRepositoryProperties) { + public IArtifactRequest createMirrorRequest(IArtifactKey key, IArtifactRepository destination, Map destinationDescriptorProperties, Map destinationRepositoryProperties) { return new MirrorRequest(key, destination, destinationDescriptorProperties, destinationRepositoryProperties); } - public IArtifactRepository createRepository(URI location, String name, String type, Map properties) throws ProvisionException { + public IArtifactRepository createRepository(URI location, String name, String type, Map properties) throws ProvisionException { return (IArtifactRepository) doCreateRepository(location, name, type, properties); } - protected IRepository factoryCreate(URI location, String name, String type, Map properties, IExtension extension) throws ProvisionException { + public IArtifactRepository getRepository(URI location) { + return (IArtifactRepository) basicGetRepository(location); + } + + protected IRepository factoryCreate(URI location, String name, String type, Map properties, IExtension extension) throws ProvisionException { ArtifactRepositoryFactory factory = (ArtifactRepositoryFactory) createExecutableExtension(extension, EL_FACTORY); if (factory == null) return null; + factory.setAgent(agent); return factory.create(location, name, type, properties); } - protected IRepository factoryLoad(URI location, IExtension extension, int flags, SubMonitor monitor) throws ProvisionException { + protected IRepository factoryLoad(URI location, IExtension extension, int flags, SubMonitor monitor) throws ProvisionException { ArtifactRepositoryFactory factory = (ArtifactRepositoryFactory) createExecutableExtension(extension, EL_FACTORY); if (factory == null) return null; + factory.setAgent(agent); return factory.load(location, flags, monitor.newChild(10)); } @@ -102,12 +109,14 @@ public class ArtifactRepositoryManager extends AbstractRepositoryManager impleme */ protected void restoreSpecialRepositories() { // TODO while recreating, we may want to have proxies on repo instead of the real repo object to limit what is activated. - AgentLocation location = (AgentLocation) ServiceHelper.getService(Activator.getContext(), AgentLocation.class.getName()); + IAgentLocation location = (IAgentLocation) ServiceHelper.getService(Activator.getContext(), IAgentLocation.class.getName()); if (location == null) // TODO should do something here since we are failing to restore. return; + URI cacheLocation = URIUtil.append(location.getDataArea("org.eclipse.equinox.p2.core"), "cache/"); //$NON-NLS-1$ //$NON-NLS-2$ + try { - loadRepository(location.getArtifactRepositoryURI(), null); + loadRepository(cacheLocation, null); return; } catch (ProvisionException e) { // log but still continue and try to create a new one @@ -115,9 +124,9 @@ public class ArtifactRepositoryManager extends AbstractRepositoryManager impleme LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "Error occurred while loading download cache.", e)); //$NON-NLS-1$ } try { - Map properties = new HashMap(1); + Map properties = new HashMap(1); properties.put(IRepository.PROP_SYSTEM, Boolean.TRUE.toString()); - createRepository(location.getArtifactRepositoryURI(), "download cache", TYPE_SIMPLE_REPOSITORY, properties); //$NON-NLS-1$ + createRepository(cacheLocation, "download cache", TYPE_SIMPLE_REPOSITORY, properties); //$NON-NLS-1$ } catch (ProvisionException e) { LogHelper.log(e); } diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRequest.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRequest.java index 352daa6d1..6fe6fc267 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRequest.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRequest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,9 +11,9 @@ package org.eclipse.equinox.internal.p2.artifact.repository; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRequest; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRequest; /** * Base class for all requests on an {@link IArtifactRepository}. diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepository.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepository.java index 411fc37f7..d51ed96c4 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepository.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepository.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. + * Copyright (c) 2008, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ @@ -18,18 +18,19 @@ import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryIO; import org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryState; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.repository.ICompositeRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.AbstractArtifactRepository; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.ICompositeRepository; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.AbstractArtifactRepository; import org.eclipse.osgi.util.NLS; -public class CompositeArtifactRepository extends AbstractArtifactRepository implements IArtifactRepository, ICompositeRepository { +public class CompositeArtifactRepository extends AbstractArtifactRepository implements ICompositeRepository { static final public String REPOSITORY_TYPE = CompositeArtifactRepository.class.getName(); static final private Integer REPOSITORY_VERSION = new Integer(1); @@ -40,16 +41,19 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl // keep a list of the child URIs. they can be absolute or relative. they may or may not point // to a valid reachable repo - private List childrenURIs = new ArrayList(); + private List childrenURIs = new ArrayList(); // keep a list of the repositories that we have successfully loaded - private List loadedRepos = new ArrayList(); + private List loadedRepos = new ArrayList(); + private IArtifactRepositoryManager manager; /** * Create a Composite repository in memory. * @return the repository or null if unable to create one */ - public static CompositeArtifactRepository createMemoryComposite() { - IArtifactRepositoryManager manager = getManager(); + public static CompositeArtifactRepository createMemoryComposite(IProvisioningAgent agent) { + if (agent == null) + return null; + IArtifactRepositoryManager manager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME); if (manager == null) return null; try { @@ -71,21 +75,23 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl return null; } - static private IArtifactRepositoryManager getManager() { - return (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); + private IArtifactRepositoryManager getManager() { + return manager; } /* * This is only called by the parser when loading a repository. */ - public CompositeArtifactRepository(CompositeRepositoryState state) { + CompositeArtifactRepository(IArtifactRepositoryManager manager, CompositeRepositoryState state) { super(state.getName(), state.getType(), state.getVersion(), state.getLocation(), state.getDescription(), state.getProvider(), state.getProperties()); + this.manager = manager; for (int i = 0; i < state.getChildren().length; i++) addChild(state.getChildren()[i], false); } - public CompositeArtifactRepository(URI location, String repositoryName, Map properties) { + CompositeArtifactRepository(IArtifactRepositoryManager manager, URI location, String repositoryName, Map properties) { super(repositoryName, REPOSITORY_TYPE, REPOSITORY_VERSION.toString(), location, null, null, properties); + this.manager = manager; save(); } @@ -103,7 +109,7 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl result.setProvider(getProvider()); result.setProperties(getProperties()); // it is important to directly access the field so we have the relative URIs - result.setChildren((URI[]) childrenURIs.toArray(new URI[childrenURIs.size()])); + result.setChildren(childrenURIs.toArray(new URI[childrenURIs.size()])); return result; } @@ -112,7 +118,7 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl * in it. Return a boolean value indicating whether or not the object was * actually added. */ - private static boolean add(List list, Object obj) { + private static boolean add(List list, T obj) { return list.contains(obj) ? false : list.add(obj); } @@ -163,21 +169,21 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl } } - public boolean addChild(URI childURI, String comparatorID) { - try { - IArtifactRepository repo = load(childURI); - if (isSane(repo, comparatorID)) { - addChild(childURI); - //Add was successful - return true; - } - } catch (ProvisionException e) { - LogHelper.log(e); - } - - //Add was not successful - return false; - } + // public boolean addChild(URI childURI, String comparatorID) { + // try { + // IArtifactRepository repo = load(childURI); + // if (isSane(repo, comparatorID)) { + // addChild(childURI); + // //Add was successful + // return true; + // } + // } catch (ProvisionException e) { + // LogHelper.log(e); + // } + // + // //Add was not successful + // return false; + // } public void removeChild(URI childURI) { boolean removed = childrenURIs.remove(childURI); @@ -190,13 +196,12 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl if (removed) { // we removed the child from the list so remove the associated repo object as well ChildInfo found = null; - for (Iterator iter = loadedRepos.iterator(); found == null && iter.hasNext();) { - ChildInfo current = (ChildInfo) iter.next(); + for (ChildInfo current : loadedRepos) { URI repoLocation = current.repo.getLocation(); - if (URIUtil.sameURI(childURI, repoLocation)) - found = current; - else if (URIUtil.sameURI(other, repoLocation)) + if (URIUtil.sameURI(childURI, repoLocation) || URIUtil.sameURI(other, repoLocation)) { found = current; + break; + } } if (found != null) loadedRepos.remove(found); @@ -210,10 +215,18 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl save(); } - public List getChildren() { - List result = new ArrayList(); - for (Iterator iter = childrenURIs.iterator(); iter.hasNext();) - result.add(URIUtil.makeAbsolute((URI) iter.next(), location)); + public List getChildren() { + List result = new ArrayList(); + for (URI uri : childrenURIs) + result.add(URIUtil.makeAbsolute(uri, location)); + return result; + } + + public List getLoadedChildren() { + List result = new ArrayList(loadedRepos.size()); + for (ChildInfo info : loadedRepos) { + result.add(info.repo); + } return result; } @@ -262,8 +275,7 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl } public boolean contains(IArtifactKey key) { - for (Iterator repositoryIterator = loadedRepos.iterator(); repositoryIterator.hasNext();) { - ChildInfo current = (ChildInfo) repositoryIterator.next(); + for (ChildInfo current : loadedRepos) { if (current.isGood() && current.repo.contains(key)) return true; } @@ -271,8 +283,7 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl } public boolean contains(IArtifactDescriptor descriptor) { - for (Iterator repositoryIterator = loadedRepos.iterator(); repositoryIterator.hasNext();) { - ChildInfo current = (ChildInfo) repositoryIterator.next(); + for (ChildInfo current : loadedRepos) { if (current.isGood() && current.repo.contains(descriptor)) return true; } @@ -280,36 +291,24 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl } public IArtifactDescriptor[] getArtifactDescriptors(IArtifactKey key) { - ArrayList result = new ArrayList(); - for (Iterator repositoryIterator = loadedRepos.iterator(); repositoryIterator.hasNext();) { - ChildInfo current = (ChildInfo) repositoryIterator.next(); + ArrayList result = new ArrayList(); + for (ChildInfo current : loadedRepos) { if (current.isGood()) { IArtifactDescriptor[] tempResult = current.repo.getArtifactDescriptors(key); for (int i = 0; i < tempResult.length; i++) add(result, tempResult[i]); } } - return (IArtifactDescriptor[]) result.toArray(new IArtifactDescriptor[result.size()]); - } - - public IArtifactKey[] getArtifactKeys() { - ArrayList result = new ArrayList(); - for (Iterator repositoryIterator = loadedRepos.iterator(); repositoryIterator.hasNext();) { - ChildInfo current = (ChildInfo) repositoryIterator.next(); - if (current.isGood()) { - IArtifactKey[] tempResult = current.repo.getArtifactKeys(); - for (int i = 0; i < tempResult.length; i++) - add(result, tempResult[i]); - } - } - return (IArtifactKey[]) result.toArray(new IArtifactKey[result.size()]); + return result.toArray(new IArtifactDescriptor[result.size()]); } public IStatus getArtifacts(IArtifactRequest[] requests, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, requests.length); MultiStatus multiStatus = new MultiStatus(Activator.ID, IStatus.OK, Messages.message_childrenRepos, null); - for (Iterator repositoryIterator = loadedRepos.iterator(); repositoryIterator.hasNext() && requests.length > 0;) { - IArtifactRepository current = ((ChildInfo) repositoryIterator.next()).repo; + for (ChildInfo childInfo : loadedRepos) { + if (requests.length == 0) + break; + IArtifactRepository current = childInfo.repo; IArtifactRequest[] applicable = getRequestsForRepository(current, requests); IStatus dlStatus = current.getArtifacts(applicable, subMonitor.newChild(requests.length)); multiStatus.add(dlStatus); @@ -333,8 +332,8 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl } private IStatus getRawOrNormalArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor, boolean raw) { - for (Iterator childIterator = loadedRepos.iterator(); childIterator.hasNext();) { - ChildInfo current = (ChildInfo) childIterator.next(); + for (Iterator childIterator = loadedRepos.iterator(); childIterator.hasNext();) { + ChildInfo current = childIterator.next(); if (current.isGood() && current.repo.contains(descriptor)) { // Child hasn't failed & contains descriptor IStatus status = raw ? current.repo.getRawArtifact(descriptor, destination, monitor) : current.repo.getArtifact(descriptor, destination, monitor); @@ -360,7 +359,7 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl } private IArtifactRequest[] filterUnfetched(IArtifactRequest[] requests) { - ArrayList filteredRequests = new ArrayList(); + ArrayList filteredRequests = new ArrayList(); for (int i = 0; i < requests.length; i++) { if (requests[i].getResult() == null || !requests[i].getResult().isOK()) { filteredRequests.add(requests[i]); @@ -373,18 +372,18 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl } private IArtifactRequest[] getRequestsForRepository(IArtifactRepository repository, IArtifactRequest[] requests) { - ArrayList applicable = new ArrayList(); + ArrayList applicable = new ArrayList(); for (int i = 0; i < requests.length; i++) { if (repository.contains(requests[i].getArtifactKey())) applicable.add(requests[i]); } - return (IArtifactRequest[]) applicable.toArray(new IArtifactRequest[applicable.size()]); + return applicable.toArray(new IArtifactRequest[applicable.size()]); } private void save() { if (!isModifiable()) return; - boolean compress = "true".equalsIgnoreCase((String) properties.get(PROP_COMPRESSED)); //$NON-NLS-1$ + boolean compress = "true".equalsIgnoreCase(properties.get(PROP_COMPRESSED)); //$NON-NLS-1$ OutputStream os = null; try { URI actualLocation = getActualLocation(location, false); @@ -433,73 +432,73 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl return repo; } - /** - * A method to check if the content of a repository is consistent with the other children by - * comparing content using the artifactComparator specified by the comparatorID - * @param toCheckRepo the repository to check - * @param comparatorID - * @return true if toCheckRepo is consistent, false if toCheckRepo - * contains an equal descriptor to that of a child and they refer to different artifacts on disk. - */ - private boolean isSane(IArtifactRepository toCheckRepo, String comparatorID) { - IArtifactComparator comparator = ArtifactComparatorFactory.getArtifactComparator(comparatorID); - for (Iterator repositoryIterator = loadedRepos.iterator(); repositoryIterator.hasNext();) { - IArtifactRepository current = ((ChildInfo) repositoryIterator.next()).repo; - if (!current.equals(toCheckRepo)) { - if (!isSane(toCheckRepo, current, comparator)) - return false; - } - } - return true; - } - - /* - * Check the two given repositories against each other using the given comparator. - */ - private boolean isSane(IArtifactRepository one, IArtifactRepository two, IArtifactComparator comparator) { - IArtifactKey[] toCheckKeys = one.getArtifactKeys(); - for (int i = 0; i < toCheckKeys.length; i++) { - IArtifactKey key = toCheckKeys[i]; - if (!two.contains(key)) - continue; - IArtifactDescriptor[] toCheckDescriptors = one.getArtifactDescriptors(key); - IArtifactDescriptor[] currentDescriptors = two.getArtifactDescriptors(key); - for (int j = 0; j < toCheckDescriptors.length; j++) { - if (!two.contains(toCheckDescriptors[j])) - continue; - for (int k = 0; k < currentDescriptors.length; k++) { - if (currentDescriptors[k].equals(toCheckDescriptors[j])) { - IStatus compareResult = comparator.compare(two, currentDescriptors[k], two, toCheckDescriptors[j]); - if (!compareResult.isOK()) { - LogHelper.log(compareResult); - return false; - } - break; - } - } - } - } - return true; - } - - /** - * A method that verifies that all children with matching artifact descriptors contain the same set of bytes - * The verification is done using the artifactComparator specified by comparatorID - * Assumes more valuable logging and output is the responsibility of the artifactComparator implementation. - * @param comparatorID - * @returns true if the repository is consistent, false if two equal descriptors refer to different artifacts on disk. - */ - public boolean validate(String comparatorID) { - IArtifactComparator comparator = ArtifactComparatorFactory.getArtifactComparator(comparatorID); - ChildInfo[] repos = (ChildInfo[]) loadedRepos.toArray(new ChildInfo[loadedRepos.size()]); - for (int outer = 0; outer < repos.length; outer++) { - for (int inner = outer + 1; inner < repos.length; inner++) { - if (!isSane(repos[outer].repo, repos[inner].repo, comparator)) - return false; - } - } - return true; - } + // /** + // * A method to check if the content of a repository is consistent with the other children by + // * comparing content using the artifactComparator specified by the comparatorID + // * @param toCheckRepo the repository to check + // * @param comparatorID + // * @return true if toCheckRepo is consistent, false if toCheckRepo + // * contains an equal descriptor to that of a child and they refer to different artifacts on disk. + // */ + // private boolean isSane(IArtifactRepository toCheckRepo, String comparatorID) { + // IArtifactComparator comparator = ArtifactComparatorFactory.getArtifactComparator(comparatorID); + // for (ChildInfo childInfo : loadedRepos) { + // IArtifactRepository current = childInfo.repo; + // if (!current.equals(toCheckRepo)) { + // if (!isSane(toCheckRepo, current, comparator)) + // return false; + // } + // } + // return true; + // } + // + // /* + // * Check the two given repositories against each other using the given comparator. + // */ + // private boolean isSane(IArtifactRepository one, IArtifactRepository two, IArtifactComparator comparator) { + // IQueryResult toCheckKeys = one.query(ArtifactKeyQuery.ALL_KEYS, null); + // for (Iterator iterator = toCheckKeys.iterator(); iterator.hasNext();) { + // IArtifactKey key = iterator.next(); + // if (!two.contains(key)) + // continue; + // IArtifactDescriptor[] toCheckDescriptors = one.getArtifactDescriptors(key); + // IArtifactDescriptor[] currentDescriptors = two.getArtifactDescriptors(key); + // for (int j = 0; j < toCheckDescriptors.length; j++) { + // if (!two.contains(toCheckDescriptors[j])) + // continue; + // for (int k = 0; k < currentDescriptors.length; k++) { + // if (currentDescriptors[k].equals(toCheckDescriptors[j])) { + // IStatus compareResult = comparator.compare(two, currentDescriptors[k], two, toCheckDescriptors[j]); + // if (!compareResult.isOK()) { + // LogHelper.log(compareResult); + // return false; + // } + // break; + // } + // } + // } + // } + // return true; + // } + // + // /** + // * A method that verifies that all children with matching artifact descriptors contain the same set of bytes + // * The verification is done using the artifactComparator specified by comparatorID + // * Assumes more valuable logging and output is the responsibility of the artifactComparator implementation. + // * @param comparatorID + // * @returns true if the repository is consistent, false if two equal descriptors refer to different artifacts on disk. + // */ + // private boolean validate(String comparatorID) { + // IArtifactComparator comparator = ArtifactComparatorFactory.getArtifactComparator(comparatorID); + // ChildInfo[] repos = loadedRepos.toArray(new ChildInfo[loadedRepos.size()]); + // for (int outer = 0; outer < repos.length; outer++) { + // for (int inner = outer + 1; inner < repos.length; inner++) { + // if (!isSane(repos[outer].repo, repos[inner].repo, comparator)) + // return false; + // } + // } + // return true; + // } private static class ChildInfo { IArtifactRepository repo; @@ -517,4 +516,26 @@ public class CompositeArtifactRepository extends AbstractArtifactRepository impl return good; } } + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + // Query all the all the repositories this composite repo contains + List repos = new ArrayList(); + for (ChildInfo info : loadedRepos) { + if (info.isGood()) + repos.add(info.repo); + } + CompoundQueryable queryable = new CompoundQueryable(repos); + return queryable.query(query, monitor); + } + + public IQueryable descriptorQueryable() { + // Query all the all the repositories this composite repo contains + List> repos = new ArrayList>(); + for (ChildInfo info : loadedRepos) { + if (info.isGood()) + repos.add(info.repo.descriptorQueryable()); + } + CompoundQueryable queryable = new CompoundQueryable(repos); + return queryable; + } } diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepositoryFactory.java index e587abfca..a37216807 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepositoryFactory.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepositoryFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. + * Copyright (c) 2008, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,6 +10,10 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.repository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactRepositoryFactory; + +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.*; import java.net.URI; import java.util.Map; @@ -21,14 +25,19 @@ import org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryIO; import org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryState; import org.eclipse.equinox.internal.p2.repository.RepositoryTransport; import org.eclipse.equinox.internal.p2.repository.Transport; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.ArtifactRepositoryFactory; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; import org.eclipse.osgi.util.NLS; public class CompositeArtifactRepositoryFactory extends ArtifactRepositoryFactory { + private IArtifactRepositoryManager getManager() { + if (getAgent() != null) + return (IArtifactRepositoryManager) getAgent().getService(IArtifactRepositoryManager.SERVICE_NAME); + return null; + } + public IArtifactRepository load(URI location, int flags, IProgressMonitor monitor) throws ProvisionException { final String PROTOCOL_FILE = "file"; //$NON-NLS-1$ long time = 0; @@ -95,7 +104,7 @@ public class CompositeArtifactRepositoryFactory extends ArtifactRepositoryFactor CompositeRepositoryState resultState = io.read(localFile.toURL(), descriptorStream, CompositeArtifactRepository.PI_REPOSITORY_TYPE, sub.newChild(100)); if (resultState.getLocation() == null) resultState.setLocation(location); - CompositeArtifactRepository result = new CompositeArtifactRepository(resultState); + CompositeArtifactRepository result = new CompositeArtifactRepository(getManager(), resultState); if (Tracing.DEBUG_METADATA_PARSING) { time += System.currentTimeMillis(); Tracing.debug(debugMsg + "time (ms): " + time); //$NON-NLS-1$ @@ -117,8 +126,8 @@ public class CompositeArtifactRepositoryFactory extends ArtifactRepositoryFactor } } - public IArtifactRepository create(URI location, String name, String type, Map properties) { - return new CompositeArtifactRepository(location, name, properties); + public IArtifactRepository create(URI location, String name, String type, Map properties) { + return new CompositeArtifactRepository(getManager(), location, name, properties); } private Transport getTransport() { diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/FlatteningIterator.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/FlatteningIterator.java new file mode 100644 index 000000000..1035f1420 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/FlatteningIterator.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (c) 2009, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.artifact.repository; + +import java.util.*; + +/** + * An iterator over values that are provided by iterating over collections. + */ +public class FlatteningIterator implements Iterator { + private static final Object NO_ELEMENT = new Object(); + private final Iterator> collectionIterator; + private Iterator currentIterator; + + private T nextObject = noElement(); + + public FlatteningIterator(Iterator> collectionIterator) { + this.collectionIterator = collectionIterator; + } + + public boolean hasNext() { + return positionNext(); + } + + public T next() { + if (!positionNext()) + throw new NoSuchElementException(); + + T nxt = nextObject; + nextObject = noElement(); + return nxt; + } + + public void remove() { + throw new UnsupportedOperationException(); + } + + private boolean positionNext() { + if (nextObject != NO_ELEMENT) + return true; + + while (currentIterator == null || !currentIterator.hasNext()) { + if (!collectionIterator.hasNext()) + return false; + currentIterator = collectionIterator.next().iterator(); + } + nextObject = currentIterator.next(); + return true; + } + + @SuppressWarnings("unchecked") + private static T noElement() { + return (T) NO_ELEMENT; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Messages.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Messages.java index c15f22c0d..1353e18b5 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Messages.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Messages.java @@ -17,6 +17,7 @@ public class Messages extends NLS { public static String artifact_not_found; public static String available_already_in; + public static String no_location; public static String downloading; public static String error_closing_stream; public static String io_failedRead; diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorRequest.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorRequest.java index 5623b78e5..6e2585445 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorRequest.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorRequest.java @@ -1,54 +1,56 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: + * Copyright (c) 2007, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: * IBM Corporation - initial API and implementation * Compeople AG (Stefan Liebig) - various ongoing maintenance * Genuitec LLC - various bug fixes *******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.repository; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.*; -import java.util.Properties; +import java.util.HashMap; +import java.util.Map; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; +import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactDescriptor; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepHandler; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; import org.eclipse.equinox.internal.provisional.p2.repository.IStateful; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.osgi.util.NLS; /** * A request to mirror (copy) an artifact into a given destination artifact repository. */ public class MirrorRequest extends ArtifactRequest { - private static final ProcessingStepDescriptor[] EMPTY_STEPS = new ProcessingStepDescriptor[0]; - protected final IArtifactRepository target; - private final Properties targetDescriptorProperties; - private final Properties targetRepositoryProperties; + private final Map targetDescriptorProperties; + private final Map targetRepositoryProperties; protected IArtifactDescriptor descriptor; - public MirrorRequest(IArtifactKey key, IArtifactRepository targetRepository, Properties targetDescriptorProperties, Properties targetRepositoryProperties) { + public MirrorRequest(IArtifactKey key, IArtifactRepository targetRepository, Map targetDescriptorProperties, Map targetRepositoryProperties) { super(key); target = targetRepository; if (targetDescriptorProperties == null || targetDescriptorProperties.isEmpty()) { this.targetDescriptorProperties = null; } else { - this.targetDescriptorProperties = new Properties(); + this.targetDescriptorProperties = new HashMap(); this.targetDescriptorProperties.putAll(targetDescriptorProperties); } if (targetRepositoryProperties == null || targetRepositoryProperties.isEmpty()) { this.targetRepositoryProperties = null; } else { - this.targetRepositoryProperties = new Properties(); + this.targetRepositoryProperties = new HashMap(); this.targetRepositoryProperties.putAll(targetRepositoryProperties); } } @@ -91,7 +93,7 @@ public class MirrorRequest extends ArtifactRequest { return; } - ArtifactDescriptor destinationDescriptor = getDestinationDescriptor(descriptor); + IArtifactDescriptor destinationDescriptor = getDestinationDescriptor(descriptor); IStatus status = transfer(destinationDescriptor, descriptor, monitor); // if ok, cancelled or transfer has already been done with the canonical form return with status set if (status.getSeverity() == IStatus.CANCEL) { @@ -125,21 +127,21 @@ public class MirrorRequest extends ArtifactRequest { setResult(new MultiStatus(Activator.ID, canonicalStatus.getCode() != 0 ? canonicalStatus.getCode() : status.getCode(), new IStatus[] {status, canonicalStatus}, Messages.MirrorRequest_multipleDownloadProblems, null)); } - private ArtifactDescriptor getDestinationDescriptor(IArtifactDescriptor sourceDescriptor) { + private IArtifactDescriptor getDestinationDescriptor(IArtifactDescriptor sourceDescriptor) { // Get the descriptor to use to store the artifact // Since we are mirroring, ensure we clear out data from the original descriptor that may // not apply in the new repo location. // TODO this is brittle. perhaps the repo itself should do this? there are cases where // we really do need to give the repo the actual descriptor to use however... - ArtifactDescriptor destinationDescriptor = new ArtifactDescriptor(sourceDescriptor); - destinationDescriptor.setProcessingSteps(EMPTY_STEPS); - destinationDescriptor.setProperty(IArtifactDescriptor.DOWNLOAD_MD5, null); - destinationDescriptor.setProperty(IArtifactDescriptor.DOWNLOAD_CONTENTTYPE, null); - destinationDescriptor.setProperty(IArtifactDescriptor.FORMAT, null); - if (targetDescriptorProperties != null) - destinationDescriptor.addProperties(targetDescriptorProperties); - if (targetRepositoryProperties != null) - destinationDescriptor.addRepositoryProperties(targetRepositoryProperties); + IArtifactDescriptor destinationDescriptor = target.createArtifactDescriptor(sourceDescriptor.getArtifactKey()); + // destinationDescriptor.setProcessingSteps(EMPTY_STEPS); + // destinationDescriptor.setProperty(IArtifactDescriptor.DOWNLOAD_MD5, null); + // destinationDescriptor.setProperty(IArtifactDescriptor.DOWNLOAD_CONTENTTYPE, null); + // destinationDescriptor.setProperty(IArtifactDescriptor.FORMAT, null); + if (targetDescriptorProperties != null && destinationDescriptor instanceof ArtifactDescriptor) + ((ArtifactDescriptor) destinationDescriptor).addProperties(targetDescriptorProperties); + if (targetRepositoryProperties != null && destinationDescriptor instanceof SimpleArtifactDescriptor) + ((SimpleArtifactDescriptor) destinationDescriptor).addRepositoryProperties(targetRepositoryProperties); return destinationDescriptor; } diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorSelector.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorSelector.java index 8104d23e8..6fb6259de 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorSelector.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorSelector.java @@ -21,7 +21,7 @@ import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.core.helpers.Tracing; import org.eclipse.equinox.internal.p2.repository.DownloadStatus; import org.eclipse.equinox.internal.p2.repository.RepositoryTransport; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepository; import org.w3c.dom.*; import org.xml.sax.InputSource; @@ -39,7 +39,7 @@ public class MirrorSelector { /** * Encapsulates information about a single mirror */ - public static class MirrorInfo implements Comparable { + public static class MirrorInfo implements Comparable { long bytesPerSecond; int failureCount; private final int initialRank; @@ -57,10 +57,7 @@ public class MirrorSelector { /** * Comparison used to sort mirrors. */ - public int compareTo(Object o) { - if (!(o instanceof MirrorInfo)) - return 0; - MirrorInfo that = (MirrorInfo) o; + public int compareTo(MirrorInfo that) { //less failures is better if (this.failureCount != that.failureCount) return this.failureCount - that.failureCount; @@ -91,7 +88,7 @@ public class MirrorSelector { MirrorInfo[] mirrors; - private final IRepository repository; + private final IRepository repository; private final Random random = new Random(); @@ -100,10 +97,10 @@ public class MirrorSelector { * not contacted and the mirrorsURL document is not parsed until a * mirror location request is sent. */ - public MirrorSelector(IRepository repository) { + public MirrorSelector(IRepository repository) { this.repository = repository; try { - String base = (String) repository.getProperties().get(IRepository.PROP_MIRRORS_BASE_URL); + String base = repository.getProperties().get(IRepository.PROP_MIRRORS_BASE_URL); if (base != null) { this.baseURI = new URI(base); } else { @@ -204,7 +201,7 @@ public class MirrorSelector { private MirrorInfo[] initMirrors(IProgressMonitor monitor) { if (mirrors != null) return mirrors; - String mirrorsURL = (String) repository.getProperties().get(IRepository.PROP_MIRRORS_URL); + String mirrorsURL = repository.getProperties().get(IRepository.PROP_MIRRORS_URL); if (mirrorsURL != null) mirrors = computeMirrors(mirrorsURL, monitor); return mirrors; diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/RawMirrorRequest.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/RawMirrorRequest.java index 3c82b5565..3c2432543 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/RawMirrorRequest.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/RawMirrorRequest.java @@ -14,10 +14,10 @@ import java.io.OutputStream; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.artifact.processors.md5.MD5Verifier; import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepHandler; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; import org.eclipse.osgi.util.NLS; public class RawMirrorRequest extends MirrorRequest { diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/SignatureVerifier.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/SignatureVerifier.java index 55330678a..2108b52f4 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/SignatureVerifier.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/SignatureVerifier.java @@ -78,7 +78,7 @@ public class SignatureVerifier extends ProcessingStep { } catch (GeneralSecurityException e) { return new Status(IStatus.ERROR, Activator.ID, Messages.SignatureVerification_failedRead + inputFile, e); } - ArrayList allStatus = new ArrayList(0); + ArrayList allStatus = new ArrayList(0); SignedContentEntry[] entries = signedContent.getSignedEntries(); for (int i = 0; i < entries.length; i++) try { @@ -90,7 +90,7 @@ public class SignatureVerifier extends ProcessingStep { break; } if (allStatus.size() > 0) - return new MultiStatus(Activator.ID, IStatus.ERROR, (IStatus[]) allStatus.toArray(new IStatus[allStatus.size()]), Messages.SignatureVerification_invalidFileContent + inputFile, null); + return new MultiStatus(Activator.ID, IStatus.ERROR, allStatus.toArray(new IStatus[allStatus.size()]), Messages.SignatureVerification_invalidFileContent + inputFile, null); return Status.OK_STATUS; } diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/messages.properties b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/messages.properties index 9b80fc9ef..eed154d94 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/messages.properties +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/messages.properties @@ -10,6 +10,7 @@ ############################################################################### artifact_not_found=Artifact not found: {0}. available_already_in=The artifact is already available in the repository {0}. +no_location=No location for {0}. downloading=Downloading {0} error_closing_stream=Error closing the output stream for {0} on repository {1}. diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/BlobStore.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/BlobStore.java index e3697cbee..bf6fed250 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/BlobStore.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/BlobStore.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,7 +12,6 @@ package org.eclipse.equinox.internal.p2.artifact.repository.simple; import java.io.*; import java.net.URI; -import java.util.Iterator; import java.util.Set; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.URIUtil; @@ -93,9 +92,9 @@ public class BlobStore { /** * Delete all of the blobs in the given set. */ - public void deleteBlobs(Set set) { - for (Iterator i = set.iterator(); i.hasNext();) - deleteBlob((byte[]) i.next()); + public void deleteBlobs(Set set) { + for (byte[] blob : set) + deleteBlob(blob); } public URI fileFor(byte[] uuid) { diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/DownloadJob.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/DownloadJob.java index 0001a2804..69aee86ef 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/DownloadJob.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/DownloadJob.java @@ -13,12 +13,12 @@ import java.util.LinkedList; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.equinox.internal.p2.artifact.repository.ArtifactRequest; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRequest; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRequest; public class DownloadJob extends Job { static final Object FAMILY = new Object(); - private LinkedList requestsPending; + private LinkedList requestsPending; private SimpleArtifactRepository repository; private IProgressMonitor masterMonitor; private MultiStatus overallStatus; @@ -28,7 +28,7 @@ public class DownloadJob extends Job { setSystem(true); } - void initialize(SimpleArtifactRepository repository, LinkedList requestsPending, IProgressMonitor masterMonitor, MultiStatus overallStatus) { + void initialize(SimpleArtifactRepository repository, LinkedList requestsPending, IProgressMonitor masterMonitor, MultiStatus overallStatus) { this.repository = repository; this.requestsPending = requestsPending; this.masterMonitor = masterMonitor; @@ -53,7 +53,7 @@ public class DownloadJob extends Job { synchronized (requestsPending) { if (requestsPending.isEmpty()) break; - request = (IArtifactRequest) requestsPending.removeFirst(); + request = requestsPending.removeFirst(); } if (masterMonitor.isCanceled()) return Status.CANCEL_STATUS; diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/Mapper.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/Mapper.java index de962a7c7..80b6b3e44 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/Mapper.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/Mapper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -53,7 +53,7 @@ public class Mapper { public URI map(URI repositoryLocation, String classifier, String id, String version, String format) { String locationString = URIUtil.toUnencodedString(repositoryLocation); - Dictionary values = new Hashtable(5); + Dictionary values = new Hashtable(5); if (repositoryLocation != null) values.put(REPOURL, locationString); diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactDescriptor.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactDescriptor.java new file mode 100644 index 000000000..e458813ee --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactDescriptor.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.artifact.repository.simple; + +import java.util.Map; +import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; + +public class SimpleArtifactDescriptor extends ArtifactDescriptor { + public static final String ARTIFACT_REFERENCE = "artifact.reference"; //$NON-NLS-1$ + + protected Map repositoryProperties = new OrderedProperties(); + + public SimpleArtifactDescriptor(IArtifactKey key) { + super(key); + } + + public SimpleArtifactDescriptor(IArtifactDescriptor base) { + super(base); + } + + public SimpleArtifactDescriptor(SimpleArtifactDescriptor base) { + super(base); + } + + public String getRepositoryProperty(String propertyKey) { + return repositoryProperties.get(propertyKey); + } + + public void setRepositoryProperty(String key, String value) { + if (value == null) + repositoryProperties.remove(key); + else + repositoryProperties.put(key, value); + } + + public void addRepositoryProperties(Map additionalProperties) { + repositoryProperties.putAll(additionalProperties); + } + + /** + * Returns a read-only collection of the repository properties of the artifact descriptor. + * @return the repository properties of this artifact descriptor. + */ + public Map getRepositoryProperties() { + return OrderedProperties.unmodifiableProperties(repositoryProperties); + } + + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null || !(obj instanceof SimpleArtifactDescriptor)) + return false; + + SimpleArtifactDescriptor other = (SimpleArtifactDescriptor) obj; + + //Properties affecting SimpleArtifactRepository#getLocation + String locationProperty = getRepositoryProperty(ARTIFACT_REFERENCE); + String otherProperty = other.getRepositoryProperty(ARTIFACT_REFERENCE); + // want not null and the same, or both null + if (locationProperty != null ? !locationProperty.equals(otherProperty) : otherProperty != null) + return false; + + return super.equals(obj); + } + + public int hashCode() { + int superHash = super.hashCode(); + String ref = getRepositoryProperty(ARTIFACT_REFERENCE); + if (ref != null) + return 31 * superHash + ref.hashCode(); + return superHash; + } +} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepository.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepository.java index fc225be63..127c7851b 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepository.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepository.java @@ -1,11 +1,11 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: + * Copyright (c) 2007, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: * IBM Corporation - initial API and implementation * Genuitec, LLC - support for multi-threaded downloads *******************************************************************************/ @@ -15,6 +15,7 @@ import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.util.*; +import java.util.Map.Entry; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import org.eclipse.core.runtime.*; @@ -26,13 +27,15 @@ import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.repository.RepositoryTransport; import org.eclipse.equinox.internal.p2.repository.Transport; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; import org.eclipse.equinox.internal.provisional.p2.repository.IStateful; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.AbstractArtifactRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.AbstractArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.osgi.util.NLS; public class SimpleArtifactRepository extends AbstractArtifactRepository implements IArtifactRepository, IFileArtifactRepository { @@ -197,12 +200,14 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme static final private Integer REPOSITORY_VERSION = new Integer(1); private static final String XML_EXTENSION = ".xml"; //$NON-NLS-1$ - protected Set artifactDescriptors = new HashSet(); - protected Map artifactMap = new HashMap(); + protected Set artifactDescriptors = new HashSet(); + /** + * Map> containing the index of artifacts in the repository. + */ + protected Map> artifactMap = new HashMap>(); private transient BlobStore blobStore; transient private Mapper mapper = new Mapper(); - static final private String PACKED_FORMAT = "packed"; //$NON-NLS-1$ static final private String PUBLISH_PACK_FILES_AS_SIBLINGS = "publishPackFilesAsSiblings"; //$NON-NLS-1$ private static final int DEFAULT_MAX_THREADS = 4; @@ -250,19 +255,19 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme /* * This is only called by the parser when loading a repository. */ - SimpleArtifactRepository(String name, String type, String version, String description, String provider, Set artifacts, String[][] mappingRules, Map properties) { + SimpleArtifactRepository(String name, String type, String version, String description, String provider, Set artifacts, String[][] mappingRules, Map properties) { super(name, type, version, null, description, provider, properties); this.artifactDescriptors.addAll(artifacts); this.mappingRules = mappingRules; - for (Iterator it = artifactDescriptors.iterator(); it.hasNext();) - mapDescriptor((IArtifactDescriptor) it.next()); + for (SimpleArtifactDescriptor desc : artifactDescriptors) + mapDescriptor(desc); } private void mapDescriptor(IArtifactDescriptor descriptor) { IArtifactKey key = descriptor.getArtifactKey(); - Collection descriptors = (Collection) artifactMap.get(key); + List descriptors = artifactMap.get(key); if (descriptors == null) { - descriptors = new ArrayList(); + descriptors = new ArrayList(); artifactMap.put(key, descriptors); } descriptors.add(descriptor); @@ -270,7 +275,7 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme private void unmapDescriptor(IArtifactDescriptor descriptor) { IArtifactKey key = descriptor.getArtifactKey(); - Collection descriptors = (Collection) artifactMap.get(key); + List descriptors = artifactMap.get(key); if (descriptors == null) return; @@ -279,13 +284,13 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme artifactMap.remove(key); } - public SimpleArtifactRepository(String repositoryName, URI location, Map properties) { + public SimpleArtifactRepository(String repositoryName, URI location, Map properties) { super(repositoryName, REPOSITORY_TYPE, REPOSITORY_VERSION.toString(), location, null, null, properties); initializeAfterLoad(location); if (properties != null) { if (properties.containsKey(PUBLISH_PACK_FILES_AS_SIBLINGS)) { synchronized (this) { - String newValue = (String) properties.get(PUBLISH_PACK_FILES_AS_SIBLINGS); + String newValue = properties.get(PUBLISH_PACK_FILES_AS_SIBLINGS); if (Boolean.TRUE.toString().equals(newValue)) { mappingRules = PACKED_MAPPING_RULES; } else { @@ -299,37 +304,57 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme } public synchronized void addDescriptor(IArtifactDescriptor toAdd) { - // TODO perhaps the argument here should be ArtifactDescriptor. IArtifactDescriptors are for - // people who are reading the repository. - // TODO: here we may want to ensure that the artifact has not been added concurrently - ((ArtifactDescriptor) toAdd).setRepository(this); - artifactDescriptors.add(toAdd); - mapDescriptor(toAdd); + if (artifactDescriptors.contains(toAdd)) + return; + + SimpleArtifactDescriptor internalDescriptor = createInternalDescriptor(toAdd); + artifactDescriptors.add(internalDescriptor); + mapDescriptor(internalDescriptor); save(); } - public synchronized void addDescriptors(IArtifactDescriptor[] descriptors) { + public IArtifactDescriptor createArtifactDescriptor(IArtifactKey key) { + return new SimpleArtifactDescriptor(key); + } + + private SimpleArtifactDescriptor createInternalDescriptor(IArtifactDescriptor descriptor) { + SimpleArtifactDescriptor internal = new SimpleArtifactDescriptor(descriptor); + + internal.setRepository(this); + if (isFolderBased(descriptor)) + internal.setRepositoryProperty(ARTIFACT_FOLDER, Boolean.TRUE.toString()); + if (descriptor instanceof SimpleArtifactDescriptor) { + Map repoProperties = ((SimpleArtifactDescriptor) descriptor).getRepositoryProperties(); + for (Entry entry : repoProperties.entrySet()) { + internal.setRepositoryProperty(entry.getKey(), entry.getValue()); + } + } + return internal; + } + public synchronized void addDescriptors(IArtifactDescriptor[] descriptors) { for (int i = 0; i < descriptors.length; i++) { - ((ArtifactDescriptor) descriptors[i]).setRepository(this); - artifactDescriptors.add(descriptors[i]); - mapDescriptor(descriptors[i]); + if (artifactDescriptors.contains(descriptors[i])) + continue; + SimpleArtifactDescriptor internalDescriptor = createInternalDescriptor(descriptors[i]); + artifactDescriptors.add(internalDescriptor); + mapDescriptor(internalDescriptor); } save(); } private synchronized OutputStream addPostSteps(ProcessingStepHandler handler, IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) { - ArrayList steps = new ArrayList(); + ArrayList steps = new ArrayList(); steps.add(new SignatureVerifier()); if (steps.isEmpty()) return destination; - ProcessingStep[] stepArray = (ProcessingStep[]) steps.toArray(new ProcessingStep[steps.size()]); + ProcessingStep[] stepArray = steps.toArray(new ProcessingStep[steps.size()]); // TODO should probably be using createAndLink here return handler.link(stepArray, destination, monitor); } private OutputStream addPreSteps(ProcessingStepHandler handler, IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) { - ArrayList steps = new ArrayList(); + ArrayList steps = new ArrayList(); if (IArtifactDescriptor.TYPE_ZIP.equals(descriptor.getProperty(IArtifactDescriptor.DOWNLOAD_CONTENTTYPE))) steps.add(new ZipVerifierStep()); if (MD5_CHECK_ENABLED && descriptor.getProperty(IArtifactDescriptor.DOWNLOAD_MD5) != null) @@ -337,7 +362,7 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme // Add steps here if needed if (steps.isEmpty()) return destination; - ProcessingStep[] stepArray = (ProcessingStep[]) steps.toArray(new ProcessingStep[steps.size()]); + ProcessingStep[] stepArray = steps.toArray(new ProcessingStep[steps.size()]); // TODO should probably be using createAndLink here return handler.link(stepArray, destination, monitor); } @@ -367,7 +392,8 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme } public synchronized boolean contains(IArtifactDescriptor descriptor) { - return artifactDescriptors.contains(descriptor); + SimpleArtifactDescriptor simpleDescriptor = createInternalDescriptor(descriptor); + return artifactDescriptors.contains(simpleDescriptor); } public synchronized boolean contains(IArtifactKey key) { @@ -404,7 +430,12 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme * descriptor existed in the repository, and was successfully removed. */ private boolean doRemoveArtifact(IArtifactDescriptor descriptor) { - if (((ArtifactDescriptor) descriptor).getRepositoryProperty(ArtifactDescriptor.ARTIFACT_REFERENCE) == null) { + SimpleArtifactDescriptor simple = null; + if (descriptor instanceof SimpleArtifactDescriptor) + simple = (SimpleArtifactDescriptor) descriptor; + else + simple = createInternalDescriptor(descriptor); + if (simple.getRepositoryProperty(SimpleArtifactDescriptor.ARTIFACT_REFERENCE) == null) { File file = getArtifactFile(descriptor); if (file == null) return false; @@ -446,7 +477,7 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme //download from the best available mirror URI baseLocation = getLocation(descriptor); if (baseLocation == null) - return new Status(IStatus.ERROR, Activator.ID, "Can not find the location of " + descriptor); + return new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.no_location, descriptor)); URI mirrorLocation = getMirror(baseLocation, monitor); IStatus status = downloadArtifact(descriptor, mirrorLocation, destination, monitor); IStatus result = reportStatus(descriptor, destination, status); @@ -494,6 +525,7 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme return mirrors.getMirrorLocation(baseLocation, monitor); } + @SuppressWarnings("rawtypes") public Object getAdapter(Class adapter) { // if we are adapting to file or writable repositories then make sure we have a file location if (adapter == IFileArtifactRepository.class) @@ -523,11 +555,11 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme } public synchronized IArtifactDescriptor[] getArtifactDescriptors(IArtifactKey key) { - Collection result = (Collection) artifactMap.get(key); + List result = artifactMap.get(key); if (result == null) return new IArtifactDescriptor[0]; - return (IArtifactDescriptor[]) result.toArray(new IArtifactDescriptor[result.size()]); + return result.toArray(new IArtifactDescriptor[result.size()]); } public File getArtifactFile(IArtifactDescriptor descriptor) { @@ -544,14 +576,9 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme return getArtifactFile(descriptor); } - public synchronized IArtifactKey[] getArtifactKeys() { - // there may be more descriptors than keys to collect up the unique keys - return (IArtifactKey[]) artifactMap.keySet().toArray(new IArtifactKey[artifactMap.keySet().size()]); - } - public IStatus getArtifacts(IArtifactRequest[] requests, IProgressMonitor monitor) { final MultiStatus overallStatus = new MultiStatus(Activator.ID, IStatus.OK, null, null); - LinkedList requestsPending = new LinkedList(Arrays.asList(requests)); + LinkedList requestsPending = new LinkedList(Arrays.asList(requests)); int numberOfJobs = Math.min(requests.length, getMaximumThreads()); if (numberOfJobs <= 1 || (!isForceThreading() && isLocal())) { @@ -591,12 +618,11 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme } public synchronized IArtifactDescriptor getCompleteArtifactDescriptor(IArtifactKey key) { - Collection descriptors = (Collection) artifactMap.get(key); + List descriptors = artifactMap.get(key); if (descriptors == null) return null; - for (Iterator iterator = descriptors.iterator(); iterator.hasNext();) { - IArtifactDescriptor desc = (IArtifactDescriptor) iterator.next(); + for (IArtifactDescriptor desc : descriptors) { // look for a descriptor that matches the key and is "complete" if (desc.getArtifactKey().equals(key) && desc.getProcessingSteps().length == 0) return desc; @@ -604,7 +630,7 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme return null; } - public synchronized Set getDescriptors() { + public synchronized Set getDescriptors() { return artifactDescriptors; } @@ -615,7 +641,7 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme * this arrangement "flat but packed". */ private boolean flatButPackedEnabled(IArtifactDescriptor descriptor) { - return Boolean.TRUE.toString().equals(getProperties().get(PUBLISH_PACK_FILES_AS_SIBLINGS)) && PACKED_FORMAT.equals(descriptor.getProperty(IArtifactDescriptor.FORMAT)); + return Boolean.TRUE.toString().equals(getProperties().get(PUBLISH_PACK_FILES_AS_SIBLINGS)) && IArtifactDescriptor.FORMAT_PACKED.equals(descriptor.getProperty(IArtifactDescriptor.FORMAT)); } /** @@ -638,8 +664,8 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme try { // if the artifact is just a reference then return the reference location - if (descriptor instanceof ArtifactDescriptor) { - String artifactReference = ((ArtifactDescriptor) descriptor).getRepositoryProperty(ArtifactDescriptor.ARTIFACT_REFERENCE); + if (descriptor instanceof SimpleArtifactDescriptor) { + String artifactReference = ((SimpleArtifactDescriptor) descriptor).getRepositoryProperty(SimpleArtifactDescriptor.ARTIFACT_REFERENCE); if (artifactReference != null) { try { return new URI(artifactReference); @@ -672,7 +698,7 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme */ private int getMaximumThreads() { try { - String maxThreadString = (String) getProperties().get(PROP_MAX_THREADS); + String maxThreadString = getProperties().get(PROP_MAX_THREADS); if (maxThreadString != null) return Math.max(1, Integer.parseInt(maxThreadString)); } catch (NumberFormatException nfe) { @@ -685,9 +711,7 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme assertModifiable(); // Create a copy of the original descriptor that we can manipulate and add to our repo. - ArtifactDescriptor newDescriptor = new ArtifactDescriptor(descriptor); - if (isFolderBased(descriptor)) - newDescriptor.setRepositoryProperty(ARTIFACT_FOLDER, Boolean.TRUE.toString()); + ArtifactDescriptor newDescriptor = createInternalDescriptor(descriptor); // Check if the artifact is already in this repository, check the newDescriptor instead of the original // since the implementation of hash/equals on the descriptor matters here. @@ -764,13 +788,12 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme } // use this method to setup any transient fields etc after the object has been restored from a stream - public synchronized void initializeAfterLoad(URI location) { - this.location = location; - blobStore = new BlobStore(getBlobStoreLocation(location), 128); + public synchronized void initializeAfterLoad(URI repoLocation) { + this.location = repoLocation; + blobStore = new BlobStore(getBlobStoreLocation(repoLocation), 128); initializeMapper(); - for (Iterator i = artifactDescriptors.iterator(); i.hasNext();) { - ((ArtifactDescriptor) i.next()).setRepository(this); - } + for (SimpleArtifactDescriptor desc : artifactDescriptors) + desc.setRepository(this); } private synchronized void initializeMapper() { @@ -779,13 +802,17 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme } private boolean isFolderBased(IArtifactDescriptor descriptor) { - // if the artifact is just a reference then return the reference location - if (descriptor instanceof ArtifactDescriptor) { - String useArtifactFolder = ((ArtifactDescriptor) descriptor).getRepositoryProperty(ARTIFACT_FOLDER); + // This is called from createInternalDescriptor, so if we aren't a + // SimpleArtifactDescriptor then just check the descriptor properties instead + // of creating the interla descriptor. + SimpleArtifactDescriptor internalDescriptor = null; + if (descriptor instanceof SimpleArtifactDescriptor) + internalDescriptor = (SimpleArtifactDescriptor) descriptor; + if (internalDescriptor != null) { + String useArtifactFolder = internalDescriptor.getRepositoryProperty(ARTIFACT_FOLDER); if (useArtifactFolder != null) return Boolean.valueOf(useArtifactFolder).booleanValue(); } - //TODO: refactor this when the artifact folder property is consistently set in repository properties return Boolean.valueOf(descriptor.getProperty(ARTIFACT_FOLDER)).booleanValue(); } @@ -809,7 +836,7 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme } public synchronized void removeAll() { - IArtifactDescriptor[] toRemove = (IArtifactDescriptor[]) artifactDescriptors.toArray(new IArtifactDescriptor[artifactDescriptors.size()]); + IArtifactDescriptor[] toRemove = artifactDescriptors.toArray(new IArtifactDescriptor[artifactDescriptors.size()]); boolean changed = false; for (int i = 0; i < toRemove.length; i++) changed |= doRemoveArtifact(toRemove[i]); @@ -873,7 +900,7 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme } public void save() { - boolean compress = "true".equalsIgnoreCase((String) properties.get(PROP_COMPRESSED)); //$NON-NLS-1$ + boolean compress = "true".equalsIgnoreCase(properties.get(PROP_COMPRESSED)); //$NON-NLS-1$ save(compress); } @@ -936,7 +963,7 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme } save(); //force repository manager to reload this repository because it caches properties - ArtifactRepositoryManager manager = (ArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); + ArtifactRepositoryManager manager = (ArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); if (manager.removeRepository(getLocation())) manager.addRepository(this); return oldValue; @@ -949,4 +976,18 @@ public class SimpleArtifactRepository extends AbstractArtifactRepository impleme public String toString() { return location.toString(); } + + public IQueryable descriptorQueryable() { + final Collection> descs = artifactMap.values(); + return new IQueryable() { + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return query.perform(new FlatteningIterator(descs.iterator())); + } + }; + } + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return query.perform(artifactMap.keySet().iterator()); + } } diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryFactory.java new file mode 100644 index 000000000..a3aec4822 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryFactory.java @@ -0,0 +1,133 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.artifact.repository.simple; + +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactRepositoryFactory; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.io.*; +import java.net.URI; +import java.util.Map; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.artifact.repository.Activator; +import org.eclipse.equinox.internal.p2.artifact.repository.Messages; +import org.eclipse.equinox.internal.p2.core.helpers.Tracing; +import org.eclipse.equinox.internal.p2.repository.RepositoryTransport; +import org.eclipse.equinox.internal.p2.repository.Transport; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.osgi.util.NLS; + +public class SimpleArtifactRepositoryFactory extends ArtifactRepositoryFactory { + public SimpleArtifactRepositoryFactory() { + super(); + } + + public IArtifactRepository load(URI location, int flags, IProgressMonitor monitor) throws ProvisionException { + final String PROTOCOL_FILE = "file"; //$NON-NLS-1$ + long time = 0; + final String debugMsg = "Restoring artifact repository "; //$NON-NLS-1$ + if (Tracing.DEBUG_METADATA_PARSING) { + Tracing.debug(debugMsg + location); + time = -System.currentTimeMillis(); + } + File localFile = null; + boolean local = false; + try { + SubMonitor sub = SubMonitor.convert(monitor, 300); + OutputStream artifacts = null; + // try with compressed + boolean compress = true; + if (PROTOCOL_FILE.equals(location.getScheme())) { + local = true; + localFile = URIUtil.toFile(SimpleArtifactRepository.getActualLocation(location, true)); + if (!localFile.exists()) { + localFile = URIUtil.toFile(SimpleArtifactRepository.getActualLocation(location, false)); + compress = false; + } + } else { + //not local, return null if the caller wanted a modifiable repo + if ((flags & IRepositoryManager.REPOSITORY_HINT_MODIFIABLE) > 0) { + return null; + } + + //download to local temp file + localFile = File.createTempFile("artifacts", ".xml"); //$NON-NLS-1$ //$NON-NLS-2$ + try { + artifacts = new BufferedOutputStream(new FileOutputStream(localFile)); + IStatus status = getTransport().download(SimpleArtifactRepository.getActualLocation(location, compress), artifacts, sub.newChild(100)); + if (!status.isOK()) { + // not meaningful to continue on an authentication exception (user will likely just be prompted again) + if (status.getCode() == ProvisionException.REPOSITORY_FAILED_AUTHENTICATION) + throw new ProvisionException(status); + // retry uncompressed + compress = false; + status = getTransport().download(SimpleArtifactRepository.getActualLocation(location, compress), artifacts, sub.newChild(100)); + if (!status.isOK()) + throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, status.getMessage(), null)); + } + } finally { + if (artifacts != null) + artifacts.close(); + } + } + InputStream descriptorStream = null; + try { + descriptorStream = new BufferedInputStream(new FileInputStream(localFile)); + if (compress) { + URI actualLocation = SimpleArtifactRepository.getActualLocation(location, false); + JarInputStream jInStream = new JarInputStream(descriptorStream); + JarEntry jarEntry = jInStream.getNextJarEntry(); + String filename = URIUtil.lastSegment(actualLocation); + while (jarEntry != null && filename != null && !(filename.equals(jarEntry.getName()))) { + jarEntry = jInStream.getNextJarEntry(); + } + if (jarEntry == null) { + //there is a jar but the entry is missing or invalid, so treat this as an invalid repository + throw new IOException(NLS.bind(Messages.io_invalidLocation, actualLocation.getPath())); + } + descriptorStream = jInStream; + } + SimpleArtifactRepositoryIO io = new SimpleArtifactRepositoryIO(); + SimpleArtifactRepository result = (SimpleArtifactRepository) io.read(localFile.toURL(), descriptorStream, sub.newChild(100)); + result.initializeAfterLoad(location); + if (Tracing.DEBUG_METADATA_PARSING) { + time += System.currentTimeMillis(); + Tracing.debug(debugMsg + "time (ms): " + time); //$NON-NLS-1$ + } + return result; + } finally { + if (descriptorStream != null) + descriptorStream.close(); + } + } catch (FileNotFoundException e) { + String msg = NLS.bind(Messages.io_failedRead, location); + throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, e)); + } catch (IOException e) { + String msg = NLS.bind(Messages.io_failedRead, location); + throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, msg, e)); + } finally { + if (!local && localFile != null && !localFile.delete()) + localFile.deleteOnExit(); + } + } + + public IArtifactRepository create(URI location, String name, String type, Map properties) { + return new SimpleArtifactRepository(name, location, properties); + } + + private Transport getTransport() { + return RepositoryTransport.getInstance(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryIO.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryIO.java index 85333d106..477aac105 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryIO.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryIO.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. + * Copyright (c) 2007, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,8 +10,12 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.repository.simple; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; import java.io.*; import java.net.URL; @@ -25,11 +29,8 @@ import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; import org.eclipse.equinox.internal.p2.persistence.XMLParser; import org.eclipse.equinox.internal.p2.persistence.XMLWriter; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.core.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.*; import org.eclipse.osgi.util.NLS; import org.osgi.framework.BundleContext; import org.xml.sax.*; @@ -109,9 +110,9 @@ public class SimpleArtifactRepositoryIO { // Constants defining the structure of the XML for a SimpleArtifactRepository // A format version number for simple artifact repository XML. - public static final Version COMPATIBLE_VERSION = new Version(1, 0, 0); - public static final Version CURRENT_VERSION = new Version(1, 1, 0); - public static final VersionRange XML_TOLERANCE = new VersionRange(COMPATIBLE_VERSION, true, new Version(2, 0, 0), false); + public static final Version COMPATIBLE_VERSION = Version.createOSGi(1, 0, 0); + public static final Version CURRENT_VERSION = Version.createOSGi(1, 1, 0); + public static final VersionRange XML_TOLERANCE = new VersionRange(COMPATIBLE_VERSION, true, Version.createOSGi(2, 0, 0), false); // Constants for processing instructions public static final String PI_REPOSITORY_TARGET = "artifactRepository"; //$NON-NLS-1$ @@ -176,11 +177,10 @@ public class SimpleArtifactRepositoryIO { } } - private void writeArtifacts(Set artifactDescriptors) { + private void writeArtifacts(Set artifactDescriptors) { start(ARTIFACTS_ELEMENT); attribute(COLLECTION_SIZE_ATTRIBUTE, artifactDescriptors.size()); - for (Iterator iter = artifactDescriptors.iterator(); iter.hasNext();) { - ArtifactDescriptor descriptor = (ArtifactDescriptor) iter.next(); + for (SimpleArtifactDescriptor descriptor : artifactDescriptors) { IArtifactKey key = descriptor.getArtifactKey(); start(ARTIFACT_ELEMENT); attribute(ARTIFACT_CLASSIFIER_ATTRIBUTE, key.getClassifier()); @@ -194,7 +194,7 @@ public class SimpleArtifactRepositoryIO { end(ARTIFACTS_ELEMENT); } - private void writeProcessingSteps(ProcessingStepDescriptor[] processingSteps) { + private void writeProcessingSteps(IProcessingStepDescriptor[] processingSteps) { if (processingSteps.length > 0) { start(PROCESSING_STEPS_ELEMENT); attribute(COLLECTION_SIZE_ATTRIBUTE, processingSteps.length); @@ -326,9 +326,9 @@ public class SimpleArtifactRepositoryIO { if (isValidXML()) { String[][] mappingRules = (mappingRulesHandler == null ? new String[0][0] // : mappingRulesHandler.getMappingRules()); - Map properties = (propertiesHandler == null ? new OrderedProperties(0) // + Map properties = (propertiesHandler == null ? new OrderedProperties(0) // : propertiesHandler.getProperties()); - Set artifacts = (artifactsHandler == null ? new HashSet(0) // + Set artifacts = (artifactsHandler == null ? new HashSet(0) // : artifactsHandler.getArtifacts()); repository = new SimpleArtifactRepository(attrValues[0], attrValues[1], attrValues[2], attrValues[3], // attrValues[4], artifacts, mappingRules, properties); @@ -338,18 +338,18 @@ public class SimpleArtifactRepositoryIO { protected class MappingRulesHandler extends AbstractHandler { - private List mappingRules; + private List mappingRules; public MappingRulesHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, MAPPING_RULES_ELEMENT); String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - mappingRules = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); + mappingRules = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); } public String[][] getMappingRules() { String[][] rules = new String[mappingRules.size()][2]; for (int index = 0; index < mappingRules.size(); index++) { - String[] ruleAttributes = (String[]) mappingRules.get(index); + String[] ruleAttributes = mappingRules.get(index); rules[index] = ruleAttributes; } return rules; @@ -368,7 +368,7 @@ public class SimpleArtifactRepositoryIO { private final String[] required = new String[] {MAPPING_RULE_FILTER_ATTRIBUTE, MAPPING_RULE_OUTPUT_ATTRIBUTE}; - public MappingRuleHandler(AbstractHandler parentHandler, Attributes attributes, List mappingRules) { + public MappingRuleHandler(AbstractHandler parentHandler, Attributes attributes, List mappingRules) { super(parentHandler, MAPPING_RULE_ELEMENT); mappingRules.add(parseRequiredAttributes(attributes, required)); } @@ -380,15 +380,15 @@ public class SimpleArtifactRepositoryIO { protected class ArtifactsHandler extends AbstractHandler { - private Set artifacts; + private Set artifacts; public ArtifactsHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, ARTIFACTS_ELEMENT); String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - artifacts = (size != null ? new LinkedHashSet(new Integer(size).intValue()) : new LinkedHashSet(4)); + artifacts = (size != null ? new LinkedHashSet(new Integer(size).intValue()) : new LinkedHashSet(4)); } - public Set getArtifacts() { + public Set getArtifacts() { return artifacts; } @@ -405,20 +405,20 @@ public class SimpleArtifactRepositoryIO { private final String[] required = new String[] {ARTIFACT_CLASSIFIER_ATTRIBUTE, ID_ATTRIBUTE, VERSION_ATTRIBUTE}; - private Set artifacts; - ArtifactDescriptor currentArtifact = null; + private Set artifacts; + SimpleArtifactDescriptor currentArtifact = null; private PropertiesHandler propertiesHandler = null; private PropertiesHandler repositoryPropertiesHandler = null; private ProcessingStepsHandler processingStepsHandler = null; - public ArtifactHandler(AbstractHandler parentHandler, Attributes attributes, Set artifacts) { + public ArtifactHandler(AbstractHandler parentHandler, Attributes attributes, Set artifacts) { super(parentHandler, ARTIFACT_ELEMENT); this.artifacts = artifacts; String[] values = parseRequiredAttributes(attributes, required); Version version = checkVersion(ARTIFACT_ELEMENT, VERSION_ATTRIBUTE, values[2]); // TODO: resolve access restriction on ArtifactKey construction - currentArtifact = new ArtifactDescriptor(new ArtifactKey(values[0], values[1], version)); + currentArtifact = new SimpleArtifactDescriptor(new ArtifactKey(values[0], values[1], version)); } public void startElement(String name, Attributes attributes) { @@ -447,13 +447,13 @@ public class SimpleArtifactRepositoryIO { protected void finished() { if (isValidXML() && currentArtifact != null) { - Map properties = (propertiesHandler == null ? new OrderedProperties(0) : propertiesHandler.getProperties()); + Map properties = (propertiesHandler == null ? new OrderedProperties(0) : propertiesHandler.getProperties()); currentArtifact.addProperties(properties); properties = (repositoryPropertiesHandler == null ? new OrderedProperties(0) : repositoryPropertiesHandler.getProperties()); currentArtifact.addRepositoryProperties(properties); - ProcessingStepDescriptor[] processingSteps = (processingStepsHandler == null ? new ProcessingStepDescriptor[0] // + IProcessingStepDescriptor[] processingSteps = (processingStepsHandler == null ? new ProcessingStepDescriptor[0] // : processingStepsHandler.getProcessingSteps()); currentArtifact.setProcessingSteps(processingSteps); artifacts.add(currentArtifact); @@ -463,16 +463,16 @@ public class SimpleArtifactRepositoryIO { protected class ProcessingStepsHandler extends AbstractHandler { - private List processingSteps; + private List processingSteps; public ProcessingStepsHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, PROCESSING_STEPS_ELEMENT); String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - processingSteps = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); + processingSteps = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); } - public ProcessingStepDescriptor[] getProcessingSteps() { - return (ProcessingStepDescriptor[]) processingSteps.toArray(new ProcessingStepDescriptor[processingSteps.size()]); + public IProcessingStepDescriptor[] getProcessingSteps() { + return processingSteps.toArray(new ProcessingStepDescriptor[processingSteps.size()]); } public void startElement(String name, Attributes attributes) { @@ -489,7 +489,7 @@ public class SimpleArtifactRepositoryIO { private final String[] required = new String[] {ID_ATTRIBUTE, STEP_REQUIRED_ATTRIBUTE}; private final String[] optional = new String[] {STEP_DATA_ATTRIBUTE}; - public ProcessingStepHandler(AbstractHandler parentHandler, Attributes attributes, List processingSteps) { + public ProcessingStepHandler(AbstractHandler parentHandler, Attributes attributes, List processingSteps) { super(parentHandler, PROCESSING_STEP_ELEMENT); String[] attributeValues = parseAttributes(attributes, required, optional); processingSteps.add(new ProcessingStepDescriptor(attributeValues[0], attributeValues[2], checkBoolean(PROCESSING_STEP_ELEMENT, STEP_REQUIRED_ATTRIBUTE, attributeValues[1]).booleanValue())); diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/ArtifactComparatorFactory.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/ArtifactComparatorFactory.java deleted file mode 100644 index b9568b02d..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/ArtifactComparatorFactory.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Compeople AG (Stefan Liebig) - various ongoing maintenance - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.artifact.repository; - -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.RegistryFactory; -import org.eclipse.equinox.internal.p2.artifact.repository.Messages; -import org.eclipse.osgi.util.NLS; - -public class ArtifactComparatorFactory { - private static final String comparatorPoint = "org.eclipse.equinox.p2.artifact.repository.artifactComparators"; //$NON-NLS-1$ - private static final String ATTR_ID = "id"; //$NON-NLS-1$ - private static final String ATTR_CLASS = "class"; //$NON-NLS-1$ - - public static IArtifactComparator getArtifactComparator(String comparatorID) { - IConfigurationElement[] extensions = RegistryFactory.getRegistry().getConfigurationElementsFor(comparatorPoint); - - IConfigurationElement element = null; - if (comparatorID == null && extensions.length > 0) { - element = extensions[0]; //just take the first one - } else { - for (int i = 0; i < extensions.length; i++) { - if (extensions[i].getAttribute(ATTR_ID).equals(comparatorID)) { - element = extensions[i]; - break; - } - } - } - if (element != null) { - try { - Object execExt = element.createExecutableExtension(ATTR_CLASS); - if (execExt instanceof IArtifactComparator) - return (IArtifactComparator) execExt; - } catch (Exception e) { - //fall through - } - } - - if (comparatorID != null) - throw new IllegalArgumentException(NLS.bind(Messages.exception_comparatorNotFound, comparatorID)); - throw new IllegalArgumentException(Messages.exception_noComparators); - } -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/ArtifactDescriptor.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/ArtifactDescriptor.java deleted file mode 100644 index 33c526325..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/ArtifactDescriptor.java +++ /dev/null @@ -1,191 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.artifact.repository; - -import java.util.Arrays; -import java.util.Map; -import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; - -/** - * This represents information about a given artifact stored on a particular byte server. - */ -public class ArtifactDescriptor implements IArtifactDescriptor { - public static final String ARTIFACT_REFERENCE = "artifact.reference"; //$NON-NLS-1$ - - private static final ProcessingStepDescriptor[] EMPTY_STEPS = new ProcessingStepDescriptor[0]; - - protected IArtifactKey key; // The key associated with this artifact - - // The list of post processing steps that must be applied one the artifact once it - // has been downloaded (e.g, unpack, then md5 checksum, then...) - protected ProcessingStepDescriptor[] processingSteps = EMPTY_STEPS; - - protected Map properties = new OrderedProperties(); - protected Map repositoryProperties = new OrderedProperties(); - - protected transient IArtifactRepository repository; - - // QUESTION: Do we need any description or user readable name - - public ArtifactDescriptor(IArtifactDescriptor base) { - super(); - key = base.getArtifactKey(); - processingSteps = base.getProcessingSteps(); - properties.putAll(base.getProperties()); - repository = base.getRepository(); - // TODO this property is hardcoded for the blob store. - // setProperty("artifact.uuid", base.getProperty("artifact.uuid")); - } - - public ArtifactDescriptor(ArtifactDescriptor base) { - super(); - key = base.key; - processingSteps = base.processingSteps; - properties = base.properties; - repository = base.repository; - } - - public ArtifactDescriptor(IArtifactKey key) { - super(); - this.key = key; - } - - public IArtifactKey getArtifactKey() { - return key; - } - - public String getProperty(String propertyKey) { - return (String) properties.get(propertyKey); - } - - public void setProperty(String key, String value) { - if (value == null) - properties.remove(key); - else - properties.put(key, value); - } - - public void addProperties(Map additionalProperties) { - properties.putAll(additionalProperties); - } - - /** - * Returns a read-only collection of the properties of the artifact descriptor. - * @return the properties of this artifact descriptor. - */ - public Map getProperties() { - return OrderedProperties.unmodifiableProperties(properties); - } - - public String getRepositoryProperty(String propertyKey) { - return (String) repositoryProperties.get(propertyKey); - } - - public void setRepositoryProperty(String key, String value) { - if (value == null) - repositoryProperties.remove(key); - else - repositoryProperties.put(key, value); - } - - public void addRepositoryProperties(Map additionalProperties) { - repositoryProperties.putAll(additionalProperties); - } - - /** - * Returns a read-only collection of the repository properties of the artifact descriptor. - * @return the repository properties of this artifact descriptor. - */ - public Map getRepositoryProperties() { - return OrderedProperties.unmodifiableProperties(repositoryProperties); - } - - public ProcessingStepDescriptor[] getProcessingSteps() { - return processingSteps; - } - - public void setProcessingSteps(ProcessingStepDescriptor[] value) { - processingSteps = value == null ? EMPTY_STEPS : value; - } - - // Implementation of both equals and hash depends on the implementation of - // SimpleArtifactRepository#getOutputStream(IArtifactDescriptor) - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ArtifactDescriptor other = (ArtifactDescriptor) obj; - if (key == null) { - if (other.key != null) - return false; - } else if (!key.equals(other.key)) - return false; - if (!Arrays.equals(processingSteps, other.processingSteps)) - return false; - - //Properties affecting SimpleArtifactRepository#getLocation - String locationProperty = getRepositoryProperty(ARTIFACT_REFERENCE); - String otherProperty = other.getRepositoryProperty(ARTIFACT_REFERENCE); - // want not null and the same, or both null - if (locationProperty != null ? !locationProperty.equals(otherProperty) : otherProperty != null) - return false; - - locationProperty = getProperty(FORMAT); - otherProperty = other.getProperty(FORMAT); - if (locationProperty != null ? !locationProperty.equals(otherProperty) : otherProperty != null) - return false; - - return true; - } - - private int hashCode(Object[] array) { - int prime = 31; - if (array == null) - return 0; - int result = 1; - for (int index = 0; index < array.length; index++) { - result = prime * result + (array[index] == null ? 0 : array[index].hashCode()); - } - return result; - } - - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((key == null) ? 0 : key.hashCode()); - result = prime * result + hashCode(processingSteps); - - String[] hashProperties = new String[] {getRepositoryProperty(ARTIFACT_REFERENCE), getProperty(FORMAT)}; - result = prime * result + hashCode(hashProperties); - return result; - } - - public IArtifactRepository getRepository() { - return repository; - } - - public void setRepository(IArtifactRepository value) { - repository = value; - } - - public String toString() { - String format = getProperty(IArtifactDescriptor.FORMAT); - if (format == null) - return "canonical: " + key.toString(); //$NON-NLS-1$ - return format + ": " + key.toString(); //$NON-NLS-1$ - } - -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactComparator.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactComparator.java deleted file mode 100644 index 6ba7d556f..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactComparator.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. All rights reserved. This - * program and the accompanying materials are made available under the terms of - * the Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: IBM Corporation - initial API and implementation - ******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.artifact.repository; - -import org.eclipse.core.runtime.IStatus; - -public interface IArtifactComparator { - - /** - * Compare 2 equivalent IArtifactDescriptors from different repositories. - * - * IArtifactDescriptors with the same id and version should represent the same - * set of bytes. The comparator should ensure this is true and return an error - * or warning otherwise. - * - * @param source - The source IArtifactRepository - * @param sourceDescriptor - The IArtifactDescriptor from the source repository - * @param destination - The target IArtifactRepository - * @param destDescriptor - The IArtifactDescriptor from the target repository - * - * @return IStatus - */ - public IStatus compare(IArtifactRepository source, IArtifactDescriptor sourceDescriptor, IArtifactRepository destination, IArtifactDescriptor destDescriptor); -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactDescriptor.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactDescriptor.java deleted file mode 100644 index 835950693..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactDescriptor.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.artifact.repository; - -import java.util.Map; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; - -public interface IArtifactDescriptor { - - public static final String DOWNLOAD_SIZE = "download.size"; //$NON-NLS-1$ - public static final String ARTIFACT_SIZE = "artifact.size"; //$NON-NLS-1$ - public static final String DOWNLOAD_MD5 = "download.md5"; //$NON-NLS-1$ - public static final String DOWNLOAD_CONTENTTYPE = "download.contentType"; //$NON-NLS-1$ - public static final String TYPE_ZIP = "application/zip"; //$NON-NLS-1$ - public static final String ARTIFACT_MD5 = "artifact.md5"; //$NON-NLS-1$ - public static final String FORMAT = "format"; //$NON-NLS-1$ - - /** - * Return the key for the artifact described by this descriptor. - * @return the key associated with this descriptor - */ - public abstract IArtifactKey getArtifactKey(); - - /** - * Return the value of the given property in this descriptor null - * is returned if no such property exists - * @param key the property key to look for - * @return the value of the given property or null - */ - public abstract String getProperty(String key); - - /** - * Returns a read-only collection of the properties of the artifact descriptor. - * @return the properties of this artifact descriptor. - */ - public Map getProperties(); - - /** - * Return the list of processing steps associated with this descriptor. - * An empty set of steps implies that this descriptor describes a complete - * copy of the artifact in its native form. - * @return the list of processing steps for this descriptor - */ - public abstract ProcessingStepDescriptor[] getProcessingSteps(); - - /** - * Return the artifact repository that holds the artifact described by this descriptor. - * null is returned if this descriptor is not held in a repository. - * - * @return the repository holding this artifact or null if none. - */ - public abstract IArtifactRepository getRepository(); -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactRepository.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactRepository.java deleted file mode 100644 index c793545ab..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactRepository.java +++ /dev/null @@ -1,133 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.artifact.repository; - -import java.io.OutputStream; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.AbstractArtifactRepository; - -/** - * A repository containing artifacts. - *

- * This interface is not intended to be implemented by clients. Artifact repository - * implementations must subclass {@link AbstractArtifactRepository} rather than - * implementing this interface directly. - *

- * @noimplement This interface is not intended to be implemented by clients. - */ -public interface IArtifactRepository extends IRepository { - - /** - * The return code to use when a client could/should retry a failed getArtifact() operation. - * For example, the repository may have additional mirrors that could be consulted. - */ - public static int CODE_RETRY = 13; - - /** - * Add the given descriptor to the set of descriptors in this repository. This is - * a relatively low-level operation that should be used only when the actual related - * content is in this repository and the given descriptor accurately describes - * that content. - * @param descriptor the descriptor to add. - */ - public void addDescriptor(IArtifactDescriptor descriptor); - - /** - * Add the given artifact descriptors to this repository - * @param descriptors the artifact descriptors to add - */ - public void addDescriptors(IArtifactDescriptor[] descriptors); - - /** - * Returns true if this repository contains the given descriptor. - * @param descriptor the descriptor to query - * @return true if the given descriptor is already in this repository - */ - public boolean contains(IArtifactDescriptor descriptor); - - /** - * Returns true if this repository contains the given artifact key. - * @param key the key to query - * @return true if the given key is already in this repository - */ - public boolean contains(IArtifactKey key); - - /** - * Write to the given output stream the bytes represented by the artifact descriptor processed by the processing steps of the given descriptor. - */ - public IStatus getArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor); - - /** - * Write to the given output stream the bytes represented by the artifact descriptor without processing by the steps of the given descriptor. - */ - public IStatus getRawArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor); - - /** - * Return the set of artifact descriptors describing the ways that this repository - * can supply the artifact associated with the given artifact key - * @param key the artifact key to lookup - * @return the descriptors associated with the given key - */ - public IArtifactDescriptor[] getArtifactDescriptors(IArtifactKey key); - - /** - * Returns the list of artifact keys managed by this repository - * @return list of artifact keys - */ - public IArtifactKey[] getArtifactKeys(); - - /** - * Executes the given artifact requests on this byte server. - * @param requests The artifact requests - * @param monitor - * @return a status object that is OK if requests were - * processed successfully. Otherwise, a status indicating information, - * warnings, or errors that occurred while executing the artifact requests - */ - public IStatus getArtifacts(IArtifactRequest[] requests, IProgressMonitor monitor); - - /** - * Open an output stream to which a client can write the data for the given - * artifact descriptor. - * @param descriptor the descriptor describing the artifact data to be written to the - * resultant stream - * @return the stream to which the artifact content can be written. The returned output - * stream may implement IStateful. - * @throws ProvisionException if the output stream could not be created. Reasons include: - *
    - *
  • An I/O exception occurred (@link {@link ProvisionException#REPOSITORY_FAILED_WRITE}) .
  • - *
  • An artifact already exists at that location ({@link ProvisionException#ARTIFACT_EXISTS}).
  • - *
- */ - public OutputStream getOutputStream(IArtifactDescriptor descriptor) throws ProvisionException; - - /** - * Remove the all keys, descriptors, and contents from this repository. - */ - public void removeAll(); - - /** - * Remove the given descriptor and its corresponding content in this repository. - * @param descriptor the descriptor to remove. - */ - public void removeDescriptor(IArtifactDescriptor descriptor); - - /** - * Remove the given key and all related content and descriptors from this repository. - * @param key the key to remove. - */ - public void removeDescriptor(IArtifactKey key); - -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactRepositoryManager.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactRepositoryManager.java deleted file mode 100644 index c804670f4..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactRepositoryManager.java +++ /dev/null @@ -1,149 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.artifact.repository; - -import java.net.URI; -import java.util.Map; -import java.util.Properties; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; - -/** - * A metadata repository manager is used to create, access, and manipulate - * {@link IArtifactRepository} instances. See {@link IRepositoryManager} - * for a general description of the characteristics of repository managers. - * - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface IArtifactRepositoryManager extends IRepositoryManager { - /** - * The name used for obtaining a reference to the metadata repository manager service - */ - public static final String SERVICE_NAME = IArtifactRepositoryManager.class.getName(); - - public static final IArtifactRequest[] NO_ARTIFACT_REQUEST = new IArtifactRequest[0]; - - /** - * Repository type for a simple repository based on a URL or local file system location. - */ - public static final String TYPE_SIMPLE_REPOSITORY = "org.eclipse.equinox.p2.artifact.repository.simpleRepository"; //$NON-NLS-1$ - public static final String TYPE_COMPOSITE_REPOSITORY = "org.eclipse.equinox.p2.artifact.repository.compositeRepository"; //$NON-NLS-1$ - - /** - * Return a new request to mirror the given artifact into the destination repository. - * @param key the artifact to mirror - * @param destination the destination where the artifact will be mirrored - * @param destinationDescriptorProperties additional properties for use in creating the repository's ArtifactDescriptor, - * or null to indicate no additional properties are needed - * @param destinationRepositoryProperties additional repository specific properties for use in creating the repositor's ArtifactDescriptor, - * , or null to indicate no additional properties are needed - * @return the newly created request object - */ - public IArtifactRequest createMirrorRequest(IArtifactKey key, IArtifactRepository destination, Properties destinationDescriptorProperties, Properties destinationRepositoryProperties); - - /** - * Creates and returns a new empty artifact repository of the given type at - * the given location. - *

- * The resulting repository is added to the list of repositories tracked by - * the repository manager. Clients must make a subsequent call to {@link #removeRepository(URI)} - * if they do not want the repository manager to remember the repository for subsequent - * load attempts. - *

- * - * @param location the absolute location for the new repository - * @param name the name of the new repository - * @param type the kind of repository to create - * @param properties the properties to set on the repository - * @return the newly created repository - * @throws ProvisionException if the repository could not be created. Reasons include: - *
    - *
  • The repository type is unknown.
  • - *
  • There was an error writing to the given repository location.
  • - *
  • A repository already exists at that location.
  • - *
- */ - public IArtifactRepository createRepository(URI location, String name, String type, Map properties) throws ProvisionException; - - /** - * Loads the repository at the given location. The location is expected to contain - * data that describes a valid artifact repository of a known type. If this manager - * already knows a repository at the given location then that repository is returned. - *

- * The resulting repository is added to the list of repositories tracked by - * the repository manager. Clients must make a subsequent call to {@link #removeRepository(URI)} - * if they do not want the repository manager to remember the repository for subsequent - * load attempts. - *

- * - * @param location the absolute location in which to look for a repository description - * @param monitor a progress monitor, or null if progress - * reporting is not desired - * @return a repository object for the given location - * @throws ProvisionException if the repository could not be created. Reasons include: - *
    - *
  • There is no existing repository at that location.
  • - *
  • The repository at that location could not be read.
  • - *
- */ - public IArtifactRepository loadRepository(URI location, IProgressMonitor monitor) throws ProvisionException; - - /** - * Loads the repository at the given location. The location is expected to contain - * data that describes a valid artifact repository of a known type. If this manager - * already knows a repository at the given location then that repository is returned. - *

- * The resulting repository is added to the list of repositories tracked by - * the repository manager. Clients must make a subsequent call to {@link #removeRepository(URI)} - * if they do not want the repository manager to remember the repository for subsequent - * load attempts. - *

- *

- * The flags passed in should be taken as a hint for the type of repository to load. If - * the manager cannot load a repository that satisfies these hints, it can fail fast. - *

- * @param location the absolute location in which to look for a repository description - * @param flags - bit-wise or of flags to consider when loading the repository - * (currently only {@link IRepositoryManager#REPOSITORY_HINT_MODIFIABLE} is supported) - * @param monitor a progress monitor, or null if progress - * reporting is not desired - * @return a repository object for the given location - * @throws ProvisionException if the repository could not be created. Reasons include: - *
    - *
  • There is no existing repository at that location.
  • - *
  • The repository at that location could not be read.
  • - *
- * @see IRepositoryManager#REPOSITORY_HINT_MODIFIABLE - */ - public IArtifactRepository loadRepository(URI location, int flags, IProgressMonitor monitor) throws ProvisionException; - - /** - * Refreshes the repository corresponding to the given URL. This method discards - * any cached state held by the repository manager and reloads the repository - * contents. The provided repository location must already be known to the repository - * manager. - * - * @param location The absolute location of the repository to refresh - * @param monitor a progress monitor, or null if progress - * reporting is not desired - * @return The refreshed metadata repository - * @throws ProvisionException if the repository could not be created. Reasons include: - *
    - *
  • The location is not known to the repository manager.
  • - *
  • There is no existing repository at that location.
  • - *
  • The repository at that location could not be read.
  • - *
- */ - public IArtifactRepository refreshRepository(URI location, IProgressMonitor monitor) throws ProvisionException; - -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactRequest.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactRequest.java deleted file mode 100644 index f68e11d3c..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IArtifactRequest.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.artifact.repository; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.p2.artifact.repository.ArtifactRequest; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; - -/** - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface IArtifactRequest { - - public IArtifactKey getArtifactKey(); - - /** - * Returns the result of the previous call to {@link ArtifactRequest#perform(IProgressMonitor)}, - * or null if perform has never been called. - * - * @return The result of the previous perform call. - */ - public IStatus getResult(); - -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IFileArtifactRepository.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IFileArtifactRepository.java deleted file mode 100644 index 6e6e07be3..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/IFileArtifactRepository.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.artifact.repository; - -import java.io.File; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; - -public interface IFileArtifactRepository extends IArtifactRepository { - /** - * Return the location of the full local file corresponding to the given - * artifact key to the given key, or null if not available. - * - * @return the location of the requested artifact ornull if not available - */ - public File getArtifactFile(IArtifactKey key); - - /** - * Return the location of the local file corresponding to the given - * artifact descriptor, or null if not available. - * - * @return the location of the requested descriptor ornull if not available - */ - public File getArtifactFile(IArtifactDescriptor descriptor); -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStep.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStep.java index 15375f95d..403670e1a 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStep.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStep.java @@ -11,11 +11,13 @@ *******************************************************************************/ package org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing; +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; + import java.io.IOException; import java.io.OutputStream; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; import org.eclipse.equinox.internal.provisional.p2.repository.IStateful; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; /** * ProcessingSteps process the data written to them and pass the resultant data on @@ -39,7 +41,7 @@ public abstract class ProcessingStep extends OutputStream implements IStateful { * @param descriptor description of the step * @param context the context in which the step is being used */ - public void initialize(ProcessingStepDescriptor descriptor, IArtifactDescriptor context) { + public void initialize(IProcessingStepDescriptor descriptor, IArtifactDescriptor context) { // nothing to do here! } diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStepDescriptor.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStepDescriptor.java deleted file mode 100644 index f7db92d7e..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStepDescriptor.java +++ /dev/null @@ -1,89 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007, 2008 compeople AG and others. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* compeople AG (Stefan Liebig) - initial API and implementation -*******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing; - -/** - * The description of a processor step. - */ -public class ProcessingStepDescriptor { - - private final String processorId; //the operation to be applied (e.g: unpack, md5, signature verification, etc.) - private final String data; //data requested for the processing (eg. expected checksum) - private final boolean required; //whether the step is optional or not - - /** - * Create a processing step description. - * - * @param processorId - * @param data - * @param required - */ - public ProcessingStepDescriptor(String processorId, String data, boolean required) { - super(); - this.processorId = processorId; - this.data = data; - this.required = required; - } - - public String getProcessorId() { - return processorId; - } - - public String getData() { - return data; - } - - public boolean isRequired() { - return required; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((data == null) ? 0 : data.hashCode()); - result = prime * result + ((processorId == null) ? 0 : processorId.hashCode()); - result = prime * result + (required ? 1231 : 1237); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof ProcessingStepDescriptor)) - return false; - final ProcessingStepDescriptor other = (ProcessingStepDescriptor) obj; - if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; - if (processorId == null) { - if (other.processorId != null) - return false; - } else if (!processorId.equals(other.processorId)) - return false; - if (required != other.required) - return false; - return true; - } - - public String toString() { - return "Processor: " + processorId + (required ? "(req)" : "(notReq)") + " ,data: " + data; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ - } -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStepHandler.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStepHandler.java index 508c46486..0387fcd28 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStepHandler.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStepHandler.java @@ -11,13 +11,15 @@ *******************************************************************************/ package org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing; +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; + import java.io.OutputStream; import java.util.ArrayList; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.artifact.repository.Activator; import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository.ArtifactOutputStream; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; import org.eclipse.equinox.internal.provisional.p2.repository.IStateful; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; import org.eclipse.osgi.util.NLS; /** @@ -42,7 +44,7 @@ public class ProcessingStepHandler { IExtensionPoint point = registry.getExtensionPoint(PROCESSING_STEPS_EXTENSION_ID); if (point == null) return false; - ProcessingStepDescriptor[] steps = descriptor.getProcessingSteps(); + IProcessingStepDescriptor[] steps = descriptor.getProcessingSteps(); for (int i = 0; i < steps.length; i++) { if (point.getExtension(steps[i].getProcessorId()) == null) return false; @@ -60,11 +62,11 @@ public class ProcessingStepHandler { public static IStatus getStatus(OutputStream stream, boolean deep) { if (!deep) return getStatus(stream); - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList(); int severity = collectStatus(stream, list); if (severity == IStatus.OK) return Status.OK_STATUS; - IStatus[] result = (IStatus[]) list.toArray(new IStatus[list.size()]); + IStatus[] result = list.toArray(new IStatus[list.size()]); return new MultiStatus(Activator.ID, severity, result, Messages.processing_step_results, null); } @@ -74,15 +76,15 @@ public class ProcessingStepHandler { * @return the requested status */ public static IStatus getErrorStatus(OutputStream stream) { - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList(); int severity = collectErrorStatus(stream, list); if (severity == IStatus.OK) return Status.OK_STATUS; - IStatus[] result = (IStatus[]) list.toArray(new IStatus[list.size()]); + IStatus[] result = list.toArray(new IStatus[list.size()]); return new MultiStatus(Activator.ID, 0, result, Messages.processing_step_results, null); } - private static int collectErrorStatus(OutputStream stream, ArrayList list) { + private static int collectErrorStatus(OutputStream stream, ArrayList list) { IStatus status = getStatus(stream); if (!status.isOK()) list.add(status); @@ -105,7 +107,7 @@ public class ProcessingStepHandler { return Status.OK_STATUS; } - private static int collectStatus(OutputStream stream, ArrayList list) { + private static int collectStatus(OutputStream stream, ArrayList list) { IStatus status = getStatus(stream); list.add(status); OutputStream destination = getDestination(stream); @@ -125,14 +127,14 @@ public class ProcessingStepHandler { return null; } - public ProcessingStep[] create(ProcessingStepDescriptor[] descriptors, IArtifactDescriptor context) { + public ProcessingStep[] create(IProcessingStepDescriptor[] descriptors, IArtifactDescriptor context) { ProcessingStep[] result = new ProcessingStep[descriptors.length]; for (int i = 0; i < descriptors.length; i++) result[i] = create(descriptors[i], context); return result; } - public ProcessingStep create(ProcessingStepDescriptor descriptor, IArtifactDescriptor context) { + public ProcessingStep create(IProcessingStepDescriptor descriptor, IArtifactDescriptor context) { IExtensionRegistry registry = RegistryFactory.getRegistry(); IExtension extension = registry.getExtension(PROCESSING_STEPS_EXTENSION_ID, descriptor.getProcessorId()); Exception error; @@ -155,7 +157,7 @@ public class ProcessingStepHandler { return result; } - public OutputStream createAndLink(ProcessingStepDescriptor[] descriptors, IArtifactDescriptor context, OutputStream output, IProgressMonitor monitor) { + public OutputStream createAndLink(IProcessingStepDescriptor[] descriptors, IArtifactDescriptor context, OutputStream output, IProgressMonitor monitor) { if (descriptors == null) return output; ProcessingStep[] steps = create(descriptors, context); diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/artifact/repository/AbstractArtifactRepository.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/artifact/repository/AbstractArtifactRepository.java deleted file mode 100644 index a5b04501b..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/artifact/repository/AbstractArtifactRepository.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository; - -import java.io.OutputStream; -import java.net.URI; -import java.util.Map; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.spi.p2.repository.AbstractRepository; - -public abstract class AbstractArtifactRepository extends AbstractRepository implements IArtifactRepository { - - protected AbstractArtifactRepository(String name, String type, String version, URI location, String description, String provider, Map properties) { - super(name, type, version, location, description, provider, properties); - } - - public abstract boolean contains(IArtifactDescriptor descriptor); - - public abstract boolean contains(IArtifactKey key); - - public abstract IStatus getArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor); - - public abstract IArtifactDescriptor[] getArtifactDescriptors(IArtifactKey key); - - public abstract IArtifactKey[] getArtifactKeys(); - - public abstract IStatus getArtifacts(IArtifactRequest[] requests, IProgressMonitor monitor); - - public abstract OutputStream getOutputStream(IArtifactDescriptor descriptor) throws ProvisionException; - - public void addDescriptor(IArtifactDescriptor descriptor) { - assertModifiable(); - } - - public void addDescriptors(IArtifactDescriptor[] descriptors) { - assertModifiable(); - } - - public void removeDescriptor(IArtifactDescriptor descriptor) { - assertModifiable(); - } - - public void removeDescriptor(IArtifactKey key) { - assertModifiable(); - } - - public void removeAll() { - assertModifiable(); - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof AbstractArtifactRepository)) { - return false; - } - if (URIUtil.sameURI(getLocation(), ((AbstractArtifactRepository) o).getLocation())) - return true; - return false; - } - - public int hashCode() { - return (this.getLocation().toString().hashCode()) * 87; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/artifact/repository/ArtifactRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/artifact/repository/ArtifactRepositoryFactory.java deleted file mode 100644 index fce9f4e85..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/artifact/repository/ArtifactRepositoryFactory.java +++ /dev/null @@ -1,75 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository; - -import java.net.URI; -import java.util.Map; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; - -/** - * An artifact repository factory is responsible for creating and loading instances - * of a particular type of artifact repository. Factories are provided via the - * org.eclipse.equinox.p2.artifact.repository.artifactRepositories extension point. - */ -public abstract class ArtifactRepositoryFactory { - - /** - * Creates and returns a new empty artifact repository of the given type at - * the given location. - * - * @param location the location for the new repository - * @param name the name of the new repository - * @param type the kind of repository to create - * @param properties the properties to set on the repository - * @return the newly created repository - * @throws ProvisionException if the repository could not be created. Reasons include: - *
    - *
  • The repository type is unknown.
  • - *
  • There was an error writing to the given repository location.
  • - *
  • A repository already exists at that location.
  • - *
- */ - public abstract IArtifactRepository create(URI location, String name, String type, Map properties) throws ProvisionException; - - /** - * Loads and returns the repository of this factory's type at the given location. - *

- * The error code returned in the case of failure is significant. In particular an - * error code of {@link ProvisionException#REPOSITORY_FAILED_READ} indicates - * that the location definitely identifies a repository of this type, but an error occurred - * while loading the repository. The repository manager will not attempt to load - * a repository from that location using any other factory. An error code of - * {@link ProvisionException#REPOSITORY_NOT_FOUND} indicates there is no - * repository of this type at the given location, and the repository manager is free - * to try again with a different repository factory. - *

- *

- * The flags passed in should be taken as a hint for the type of repository to load. If - * the factory knows it will not load a repository that satisfies these hints, it can fail - * fast and return null. - * @see IRepositoryManager#REPOSITORY_HINT_MODIFIABLE - *

- * @param location the location in which to look for a repository description - * @param flags to consider while loading the repository - * @param monitor a progress monitor, or null if progress - * reporting is not desired - * @return a repository object for the given location - * @throws ProvisionException if the repository could not be created. Reasons include: - *
    - *
  • There is no existing repository at that location.
  • - *
  • The repository at that location could not be read.
  • - *
- */ - public abstract IArtifactRepository load(URI location, int flags, IProgressMonitor monitor) throws ProvisionException; -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/artifact/repository/SimpleArtifactRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/artifact/repository/SimpleArtifactRepositoryFactory.java deleted file mode 100644 index d9744eadb..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/artifact/repository/SimpleArtifactRepositoryFactory.java +++ /dev/null @@ -1,129 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository; - -import java.io.*; -import java.net.URI; -import java.util.Map; -import java.util.jar.JarEntry; -import java.util.jar.JarInputStream; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.artifact.repository.Activator; -import org.eclipse.equinox.internal.p2.artifact.repository.Messages; -import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository; -import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepositoryIO; -import org.eclipse.equinox.internal.p2.core.helpers.Tracing; -import org.eclipse.equinox.internal.p2.repository.RepositoryTransport; -import org.eclipse.equinox.internal.p2.repository.Transport; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.osgi.util.NLS; - -public class SimpleArtifactRepositoryFactory extends ArtifactRepositoryFactory { - - public IArtifactRepository load(URI location, int flags, IProgressMonitor monitor) throws ProvisionException { - final String PROTOCOL_FILE = "file"; //$NON-NLS-1$ - long time = 0; - final String debugMsg = "Restoring artifact repository "; //$NON-NLS-1$ - if (Tracing.DEBUG_METADATA_PARSING) { - Tracing.debug(debugMsg + location); - time = -System.currentTimeMillis(); - } - File localFile = null; - boolean local = false; - try { - SubMonitor sub = SubMonitor.convert(monitor, 300); - OutputStream artifacts = null; - // try with compressed - boolean compress = true; - if (PROTOCOL_FILE.equals(location.getScheme())) { - local = true; - localFile = URIUtil.toFile(SimpleArtifactRepository.getActualLocation(location, true)); - if (!localFile.exists()) { - localFile = URIUtil.toFile(SimpleArtifactRepository.getActualLocation(location, false)); - compress = false; - } - } else { - //not local, return null if the caller wanted a modifiable repo - if ((flags & IRepositoryManager.REPOSITORY_HINT_MODIFIABLE) > 0) { - return null; - } - - //download to local temp file - localFile = File.createTempFile("artifacts", ".xml"); //$NON-NLS-1$ //$NON-NLS-2$ - try { - artifacts = new BufferedOutputStream(new FileOutputStream(localFile)); - IStatus status = getTransport().download(SimpleArtifactRepository.getActualLocation(location, compress), artifacts, sub.newChild(100)); - if (!status.isOK()) { - // not meaningful to continue on an authentication exception (user will likely just be prompted again) - if (status.getCode() == ProvisionException.REPOSITORY_FAILED_AUTHENTICATION) - throw new ProvisionException(status); - // retry uncompressed - compress = false; - status = getTransport().download(SimpleArtifactRepository.getActualLocation(location, compress), artifacts, sub.newChild(100)); - if (!status.isOK()) - throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, status.getMessage(), null)); - } - } finally { - if (artifacts != null) - artifacts.close(); - } - } - InputStream descriptorStream = null; - try { - descriptorStream = new BufferedInputStream(new FileInputStream(localFile)); - if (compress) { - URI actualLocation = SimpleArtifactRepository.getActualLocation(location, false); - JarInputStream jInStream = new JarInputStream(descriptorStream); - JarEntry jarEntry = jInStream.getNextJarEntry(); - String filename = URIUtil.lastSegment(actualLocation); - while (jarEntry != null && filename != null && !(filename.equals(jarEntry.getName()))) { - jarEntry = jInStream.getNextJarEntry(); - } - if (jarEntry == null) { - //there is a jar but the entry is missing or invalid, so treat this as an invalid repository - throw new IOException(NLS.bind(Messages.io_invalidLocation, actualLocation.getPath())); - } - descriptorStream = jInStream; - } - SimpleArtifactRepositoryIO io = new SimpleArtifactRepositoryIO(); - SimpleArtifactRepository result = (SimpleArtifactRepository) io.read(localFile.toURL(), descriptorStream, sub.newChild(100)); - result.initializeAfterLoad(location); - if (Tracing.DEBUG_METADATA_PARSING) { - time += System.currentTimeMillis(); - Tracing.debug(debugMsg + "time (ms): " + time); //$NON-NLS-1$ - } - return result; - } finally { - if (descriptorStream != null) - descriptorStream.close(); - } - } catch (FileNotFoundException e) { - String msg = NLS.bind(Messages.io_failedRead, location); - throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, e)); - } catch (IOException e) { - String msg = NLS.bind(Messages.io_failedRead, location); - throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, msg, e)); - } finally { - if (!local && localFile != null && !localFile.delete()) - localFile.deleteOnExit(); - } - } - - public IArtifactRepository create(URI location, String name, String type, Map properties) { - return new SimpleArtifactRepository(name, location, properties); - } - - private Transport getTransport() { - return RepositoryTransport.getInstance(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/AddChildTask.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/AddChildTask.java deleted file mode 100644 index a2e122805..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/AddChildTask.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.artifact.repository.ant; - -import java.net.URI; -import java.net.URISyntaxException; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Task; -import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.p2.artifact.repository.Activator; -import org.eclipse.equinox.internal.p2.artifact.repository.CompositeArtifactRepository; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; - -/** - * Ant task to add a child artifact repository to an already-existing composite artifact repository. - */ -public class AddChildTask extends Task { - - URI location; // location of the composite repository - URI child; // address of the child to add - String comparatorID; // comparator to use for compare (optional) - - /* (non-Javadoc) - * @see org.apache.tools.ant.Task#execute() - */ - public void execute() { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); - if (manager == null) - throw new BuildException("Unable to acquire artifact repository manager service."); - - // get the composite repository - CompositeArtifactRepository repo = null; - try { - repo = (CompositeArtifactRepository) manager.loadRepository(location, null); - } catch (ProvisionException e) { - throw new BuildException("Exception while loading repository.", e); - } - - // just do a straight add if the user didn't specify a comparator. - if (comparatorID == null) { - repo.addChild(child); - return; - } - - // otherwise run the comparator when we try and add the child and print out the result. - if (repo.addChild(child, comparatorID)) - System.out.println(child + " was added successfully."); - else - System.out.println(child + " was not added."); - } - - /* - * Set the location of the composite repository. - */ - public void setLocation(String value) throws URISyntaxException { - location = URIUtil.fromString(value); - } - - /* - * Set the location of the child repository. - */ - public void setChild(String value) throws URISyntaxException { - child = URIUtil.fromString(value); - } - - /* - * Set the identifier of the comparator to use. - */ - public void setComparatorID(String value) { - comparatorID = value; - } -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/AntMirrorLog.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/AntMirrorLog.java deleted file mode 100644 index 9d30c11f0..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/AntMirrorLog.java +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.artifact.repository.ant; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.p2.artifact.mirror.IArtifactMirrorLog; -import org.eclipse.equinox.internal.p2.artifact.repository.Messages; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; - -public class AntMirrorLog implements IArtifactMirrorLog { - - private boolean consoleMessage = false; - private Method log; - private Object task; - - public AntMirrorLog(Object task) throws NoSuchMethodException { - this.task = task; - try { - log = task.getClass().getMethod("log", new Class[] {String.class, int.class}); //$NON-NLS-1$ - } catch (SecurityException e) { - exceptionOccurred(null, e); - } - } - - public void log(IArtifactDescriptor descriptor, IStatus status) { - log(descriptor.toString(), status.getSeverity()); - log(status); - } - - public void log(IStatus status) { - int severity = status.getSeverity(); - // Log the status message - log(status.getMessage(), severity); - // Log the exception if applicable - if (status.getException() != null) - log(status.getException().getMessage(), severity); - - // Log any children of this status - IStatus[] nestedStatus = status.getChildren(); - if (nestedStatus != null) - for (int i = 0; i < nestedStatus.length; i++) - log(nestedStatus[i]); - } - - public void close() { - // nothing to do here - } - - /* - * Log a message to the Ant Task - */ - private void log(String message, int statusSeverity) { - try { - log.invoke(task, new Object[] {message, new Integer(mapLogLevels(statusSeverity))}); - } catch (IllegalArgumentException e) { - exceptionOccurred(message, e); - } catch (IllegalAccessException e) { - exceptionOccurred(message, e); - } catch (InvocationTargetException e) { - exceptionOccurred(message, e); - } - } - - /* - * Show an error message if this the first time, and print status messages. - */ - private void exceptionOccurred(String message, Exception e) { - if (!consoleMessage) { - System.err.println(Messages.MirrorLog_Exception_Occurred); - e.printStackTrace(System.err); - System.err.println(Messages.MirrorLog_Console_Log); - consoleMessage = true; - } - if (message != null) - System.out.println(message); - } - - /** - * Copied from AntLogAdapter in pde build. - */ - private int mapLogLevels(int iStatusLevel) { - switch (iStatusLevel) { - case IStatus.ERROR : - return 0; - case IStatus.OK : - return 2; - case IStatus.INFO : - return 2; - case IStatus.WARNING : - return 1; - default : - return 1; - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/CreateCompositeArtifactRepositoryTask.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/CreateCompositeArtifactRepositoryTask.java deleted file mode 100644 index a86224e53..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/CreateCompositeArtifactRepositoryTask.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.artifact.repository.ant; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Task; -import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.p2.artifact.repository.Activator; -import org.eclipse.equinox.internal.p2.artifact.repository.CompositeArtifactRepository; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; - -/** - * Ant task for creating a new composite artifact repository. - */ -public class CreateCompositeArtifactRepositoryTask extends Task { - - URI location; // desired location of the composite repository - String name = "Composite Artifact Repository"; - boolean compressed = true; - boolean failOnExists = false; // should we fail if a repo already exists? - Map properties = new HashMap(); - - /* (non-Javadoc) - * @see org.apache.tools.ant.Task#execute() - */ - public void execute() { - validate(); - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); - if (manager == null) - throw new BuildException("Unable to aquire artifact repository manager service."); - - // remove the repo first. - manager.removeRepository(location); - - // first try and load to see if one already exists at that location. - // if we have an already existing repository at that location, then throw an error - // if the user told us to - try { - IArtifactRepository repository = manager.loadRepository(location, null); - if (repository instanceof CompositeArtifactRepository) { - if (failOnExists) - throw new BuildException("Composite repository already exists at location: " + location); - return; - } else { - // we have a non-composite repo at this location. that is ok because we can co-exist. - } - } catch (ProvisionException e) { - // re-throw the exception if we got anything other than "repo not found" - if (e.getStatus().getCode() != ProvisionException.REPOSITORY_NOT_FOUND) - throw new BuildException("Exception while trying to read repository at: " + location, e); - } - - // set the properties - if (compressed) - properties.put(IRepository.PROP_COMPRESSED, Boolean.toString(true)); - - // create the repository - try { - manager.createRepository(location, name, IArtifactRepositoryManager.TYPE_COMPOSITE_REPOSITORY, properties); - } catch (ProvisionException e) { - throw new BuildException("Error occurred while creating composite artifact repository.", e); - } - } - - /* - * Perform basic sanity checking of some of the parameters. - */ - private void validate() { - if (location == null) - throw new BuildException("Must specify repository location."); - if (name == null) - throw new BuildException("Must specify a repository name."); - } - - /* - * Set the name of the composite repository. - */ - public void setName(String value) { - name = value; - } - - /* - * Set the location of the repository. - */ - public void setLocation(String value) throws URISyntaxException { - location = URIUtil.fromString(value); - } - - /* - * Set a value indicating whether or not the repository should be compressed. - */ - public void setCompressed(boolean value) { - compressed = value; - } - - /* - * Set whether or not we should fail the operation if a repository - * already exists at the location. - */ - public void setFailOnExists(boolean value) { - failOnExists = value; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/MirrorApplicationTask.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/MirrorApplicationTask.java deleted file mode 100644 index 5040961cf..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/MirrorApplicationTask.java +++ /dev/null @@ -1,221 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.artifact.repository.ant; - -import java.io.File; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Task; -import org.eclipse.equinox.app.IApplicationContext; -import org.eclipse.equinox.internal.p2.artifact.mirror.MirrorApplication; -import org.osgi.framework.Bundle; - -/** - * Ant task for running the artifact repository mirroring application. - */ -public class MirrorApplicationTask extends Task { - - private static final String EMPTY_STRING = ""; //$NON-NLS-1$ - private static final String ARG_COMPARATOR = "-comparator"; //$NON-NLS-1$ - private static final String ARG_COMPARE = "-compare"; //$NON-NLS-1$ - private static final String ARG_COMPARE_AGAINST = "-compareAgainst"; //$NON-NLS-1$ - private static final String ARG_COMPARATOR_LOG = "-comparatorLog"; //$NON-NLS-1$ - private static final String ARG_DESTINATION = "-destination"; //$NON-NLS-1$ - private static final String ARG_DESTINATION_NAME = "-destinationName"; //$NON-NLS-1$ - private static final String ARG_IGNORE_ERRORS = "-ignoreErrors"; //$NON-NLS-1$ - private static final String ARG_LOG = "-log"; //$NON-NLS-1$ - private static final String ARG_RAW = "-raw"; //$NON-NLS-1$ - private static final String ARG_SOURCE = "-source"; //$NON-NLS-1$ - private static final String ARG_VERBOSE = "-verbose"; //$NON-NLS-1$ - private static final String ARG_WRITE_MODE = "-writeMode"; //$NON-NLS-1$ - - URL source; - URL destination; - String destinationName; - URL baseline; // location of known good repository for compare against (optional) - File mirrorLog; // file to log mirror output to (optional) - File comparatorLog; // file to comparator output to (optional) - String comparatorID; // specifies a comparator (optional) - String writeMode; - boolean compare = false; - boolean ignoreErrors = false; - boolean raw = false; // use raw artifact descriptors? - boolean verbose = false; - - /* - * Runs the mirror application with the given arguments. - */ - private void runMirrorApplication(final String[] args) throws Exception { - MirrorApplication app = new MirrorApplication(); - if (mirrorLog == null) - app.setLog(new AntMirrorLog(this)); - app.start(new IApplicationContext() { - - public void applicationRunning() { - // nothing to do - } - - public Map getArguments() { - Map arguments = new HashMap(); - arguments.put(IApplicationContext.APPLICATION_ARGS, args); - return arguments; - } - - public String getBrandingApplication() { - return null; - } - - public Bundle getBrandingBundle() { - return null; - } - - public String getBrandingDescription() { - return null; - } - - public String getBrandingId() { - return null; - } - - public String getBrandingName() { - return null; - } - - public String getBrandingProperty(String key) { - return null; - } - }); - } - - /* (non-Javadoc) - * @see org.apache.tools.ant.Task#execute() - */ - public void execute() { - // Compare against if baseline specified - boolean compareAgainst = baseline != null; - boolean comparator = comparatorID != null; - - // create arguments - String[] args = new String[] { // - ARG_SOURCE, source.toExternalForm(), // - ARG_DESTINATION, destination.toExternalForm(), // - ARG_WRITE_MODE, writeMode == null ? EMPTY_STRING : writeMode, // - compare ? ARG_COMPARE : EMPTY_STRING, // - ignoreErrors ? ARG_IGNORE_ERRORS : EMPTY_STRING, // - raw ? ARG_RAW : EMPTY_STRING, // - verbose ? ARG_VERBOSE : EMPTY_STRING, // - compareAgainst ? ARG_COMPARE_AGAINST : EMPTY_STRING, // - compareAgainst ? baseline.toExternalForm() : EMPTY_STRING, // - comparator ? ARG_COMPARATOR : EMPTY_STRING, // - comparator ? comparatorID : EMPTY_STRING, // - mirrorLog != null ? ARG_LOG : EMPTY_STRING, // - mirrorLog != null ? mirrorLog.getAbsolutePath() : EMPTY_STRING, // - comparatorLog != null ? ARG_COMPARATOR_LOG : EMPTY_STRING, // - comparatorLog != null ? comparatorLog.getAbsolutePath() : EMPTY_STRING, // - destinationName != null ? ARG_DESTINATION_NAME : EMPTY_STRING, // - destinationName != null ? destinationName : EMPTY_STRING}; - - try { - runMirrorApplication(args); - } catch (Exception e) { - throw new BuildException("Exception while running mirror application.", e); - } - } - - /* - * Set the location of the source. - */ - public void setSource(String value) throws MalformedURLException { - source = new URL(value); - } - - /* - * Set the location of the destination. - */ - public void setDestination(String value) throws MalformedURLException { - destination = new URL(value); - } - - /* - * Set the name of the destination repository. - */ - public void setDestinationName(String value) { - destinationName = value; - } - - /* - * Set the location of the baseline repository. (used in comparison) - */ - public void setBaseline(String value) throws MalformedURLException { - baseline = new URL(value); - compare = true; - } - - /* - * Set the identifier of the comparator to use. - */ - public void setComparatorID(String value) { - comparatorID = value; - compare = true; - } - - /* - * Set the location of the comparator log - */ - public void setComparatorLog(String value) { - comparatorLog = new File(value); - } - - /* - * Set the write mode. (e.g. clean or append) - */ - public void setWriteMode(String value) { - writeMode = value; - } - - /* - * Set the log location if applicable - */ - public void setLog(String value) { - mirrorLog = new File(value); - } - - /* - * Set whether or not the application should be calling a comparator when mirroring. - */ - public void setCompare(boolean value) { - compare = value; - } - - /* - * Set whether or not we should ignore errors when running the mirror application. - */ - public void setIgnoreErrors(boolean value) { - ignoreErrors = value; - } - - /* - * Set whether or not the the artifacts are raw. - */ - public void setRaw(boolean value) { - raw = value; - } - - /* - * Set whether or not the mirror application should be run in verbose mode. - */ - public void setVerbose(boolean value) { - verbose = value; - } -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/RemoveChildTask.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/RemoveChildTask.java deleted file mode 100644 index 2a1212660..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/RemoveChildTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.artifact.repository.ant; - -import java.net.URI; -import java.net.URISyntaxException; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Task; -import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.p2.artifact.repository.Activator; -import org.eclipse.equinox.internal.p2.artifact.repository.CompositeArtifactRepository; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; - -/** - * Ant task for removing a specific child from a composite artifact repository. - */ -public class RemoveChildTask extends Task { - - URI location; // location of the composite repository - URI child; // location of child to remove - boolean allChildren = false; // should we remove all children? - - /* (non-Javadoc) - * @see org.apache.tools.ant.Task#execute() - */ - public void execute() { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); - if (manager == null) - throw new BuildException("Unable to aquire artifact repository manager service."); - - // load repository - CompositeArtifactRepository repo; - try { - repo = (CompositeArtifactRepository) manager.loadRepository(location, null); - } catch (ProvisionException e) { - throw new BuildException("Error occurred while loading repository.", e); - } - - // remove all children or just a specified child - if (allChildren) - repo.removeAllChildren(); - else - repo.removeChild(child); - } - - /* - * Set the repository location. - */ - public void setLocation(String value) throws URISyntaxException { - location = URIUtil.fromString(value); - } - - /* - * Set the child repository location. - */ - public void setChild(String value) throws URISyntaxException { - child = URIUtil.fromString(value); - } - - /* - * Set whether or not we want to remove all the children. - */ - public void setAllChildren(String value) { - allChildren = Boolean.valueOf(value).booleanValue(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/ValidateTask.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/ValidateTask.java deleted file mode 100644 index 96a4d3a7e..000000000 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src_ant/org/eclipse/equinox/internal/p2/artifact/repository/ant/ValidateTask.java +++ /dev/null @@ -1,68 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.artifact.repository.ant; - -import java.net.URI; -import java.net.URISyntaxException; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Task; -import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.p2.artifact.repository.Activator; -import org.eclipse.equinox.internal.p2.artifact.repository.CompositeArtifactRepository; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; - -/** - * Ant task for validating the contents of a composite artifact repository. - */ -public class ValidateTask extends Task { - - URI location; // location of the composite repository - String comparatorID; // specifies the comparator we want to use. - - /* (non-Javadoc) - * @see org.apache.tools.ant.Task#execute() - */ - public void execute() { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); - if (manager == null) - throw new BuildException("Unable to aquire artifact repository manager service."); - - // load the repository - CompositeArtifactRepository repo = null; - try { - repo = (CompositeArtifactRepository) manager.loadRepository(location, null); - } catch (ProvisionException e) { - throw new BuildException("Exception while loading repository.", e); - } - - // perform the sanity check - if (repo.validate(comparatorID)) - System.err.println("Valid repository at: " + location); - else - System.err.println("Invalid repository at: " + location); - } - - /* - * Set the repository location. - */ - public void setLocation(String value) throws URISyntaxException { - location = URIUtil.fromString(value); - } - - /* - * Set the ID of the comparator. - */ - public void setComparatorID(String value) { - comparatorID = value; - } -} diff --git a/bundles/org.eclipse.equinox.p2.console/.classpath b/bundles/org.eclipse.equinox.p2.console/.classpath index 7cdeb7319..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.console/.classpath +++ b/bundles/org.eclipse.equinox.p2.console/.classpath @@ -1,7 +1,7 @@ - - + + diff --git a/bundles/org.eclipse.equinox.p2.console/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.console/.settings/org.eclipse.jdt.core.prefs index a455b6228..dd9ddfffa 100644 --- a/bundles/org.eclipse.equinox.p2.console/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.console/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Thu Sep 13 22:02:41 EDT 2007 +#Mon Dec 28 17:08:33 CET 2009 eclipse.preferences.version=1 instance/org.eclipse.core.net/org.eclipse.core.net.hasMigrated=true org.eclipse.jdt.core.builder.cleanOutputFolder=clean @@ -8,24 +8,24 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=warning @@ -81,7 +81,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=en org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 @@ -153,7 +153,6 @@ org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert diff --git a/bundles/org.eclipse.equinox.p2.console/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.console/META-INF/MANIFEST.MF index ad704999f..46f109c5d 100644 --- a/bundles/org.eclipse.equinox.p2.console/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.console/META-INF/MANIFEST.MF @@ -7,20 +7,23 @@ Bundle-Localization: plugin Bundle-Version: 1.0.100.qualifier Bundle-Activator: org.eclipse.equinox.internal.p2.console.Activator Bundle-ActivationPolicy: lazy -Export-Package: org.eclipse.equinox.internal.p2.console;x-friends:="org.eclipse.equinox.p2.director.app,org.eclipse.equinox.p2.tools" +Export-Package: org.eclipse.equinox.internal.p2.console;x-friends:="org.eclipse.equinox.p2.director.app" Import-Package: org.eclipse.core.runtime;common=split, org.eclipse.equinox.internal.p2.core.helpers, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, - org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.director, - org.eclipse.equinox.internal.provisional.p2.engine, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.p2.repository, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.metadata, org.eclipse.osgi.framework.console;version="1.0.0";resolution:=optional, org.eclipse.osgi.service.environment;version="1.0.0", org.osgi.framework;version="1.4.0", org.osgi.util.tracker;version="1.3.0" -Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, - J2SE-1.4 +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 diff --git a/bundles/org.eclipse.equinox.p2.console/build.properties b/bundles/org.eclipse.equinox.p2.console/build.properties index a6b8330d2..246ea6cb7 100644 --- a/bundles/org.eclipse.equinox.p2.console/build.properties +++ b/bundles/org.eclipse.equinox.p2.console/build.properties @@ -15,3 +15,5 @@ bin.includes = META-INF/,\ about.html,\ plugin.properties src.includes = about.html +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.console/src/org/eclipse/equinox/internal/p2/console/Activator.java b/bundles/org.eclipse.equinox.p2.console/src/org/eclipse/equinox/internal/p2/console/Activator.java index 78398a0b0..42a465ee1 100644 --- a/bundles/org.eclipse.equinox.p2.console/src/org/eclipse/equinox/internal/p2/console/Activator.java +++ b/bundles/org.eclipse.equinox.p2.console/src/org/eclipse/equinox/internal/p2/console/Activator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2008, 2009, IBM Corporation and others. All rights reserved. This * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,10 +7,11 @@ * * Contributors: * IBM Corporation - initial API and implementation + * Composent, Inc. - additions *******************************************************************************/ package org.eclipse.equinox.internal.p2.console; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.engine.IProfileRegistry; import org.osgi.framework.*; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; @@ -33,8 +34,8 @@ public class Activator implements BundleActivator, ServiceTrackerCustomizer { super(); } - public void start(BundleContext context) throws Exception { - Activator.context = context; + public void start(BundleContext ctxt) throws Exception { + Activator.context = ctxt; boolean registerCommands = true; try { Class.forName(PROVIDER_NAME); @@ -43,12 +44,12 @@ public class Activator implements BundleActivator, ServiceTrackerCustomizer { } if (registerCommands) { - profileTracker = new ServiceTracker(context, IProfileRegistry.class.getName(), this); + profileTracker = new ServiceTracker(context, IProfileRegistry.SERVICE_NAME, this); profileTracker.open(); } } - public void stop(BundleContext context) throws Exception { + public void stop(BundleContext ctxt) throws Exception { profileTracker.close(); if (providerRegistration != null) providerRegistration.unregister(); @@ -57,15 +58,15 @@ public class Activator implements BundleActivator, ServiceTrackerCustomizer { } public Object addingService(ServiceReference reference) { - BundleContext context = Activator.getContext(); - IProfileRegistry registry = (IProfileRegistry) context.getService(reference); - provider = new ProvCommandProvider(context.getProperty("eclipse.p2.profile"), registry); - providerRegistration = context.registerService(PROVIDER_NAME, provider, null); + BundleContext ctxt = Activator.getContext(); + IProfileRegistry registry = (IProfileRegistry) ctxt.getService(reference); + provider = new ProvCommandProvider(ctxt.getProperty("eclipse.p2.profile"), registry); //$NON-NLS-1$ + providerRegistration = ctxt.registerService(PROVIDER_NAME, provider, null); return registry; } public void modifiedService(ServiceReference reference, Object service) { - // TODO Auto-generated method stub + // nothing } public void removedService(ServiceReference reference, Object service) { diff --git a/bundles/org.eclipse.equinox.p2.console/src/org/eclipse/equinox/internal/p2/console/ProvCommandProvider.java b/bundles/org.eclipse.equinox.p2.console/src/org/eclipse/equinox/internal/p2/console/ProvCommandProvider.java index 54b137b8a..83bb98ad9 100644 --- a/bundles/org.eclipse.equinox.p2.console/src/org/eclipse/equinox/internal/p2/console/ProvCommandProvider.java +++ b/bundles/org.eclipse.equinox.p2.console/src/org/eclipse/equinox/internal/p2/console/ProvCommandProvider.java @@ -1,15 +1,17 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. All rights reserved. This + * Copyright (c) 2007, 2008, 2009 IBM Corporation and others. All rights reserved. This * program and the accompanying materials are made available under the terms of * the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: IBM Corporation - initial API and implementation * Band XI - add more commands + * Composent, Inc. - command additions ******************************************************************************/ package org.eclipse.equinox.internal.p2.console; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.io.File; import java.net.URI; @@ -18,14 +20,17 @@ import java.util.*; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.GroupQuery; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.framework.console.CommandInterpreter; import org.eclipse.osgi.framework.console.CommandProvider; @@ -55,60 +60,90 @@ public class ProvCommandProvider implements CommandProvider { } /** - * Adds a metadata repository. + * Adds both a metadata repository and artifact repository */ public void _provaddrepo(CommandInterpreter interpreter) { String urlString = interpreter.nextArgument(); if (urlString == null) { - interpreter.print("Repository location must be provided"); - interpreter.println(); + interpreter.println("Repository location must be provided"); return; } - URI repoURL = toURI(interpreter, urlString); - if (repoURL == null) + URI repoURI = toURI(interpreter, urlString); + if (repoURI == null) return; - if (ProvisioningHelper.addMetadataRepository(repoURL) == null) - interpreter.println("Unable to add repository: " + repoURL); + // add metadata repo + if (ProvisioningHelper.addMetadataRepository(repoURI) == null) { + interpreter.println("Unable to add metadata repository: " + repoURI); + } else // add artifact repo at same URL + if (ProvisioningHelper.addArtifactRepository(repoURI) == null) { + interpreter.println("Unable to add artifact repository: " + repoURI); + } } public void _provdelrepo(CommandInterpreter interpreter) { String urlString = interpreter.nextArgument(); if (urlString == null) { - interpreter.print("Repository location must be provided"); - interpreter.println(); + interpreter.println("Repository location must be provided"); return; } - URI repoURL = toURI(interpreter, urlString); - if (repoURL == null) + URI repoURI = toURI(interpreter, urlString); + if (repoURI == null) + return; + ProvisioningHelper.removeMetadataRepository(repoURI); + ProvisioningHelper.removeArtifactRepository(repoURI); + } + + /** + * Adds a metadata repository. + */ + public void _provaddmetadatarepo(CommandInterpreter interpreter) { + String urlString = interpreter.nextArgument(); + if (urlString == null) { + interpreter.println("Repository location must be provided"); + return; + } + URI repoURI = toURI(interpreter, urlString); + if (repoURI == null) return; - ProvisioningHelper.removeMetadataRepository(repoURL); + if (ProvisioningHelper.addMetadataRepository(repoURI) == null) + interpreter.println("Unable to add repository: " + repoURI); + } + + public void _provdelmetadatarepo(CommandInterpreter interpreter) { + String urlString = interpreter.nextArgument(); + if (urlString == null) { + interpreter.println("Repository location must be provided"); + return; + } + URI repoURI = toURI(interpreter, urlString); + if (repoURI == null) + return; + ProvisioningHelper.removeMetadataRepository(repoURI); } public void _provaddartifactrepo(CommandInterpreter interpreter) { String urlString = interpreter.nextArgument(); if (urlString == null) { - interpreter.print("Repository location must be provided"); - interpreter.println(); + interpreter.println("Repository location must be provided"); return; } - URI repoURL = toURI(interpreter, urlString); - if (repoURL == null) + URI repoURI = toURI(interpreter, urlString); + if (repoURI == null) return; - if (ProvisioningHelper.addArtifactRepository(repoURL) == null) - interpreter.println("Unable to add repository: " + repoURL); + if (ProvisioningHelper.addArtifactRepository(repoURI) == null) + interpreter.println("Unable to add repository " + repoURI); } public void _provdelartifactrepo(CommandInterpreter interpreter) { String urlString = interpreter.nextArgument(); if (urlString == null) { - interpreter.print("Repository location must be provided"); - interpreter.println(); + interpreter.println("Repository location must be provided"); return; } - URI repoURL = toURI(interpreter, urlString); - if (repoURL == null) + URI repoURI = toURI(interpreter, urlString); + if (repoURI == null) return; - ProvisioningHelper.removeArtifactRepository(repoURL); + ProvisioningHelper.removeArtifactRepository(repoURI); } /** @@ -118,24 +153,26 @@ public class ProvCommandProvider implements CommandProvider { String iu = interpreter.nextArgument(); String version = interpreter.nextArgument(); String profileId = interpreter.nextArgument(); - if (profileId == null || profileId.equals("this")) + if (profileId == null || profileId.equals("this")) //$NON-NLS-1$ profileId = IProfileRegistry.SELF; if (iu == null || version == null || profileId == null) { - interpreter.println("Installable unit id, version, and profile Id must be provided"); + interpreter.println("Installable unit id, version, and profileid must be provided"); return; } IStatus s = null; try { s = ProvisioningHelper.install(iu, version, ProvisioningHelper.getProfile(profileId), new NullProgressMonitor()); } catch (ProvisionException e) { - interpreter.println("installation failed "); - e.printStackTrace(); + interpreter.println("Installation failed with ProvisionException for " + iu + " " + version); + interpreter.printStackTrace(e); return; } if (s.isOK()) - interpreter.println("installation complete"); - else - interpreter.println("installation failed " + s.getMessage()); + interpreter.println("Installation complete for " + iu + " " + version); + else { + interpreter.println("Installation failed for " + iu + " " + version); + printErrorStatus(interpreter, s); + } } /** @@ -150,16 +187,16 @@ public class ProvCommandProvider implements CommandProvider { return; } String environments = interpreter.nextArgument(); - Properties props = new Properties(); - props.setProperty(IProfile.PROP_INSTALL_FOLDER, location); - props.setProperty(IProfile.PROP_FLAVOR, flavor); + Map props = new HashMap(); + props.put(IProfile.PROP_INSTALL_FOLDER, location); if (environments != null) - props.setProperty(IProfile.PROP_ENVIRONMENTS, environments); + props.put(IProfile.PROP_ENVIRONMENTS, environments); try { ProvisioningHelper.addProfile(profileId, props); } catch (ProvisionException e) { - interpreter.println("add profile failed " + e.getMessage()); + interpreter.println("Add profile failed. " + e.getMessage()); + interpreter.printStackTrace(e); } } @@ -169,7 +206,7 @@ public class ProvCommandProvider implements CommandProvider { public void _provdelprofile(CommandInterpreter interpreter) { String profileId = interpreter.nextArgument(); if (profileId == null) { - interpreter.println("Id must be provided"); + interpreter.println("profileid must be provided"); return; } ProvisioningHelper.removeProfile(profileId); @@ -225,9 +262,9 @@ public class ProvCommandProvider implements CommandProvider { */ public void _provlg(CommandInterpreter interpreter) { String urlString = processArgument(interpreter.nextArgument()); - IQueryable queryable = null; + IQueryable queryable = null; if (urlString == null) { - queryable = (IQueryable) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + queryable = (IQueryable) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); if (queryable == null) return; } else { @@ -238,8 +275,7 @@ public class ProvCommandProvider implements CommandProvider { if (queryable == null) return; } - Query query = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_GROUP, Boolean.TRUE.toString()); - IInstallableUnit[] units = sort(queryable.query(query, new Collector(), null)); + IInstallableUnit[] units = sort(queryable.query(new GroupQuery(), null)); for (int i = 0; i < units.length; i++) println(interpreter, units[i]); } @@ -264,26 +300,27 @@ public class ProvCommandProvider implements CommandProvider { if (repoURL == null) return; IArtifactRepository repo = ProvisioningHelper.getArtifactRepository(repoURL); - IArtifactKey[] keys = null; + IQueryResult keys = null; try { - keys = (repo != null) ? repo.getArtifactKeys() : null; + keys = (repo != null) ? repo.query(ArtifactKeyQuery.ALL_KEYS, null) : null; } catch (UnsupportedOperationException e) { - interpreter.println("Repository does not support list commands."); + interpreter.println("Repository does not support queries."); return; } - if (keys == null || keys.length == 0) { + if (keys == null || keys.isEmpty()) { interpreter.println("Repository has no artifacts"); return; } IFileArtifactRepository fileRepo = (IFileArtifactRepository) repo.getAdapter(IFileArtifactRepository.class); - for (int i = 0; i < keys.length; i++) { - IArtifactDescriptor[] descriptors = repo.getArtifactDescriptors(keys[i]); + for (Iterator iterator = keys.iterator(); iterator.hasNext();) { + IArtifactKey key = iterator.next(); + IArtifactDescriptor[] descriptors = repo.getArtifactDescriptors(key); for (int j = 0; j < descriptors.length; j++) { IArtifactDescriptor descriptor = descriptors[j]; File location = null; if (fileRepo != null) location = fileRepo.getArtifactFile(descriptor); - println(interpreter, keys[i], location); + println(interpreter, key, location); } } @@ -326,53 +363,238 @@ public class ProvCommandProvider implements CommandProvider { } // determine which profile is to be listed IProfile target = null; - if (profileId.equals("this")) + if (profileId.equals("this")) //$NON-NLS-1$ profileId = IProfileRegistry.SELF; target = ProvisioningHelper.getProfile(profileId); if (target == null) return; // list the profile contents - IInstallableUnit[] result = sort(target.query(new InstallableUnitQuery(id, new VersionRange(range)), new Collector(), null)); + IInstallableUnit[] result = sort(target.query(new InstallableUnitQuery(id, new VersionRange(range)), null)); for (int i = 0; i < result.length; i++) interpreter.println(result[i]); } - private IInstallableUnit[] sort(Collector collector) { - IInstallableUnit[] units = (IInstallableUnit[]) collector.toArray(IInstallableUnit.class); - Arrays.sort(units, new Comparator() { - public int compare(Object arg0, Object arg1) { + /** + * Lists the profile timestamps for a given profile id, if no profile id, the default profile + * is used. + * + * @param interpreter + */ + public void _provlpts(CommandInterpreter interpreter) { + String profileId = processArgument(interpreter.nextArgument()); + if (profileId == null || profileId.equals("this")) { //$NON-NLS-1$ + profileId = IProfileRegistry.SELF; + } + long[] profileTimestamps = ProvisioningHelper.getProfileTimestamps(profileId); + // if no profile timestamps for given id, print that out and done + if (profileTimestamps == null || profileTimestamps.length == 0) { + interpreter.print("No timestamps found for profile "); + interpreter.println(profileId); + return; + } + // else if there are some timestamps then print them out on separate line + interpreter.print("Timestamps for profile "); + interpreter.println(profileId); + for (int i = 0; i < profileTimestamps.length; i++) { + interpreter.print("\t"); //$NON-NLS-1$ + interpreter.println(new Long(profileTimestamps[i])); + } + } + + /** + * Revert a profile to a given timestamp + */ + public void _provrevert(CommandInterpreter interpreter) { + String timestamp = interpreter.nextArgument(); + if (timestamp == null) { + interpreter.println("Valid timestamp must be provided. Timestamps can be retrieved via 'provlpts' command."); + return; + } + Long ts = null; + try { + ts = new Long(timestamp); + } catch (NumberFormatException e) { + interpreter.println("Timestamp " + timestamp + " not valid. Timestamps can be retrieved via 'provlpts' command."); + return; + } + String profileId = interpreter.nextArgument(); + if (profileId == null || profileId.equals("this")) + profileId = IProfileRegistry.SELF; + + IProfile profile = ProvisioningHelper.getProfile(profileId); + if (profile == null) { + interpreter.println("Profile " + profileId + " not found"); + return; + } + IStatus s = null; + try { + s = ProvisioningHelper.revertToPreviousState(profile, ts.longValue()); + } catch (ProvisionException e) { + interpreter.println("revert failed "); + interpreter.printStackTrace(e); + return; + } + if (s.isOK()) + interpreter.println("revert completed"); + else { + interpreter.println("revert failed "); + printErrorStatus(interpreter, s); + } + } + + private IInstallableUnit[] sort(IQueryResult queryResult) { + IInstallableUnit[] units = queryResult.toArray(IInstallableUnit.class); + Arrays.sort(units, new Comparator() { + public int compare(IInstallableUnit arg0, IInstallableUnit arg1) { return arg0.toString().compareTo(arg1.toString()); } }); return units; } + public void _provlgp(CommandInterpreter interpreter) { + String profileId = processArgument(interpreter.nextArgument()); + if (profileId == null || profileId.equals("this")) { + profileId = IProfileRegistry.SELF; + } + IProfile profile = ProvisioningHelper.getProfile(profileId); + if (profile == null) { + interpreter.println("Profile " + profileId + " not found"); + return; + } + IInstallableUnit[] units = sort(profile.query(new GroupQuery(), new NullProgressMonitor())); + // Now print out results + for (int i = 0; i < units.length; i++) + println(interpreter, units[i]); + + } + + public void _provremove(CommandInterpreter interpreter) { + String iu = interpreter.nextArgument(); + String version = interpreter.nextArgument(); + String profileId = interpreter.nextArgument(); + if (profileId == null || profileId.equals("this")) + profileId = IProfileRegistry.SELF; + if (version == null) { + version = Version.emptyVersion.toString(); + } + if (iu == null) { + interpreter.println("Installable unit id must be provided"); + return; + } + IStatus s = null; + try { + s = ProvisioningHelper.uninstall(iu, version, ProvisioningHelper.getProfile(profileId), new NullProgressMonitor()); + } catch (ProvisionException e) { + interpreter.println("Remove failed with ProvisionException for " + iu + " " + version); + interpreter.printStackTrace(e); + return; + } + if (s.isOK()) + interpreter.println("Remove complete for " + iu + " " + version); + else { + interpreter.println("Remove failed for " + iu + " " + version); + printErrorStatus(interpreter, s); + } + } + + private void printErrorStatus(CommandInterpreter interpreter, IStatus status) { + interpreter.print("--Error status "); + interpreter.print("message=" + status.getMessage()); + interpreter.print(",code=" + status.getCode()); + String severityString = null; + switch (status.getSeverity()) { + case IStatus.INFO : + severityString = "INFO"; + break; + case IStatus.CANCEL : + severityString = "CANCEL"; + break; + case IStatus.WARNING : + severityString = "WARNING"; + break; + case IStatus.ERROR : + severityString = "ERROR"; + break; + } + interpreter.print(",severity=" + severityString); + interpreter.print(",bundle=" + status.getPlugin()); + interpreter.println("--"); + Throwable t = status.getException(); + if (t != null) + interpreter.printStackTrace(t); + IStatus[] children = status.getChildren(); + if (children != null && children.length > 0) { + interpreter.println("Error status children:"); + for (int i = 0; i < children.length; i++) { + printErrorStatus(interpreter, children[i]); + } + } + interpreter.println("--End Error Status--"); + } + public String getHelp() { StringBuffer help = new StringBuffer(); help.append(NEW_LINE); - help.append("---"); //$NON-NLS-1$ - help.append("Provisioning Commands"); - help.append("---"); //$NON-NLS-1$ + help.append("---"); + help.append("P2 Provisioning Commands"); + help.append("---"); help.append(NEW_LINE); - help.append("\tprovlr [ ] - Lists all metadata repositories, or the contents of a given metadata repository"); + + help.append("---"); + help.append("Repository Commands"); + help.append("---"); help.append(NEW_LINE); - help.append("\tprovlar [] - Lists all artifact repositories, or the contents of a given artifact repository"); + help.append("\tprovaddrepo - Adds a both a metadata and artifact repository at URI"); help.append(NEW_LINE); - help.append("\tprovliu [ ] - Lists the IUs that match the pattern in the given repo. * matches all"); + help.append("\tprovdelrepo - Deletes a metadata and artifact repository at URI"); help.append(NEW_LINE); - help.append("\tprovlp [ - Lists all profiles, or the contents of the profile at the given profile"); + help.append("\tprovaddmetadatarepo - Adds a metadata repository at URI"); help.append(NEW_LINE); - help.append("\tprovlg [ ] - Lists all IUs with group capabilities in the given repo or in all repos if the URL is omitted"); + help.append("\tprovdelmetadatarepo - Deletes a metadata repository at URI"); help.append(NEW_LINE); - help.append("\tprovinstall - Provisions an IU to the profile with the give id"); + help.append("\tprovaddartifactrepo - Adds an artifact repository at URI"); help.append(NEW_LINE); - help.append("\tprovaddrepo - Adds a metadata repository"); + help.append("\tprovdelartifactrepo - Deletes an artifact repository URI"); help.append(NEW_LINE); - help.append("\tprovaddartifactrepo - Adds an artifact repository"); + help.append("\tprovlg [ ] - Lists all IUs with group capabilities in the given repo or in all repos if URI is omitted"); help.append(NEW_LINE); - help.append("\tprovaddprofile - Adds a profile with the given id, location and flavor"); + help.append("\tprovlr [ ] - Lists all metadata repositories, or the contents of a given metadata repository"); help.append(NEW_LINE); + help.append("\tprovlar [] - Lists all artifact repositories, or the contents of a given artifact repository"); + help.append(NEW_LINE); + help.append("\tprovliu [ ] - Lists the IUs that match the pattern in the given repo. * matches all"); + help.append(NEW_LINE); + + help.append("---"); + help.append("Profile Registry Commands"); + help.append("---"); + help.append(NEW_LINE); + + help.append("\tprovaddprofile - Adds a profile with the given profileid, location and flavor"); + help.append(NEW_LINE); + help.append("\tprovdelprofile - Deletes a profile with the given profileid"); + help.append(NEW_LINE); + help.append("\tprovlp [] - Lists all profiles, or the contents of the profile at the given profile"); + help.append(NEW_LINE); + help.append("\tprovlgp [] - Lists all IUs with group capabilities in the given profile, or current profile if profileid is omitted"); + help.append(NEW_LINE); + help.append("\tprovlpts [] - Lists timestamps for given profile, or if no profileid given then the default profile timestamps are reported"); + help.append(NEW_LINE); + + help.append("---"); + help.append("Install Commands"); + help.append("---"); + help.append(NEW_LINE); + + help.append("\tprovinstall - installs an IU to the profileid. If no profileid is given, installs into default profile."); + help.append(NEW_LINE); + help.append("\tprovremove - Removes an IU from the profileid. If no profileid is given, installs into default profile."); + help.append(NEW_LINE); + help.append("\tprovrevert ] - Reverts to a given profileTimestamp for an optional profileId"); + help.append(NEW_LINE); + return help.toString(); } diff --git a/bundles/org.eclipse.equinox.p2.console/src/org/eclipse/equinox/internal/p2/console/ProvisioningHelper.java b/bundles/org.eclipse.equinox.p2.console/src/org/eclipse/equinox/internal/p2/console/ProvisioningHelper.java index 730e04c8c..02d9e1091 100644 --- a/bundles/org.eclipse.equinox.p2.console/src/org/eclipse/equinox/internal/p2/console/ProvisioningHelper.java +++ b/bundles/org.eclipse.equinox.p2.console/src/org/eclipse/equinox/internal/p2/console/ProvisioningHelper.java @@ -10,31 +10,32 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.console; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.net.URI; -import java.util.*; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; +import java.util.HashMap; +import java.util.Map; +import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.service.environment.EnvironmentInfo; public class ProvisioningHelper { public static IMetadataRepository addMetadataRepository(URI location) { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); if (manager == null) - throw new IllegalStateException("No metadata repository manager found"); //$NON-NLS-1$ + throw new IllegalStateException("No metadata repository manager found"); try { return manager.loadRepository(location, null); } catch (ProvisionException e) { @@ -42,7 +43,7 @@ public class ProvisioningHelper { } // for convenience create and add a repository here - String repositoryName = location + " - metadata"; //$NON-NLS-1$ + String repositoryName = location + " - metadata"; try { return manager.createRepository(location, repositoryName, IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, null); } catch (ProvisionException e) { @@ -51,7 +52,7 @@ public class ProvisioningHelper { } public static IMetadataRepository getMetadataRepository(URI location) { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); if (manager == null) throw new IllegalStateException("No metadata repository manager found"); try { @@ -62,14 +63,14 @@ public class ProvisioningHelper { } public static void removeMetadataRepository(URI location) { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); if (manager == null) throw new IllegalStateException("No metadata repository manager found"); manager.removeRepository(location); } public static IArtifactRepository addArtifactRepository(URI location) { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); + IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); if (manager == null) // TODO log here return null; @@ -79,7 +80,7 @@ public class ProvisioningHelper { //fall through and create a new repository } // could not load a repo at that location so create one as a convenience - String repositoryName = location + " - artifacts"; //$NON-NLS-1$ + String repositoryName = location + " - artifacts"; try { return manager.createRepository(location, repositoryName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, null); } catch (ProvisionException e) { @@ -88,32 +89,26 @@ public class ProvisioningHelper { } public static void removeArtifactRepository(URI location) { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); + IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); if (manager == null) // TODO log here return; manager.removeRepository(location); } - public static IProfile addProfile(String profileId, Properties properties) throws ProvisionException { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(Activator.getContext(), IProfileRegistry.class.getName()); + public static IProfile addProfile(String profileId, Map properties) throws ProvisionException { + IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(Activator.getContext(), IProfileRegistry.SERVICE_NAME); if (profileRegistry == null) return null; IProfile profile = profileRegistry.getProfile(profileId); if (profile != null) return profile; - Map profileProperties = new HashMap(); - - for (Iterator it = properties.keySet().iterator(); it.hasNext();) { - String key = (String) it.next(); - profileProperties.put(key, properties.getProperty(key)); - } - + Map profileProperties = new HashMap(properties); if (profileProperties.get(IProfile.PROP_ENVIRONMENTS) == null) { EnvironmentInfo info = (EnvironmentInfo) ServiceHelper.getService(Activator.getContext(), EnvironmentInfo.class.getName()); if (info != null) - profileProperties.put(IProfile.PROP_ENVIRONMENTS, "osgi.os=" + info.getOS() + ",osgi.ws=" + info.getWS() + ",osgi.arch=" + info.getOSArch()); + profileProperties.put(IProfile.PROP_ENVIRONMENTS, "osgi.os=" + info.getOS() + ",osgi.ws=" + info.getWS() + ",osgi.arch=" + info.getOSArch()); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ else profileProperties.put(IProfile.PROP_ENVIRONMENTS, ""); } @@ -122,21 +117,21 @@ public class ProvisioningHelper { } public static void removeProfile(String profileId) { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(Activator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(Activator.getContext(), IProfileRegistry.SERVICE_NAME); if (profileRegistry == null) return; profileRegistry.removeProfile(profileId); } public static IProfile[] getProfiles() { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(Activator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(Activator.getContext(), IProfileRegistry.SERVICE_NAME); if (profileRegistry == null) return new IProfile[0]; return profileRegistry.getProfiles(); } public static IProfile getProfile(String id) { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(Activator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(Activator.getContext(), IProfileRegistry.SERVICE_NAME); if (profileRegistry == null) return null; return profileRegistry.getProfile(id); @@ -152,24 +147,20 @@ public class ProvisioningHelper { * @param monitor A progress monitor, or null * @return The IUs that match the query */ - public static Collector getInstallableUnits(URI location, Query query, IProgressMonitor monitor) { - return getInstallableUnits(location, query, new Collector(), monitor); - } - - public static Collector getInstallableUnits(URI location, Query query, Collector collector, IProgressMonitor monitor) { - IQueryable queryable = null; + public static IQueryResult getInstallableUnits(URI location, IQuery query, IProgressMonitor monitor) { + IQueryable queryable = null; if (location == null) { - queryable = (IQueryable) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + queryable = (IQueryable) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); } else { queryable = getMetadataRepository(location); } if (queryable != null) - return queryable.query(query, collector, monitor); - return collector; + return queryable.query(query, monitor); + return Collector.emptyCollector(); } public static URI[] getMetadataRepositories() { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); if (manager == null) // TODO log here return null; @@ -185,7 +176,7 @@ public class ProvisioningHelper { public static IStatus install(String unitId, String version, IProfile profile, IProgressMonitor progress) throws ProvisionException { if (profile == null) return null; - Collector units = getInstallableUnits(null, new InstallableUnitQuery(unitId, new Version(version)), progress); + IQueryResult units = getInstallableUnits((URI) null, new InstallableUnitQuery(unitId, Version.create(version)), progress); if (units.isEmpty()) { StringBuffer error = new StringBuffer(); error.append("Installable unit not found: " + unitId + ' ' + version + '\n'); @@ -198,23 +189,22 @@ public class ProvisioningHelper { throw new ProvisionException(error.toString()); } - IPlanner planner = (IPlanner) ServiceHelper.getService(Activator.getContext(), IPlanner.class.getName()); + IPlanner planner = (IPlanner) ServiceHelper.getService(Activator.getContext(), IPlanner.SERVICE_NAME); if (planner == null) throw new ProvisionException("No planner service found."); IEngine engine = (IEngine) ServiceHelper.getService(Activator.getContext(), IEngine.SERVICE_NAME); if (engine == null) throw new ProvisionException("No director service found."); - IInstallableUnit[] toInstall = (IInstallableUnit[]) units.toArray(IInstallableUnit.class); ProvisioningContext context = new ProvisioningContext(); ProfileChangeRequest request = new ProfileChangeRequest(profile); - request.addInstallableUnits(toInstall); - ProvisioningPlan result = planner.getProvisioningPlan(request, context, progress); + request.addInstallableUnits(units); + IProvisioningPlan result = planner.getProvisioningPlan(request, context, progress); return PlanExecutionHelper.executePlan(result, engine, context, progress); } public static URI[] getArtifactRepositories() { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); + IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); if (manager == null) // TODO log here return null; @@ -225,7 +215,7 @@ public class ProvisioningHelper { } public static IArtifactRepository getArtifactRepository(URI repoURL) { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); + IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); try { if (manager != null) return manager.loadRepository(repoURL, null); @@ -234,4 +224,82 @@ public class ProvisioningHelper { } return null; } + + public static long[] getProfileTimestamps(String profileId) { + if (profileId == null) { + profileId = IProfileRegistry.SELF; + } + IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(Activator.getContext(), IProfileRegistry.SERVICE_NAME); + if (profileRegistry == null) + return null; + return profileRegistry.listProfileTimestamps(profileId); + } + + public static IStatus revertToPreviousState(IProfile profile, long revertToPreviousState) throws ProvisionException { + IEngine engine = (IEngine) ServiceHelper.getService(Activator.getContext(), IEngine.SERVICE_NAME); + if (engine == null) + throw new ProvisionException("No p2 engine found."); + IPlanner planner = (IPlanner) ServiceHelper.getService(Activator.getContext(), IPlanner.SERVICE_NAME); + if (planner == null) + throw new ProvisionException("No planner found."); + IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(Activator.getContext(), IProfileRegistry.SERVICE_NAME); + if (profileRegistry == null) + throw new ProvisionException("profile registry cannot be null"); + // If given profile is null, then get/use the self profile + if (profile == null) { + profile = getProfile(IProfileRegistry.SELF); + } + IProfile targetProfile = null; + if (revertToPreviousState == 0) { + long[] profiles = profileRegistry.listProfileTimestamps(profile.getProfileId()); + if (profiles.length == 0) + // Nothing to do, as the profile does not have any previous timestamps + return Status.OK_STATUS; + targetProfile = profileRegistry.getProfile(profile.getProfileId(), profiles[profiles.length - 1]); + } else { + targetProfile = profileRegistry.getProfile(profile.getProfileId(), revertToPreviousState); + } + if (targetProfile == null) + throw new ProvisionException("target profile with timestamp=" + revertToPreviousState + " not found"); + URI[] artifactRepos = getArtifactRepositories(); + URI[] metadataRepos = getMetadataRepositories(); + IProvisioningPlan plan = planner.getDiffPlan(profile, targetProfile, new NullProgressMonitor()); + ProvisioningContext context = new ProvisioningContext(metadataRepos); + context.setArtifactRepositories(artifactRepos); + return PlanExecutionHelper.executePlan(plan, engine, context, new NullProgressMonitor()); + } + + /** + * Install the described IU + */ + public static IStatus uninstall(String unitId, String version, IProfile profile, IProgressMonitor progress) throws ProvisionException { + if (profile == null) + return null; + IQueryResult units = profile.query(new InstallableUnitQuery(unitId, Version.create(version)), progress); + if (units.isEmpty()) { + StringBuffer error = new StringBuffer(); + error.append("Installable unit not found: " + unitId + ' ' + version + '\n'); + error.append("Repositories searched:\n"); + URI[] repos = getMetadataRepositories(); + if (repos != null) { + for (int i = 0; i < repos.length; i++) + error.append(repos[i] + "\n"); //$NON-NLS-1$ + } + throw new ProvisionException(error.toString()); + } + + IPlanner planner = (IPlanner) ServiceHelper.getService(Activator.getContext(), IPlanner.SERVICE_NAME); + if (planner == null) + throw new ProvisionException("No planner service found."); + + IEngine engine = (IEngine) ServiceHelper.getService(Activator.getContext(), IEngine.SERVICE_NAME); + if (engine == null) + throw new ProvisionException("No engine service found."); + ProvisioningContext context = new ProvisioningContext(); + ProfileChangeRequest request = new ProfileChangeRequest(profile); + request.removeInstallableUnits(units); + IProvisioningPlan result = planner.getProvisioningPlan(request, context, progress); + return PlanExecutionHelper.executePlan(result, engine, context, progress); + } + } diff --git a/bundles/org.eclipse.equinox.p2.core/.classpath b/bundles/org.eclipse.equinox.p2.core/.classpath index 6f3b481ac..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.core/.classpath +++ b/bundles/org.eclipse.equinox.p2.core/.classpath @@ -1,6 +1,6 @@ - + diff --git a/bundles/org.eclipse.equinox.p2.core/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.core/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 327fbe678..000000000 --- a/bundles/org.eclipse.equinox.p2.core/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,346 +0,0 @@ -#Mon Aug 24 11:19:53 EDT 2009 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert -org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning -org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false -org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false -org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert -org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=public -org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=warning -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert -org.eclipse.jdt.core.compiler.problem.fieldHiding=warning -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning -org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert -org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.formatter.comment.format_source_code=true -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=warning -org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=warning -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -org.eclipse.jdt.core.classpath.exclusionPatterns=enabled -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 -org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert -org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.formatter.comment.format_header=false -org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.comment.line_length=80 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert -org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert -org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.builder.cleanOutputFolder=clean -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=enabled -org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert -org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=false -org.eclipse.jdt.core.formatter.continuation_indentation=2 -org.eclipse.jdt.core.compiler.problem.invalidJavadoc=error -org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert -org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 -org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert -org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line -org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.incompleteClasspath=error -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert -instance/org.eclipse.core.net/org.eclipse.core.net.hasMigrated=true -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=enabled -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=error -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 -org.eclipse.jdt.core.formatter.comment.format_block_comments=false -org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert -org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=insert -org.eclipse.jdt.core.formatter.comment.format_html=true -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning -org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=error -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true -org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert -org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert -org.eclipse.jdt.core.circularClasspath=error -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning -org.eclipse.jdt.core.formatter.tabulation.char=tab -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert -org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true -org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert -org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false -org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false -org.eclipse.jdt.core.formatter.compact_else_if=true -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert -org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert -org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore -org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true -org.eclipse.jdt.core.compiler.problem.discouragedReference=error -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 -org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert -org.eclipse.jdt.core.formatter.comment.format_line_comments=false -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert -org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert -org.eclipse.jdt.core.formatter.comment.indent_parameter_description=false -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=enabled -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.comment.indent_root_tags=false -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert -org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false -org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true -org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.blank_lines_before_package=0 -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert -org.eclipse.jdt.core.formatter.indent_empty_lines=false -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert -org.eclipse.jdt.core.compiler.problem.unusedImport=error -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert -org.eclipse.jdt.core.builder.invalidClasspath=abort -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.incompatibleJDKLevel=ignore -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 -org.eclipse.jdt.core.formatter.lineSplit=800 -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled -org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 -org.eclipse.jdt.core.compiler.source=1.3 -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert -org.eclipse.jdt.core.formatter.tabulation.size=4 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert -org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.builder.duplicateResourceTask=warning -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=insert -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.compiler.doc.comment.support=enabled -org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.compiler.compliance=1.4 -org.eclipse.jdt.core.formatter.blank_lines_after_package=1 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert -org.eclipse.jdt.core.formatter.blank_lines_before_field=0 diff --git a/bundles/org.eclipse.equinox.p2.core/.settings/org.eclipse.pde.api.tools.prefs b/bundles/org.eclipse.equinox.p2.core/.settings/org.eclipse.pde.api.tools.prefs index 7b4e4a2c4..c97ebe5f5 100644 --- a/bundles/org.eclipse.equinox.p2.core/.settings/org.eclipse.pde.api.tools.prefs +++ b/bundles/org.eclipse.equinox.p2.core/.settings/org.eclipse.pde.api.tools.prefs @@ -1,10 +1,12 @@ -#Wed Dec 03 12:05:24 EST 2008 +#Wed Jan 13 12:12:41 EST 2010 ANNOTATION_ELEMENT_TYPE_ADDED_METHOD_WITHOUT_DEFAULT_VALUE=Error ANNOTATION_ELEMENT_TYPE_CHANGED_TYPE_CONVERSION=Error ANNOTATION_ELEMENT_TYPE_REMOVED_FIELD=Error ANNOTATION_ELEMENT_TYPE_REMOVED_METHOD=Error ANNOTATION_ELEMENT_TYPE_REMOVED_TYPE_MEMBER=Error API_COMPONENT_ELEMENT_TYPE_REMOVED_API_TYPE=Error +API_COMPONENT_ELEMENT_TYPE_REMOVED_REEXPORTED_API_TYPE=Error +API_COMPONENT_ELEMENT_TYPE_REMOVED_REEXPORTED_TYPE=Error API_COMPONENT_ELEMENT_TYPE_REMOVED_TYPE=Error CLASS_ELEMENT_TYPE_ADDED_METHOD=Error CLASS_ELEMENT_TYPE_ADDED_RESTRICTIONS=Error @@ -56,8 +58,8 @@ INTERFACE_ELEMENT_TYPE_REMOVED_FIELD=Error INTERFACE_ELEMENT_TYPE_REMOVED_METHOD=Error INTERFACE_ELEMENT_TYPE_REMOVED_TYPE_MEMBER=Error INTERFACE_ELEMENT_TYPE_REMOVED_TYPE_PARAMETER=Error -INVALID_JAVADOC_TAG=Warning -INVALID_REFERENCE_IN_SYSTEM_LIBRARIES=Error +INVALID_JAVADOC_TAG=Ignore +INVALID_REFERENCE_IN_SYSTEM_LIBRARIES=Ignore LEAK_EXTEND=Warning LEAK_FIELD_DECL=Warning LEAK_IMPLEMENT=Warning @@ -79,6 +81,7 @@ TYPE_PARAMETER_ELEMENT_TYPE_CHANGED_CLASS_BOUND=Error TYPE_PARAMETER_ELEMENT_TYPE_CHANGED_INTERFACE_BOUND=Error TYPE_PARAMETER_ELEMENT_TYPE_REMOVED_CLASS_BOUND=Error TYPE_PARAMETER_ELEMENT_TYPE_REMOVED_INTERFACE_BOUND=Error +UNUSED_PROBLEM_FILTERS=Warning eclipse.preferences.version=1 incompatible_api_component_version=Error incompatible_api_component_version_include_major_without_breaking_change=Disabled @@ -86,3 +89,5 @@ incompatible_api_component_version_include_minor_without_api_change=Disabled invalid_since_tag_version=Error malformed_since_tag=Error missing_since_tag=Error +report_api_breakage_when_major_version_incremented=Disabled +report_resolution_errors_api_component=Warning diff --git a/bundles/org.eclipse.equinox.p2.core/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.core/META-INF/MANIFEST.MF index de1a72cde..2f2feff92 100644 --- a/bundles/org.eclipse.equinox.p2.core/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.core/META-INF/MANIFEST.MF @@ -4,7 +4,7 @@ Bundle-SymbolicName: org.eclipse.equinox.p2.core;singleton:=true Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-Localization: plugin -Bundle-Version: 1.1.0.qualifier +Bundle-Version: 2.0.0.qualifier Import-Package: org.eclipse.osgi.framework.eventmgr;version="1.2.0", org.eclipse.osgi.framework.log;version="1.0.0", org.eclipse.osgi.service.debug;version="1.0.0", @@ -25,12 +25,14 @@ Export-Package: org.eclipse.equinox.internal.p2.core;x-friends:="org.eclipse.equ org.eclipse.equinox.p2.installer, org.eclipse.equinox.p2.metadata, org.eclipse.equinox.p2.metadata.generator, + org.eclipse.equinox.p2.operations, org.eclipse.equinox.frameworkadmin.test, org.eclipse.equinox.p2.metadata.repository, org.eclipse.equinox.p2.repositoryoptimizer, org.eclipse.equinox.p2.touchpoint.eclipse, org.eclipse.equinox.p2.touchpoint.natives, org.eclipse.equinox.p2.ui, + org.eclipse.equinox.p2.ui.admin, org.eclipse.equinox.p2.ui.sdk, org.eclipse.equinox.p2.ui.sdk.scheduler, org.eclipse.equinox.p2.updatechecker, @@ -42,7 +44,8 @@ Export-Package: org.eclipse.equinox.internal.p2.core;x-friends:="org.eclipse.equ org.eclipse.equinox.p2.extensionlocation, org.eclipse.equinox.p2.publisher, org.eclipse.equinox.p2.repository.tools, - org.eclipse.equinox.p2.repository", + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.ql", org.eclipse.equinox.internal.provisional.p2.core; x-friends:="org.eclipse.equinox.p2.artifact.optimizers, org.eclipse.equinox.p2.artifact.processors, @@ -56,6 +59,7 @@ Export-Package: org.eclipse.equinox.internal.p2.core;x-friends:="org.eclipse.equ org.eclipse.equinox.p2.installer, org.eclipse.equinox.p2.metadata.generator, org.eclipse.equinox.p2.metadata.repository, + org.eclipse.equinox.p2.operations, org.eclipse.equinox.p2.publisher, org.eclipse.equinox.p2.reconciler.dropins, org.eclipse.equinox.p2.touchpoint.eclipse, @@ -86,21 +90,16 @@ Export-Package: org.eclipse.equinox.internal.p2.core;x-friends:="org.eclipse.equ org.eclipse.equinox.p2.artifact.repository, org.eclipse.equinox.p2.touchpoint.eclipse, org.eclipse.equinox.p2.touchpoint.natives, + org.eclipse.equinox.p2.operations, org.eclipse.equinox.p2.publisher, org.eclipse.equinox.p2.repository", - org.eclipse.equinox.internal.provisional.p2.core.location; - x-friends:="org.eclipse.equinox.p2.artifact.repository, - org.eclipse.equinox.p2.touchpoint.natives, - org.eclipse.equinox.p2.metadata.repository, - org.eclipse.equinox.p2.director, - org.eclipse.equinox.p2.engine, - org.eclipse.equinox.p2.touchpoint.eclipse", org.eclipse.equinox.p2.core, org.eclipse.equinox.p2.core.spi Bundle-ActivationPolicy: lazy Bundle-ClassPath: . -Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, - J2SE-1.4 +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 Bundle-Activator: org.eclipse.equinox.internal.p2.core.Activator Require-Bundle: org.eclipse.equinox.common;bundle-version="[3.5.0,4.0.0)" Service-Component: OSGI-INF/eventBus.xml, OSGI-INF/agentProvider.xml diff --git a/bundles/org.eclipse.equinox.p2.core/build.properties b/bundles/org.eclipse.equinox.p2.core/build.properties index 4f52e07f1..98b717479 100644 --- a/bundles/org.eclipse.equinox.p2.core/build.properties +++ b/bundles/org.eclipse.equinox.p2.core/build.properties @@ -16,3 +16,5 @@ bin.includes = META-INF/,\ OSGI-INF/ src.includes = about.html source.. = src/ +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/Activator.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/Activator.java index 8b67449da..45f8a9d66 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/Activator.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/Activator.java @@ -11,18 +11,19 @@ package org.eclipse.equinox.internal.p2.core; import java.io.File; -import java.net.MalformedURLException; -import java.net.URL; +import java.net.URI; +import java.net.URISyntaxException; import java.util.Dictionary; import java.util.Hashtable; import org.eclipse.core.runtime.Path; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; +import org.eclipse.core.runtime.URIUtil; +import org.eclipse.equinox.p2.core.IAgentLocation; import org.eclipse.osgi.framework.log.FrameworkLog; import org.osgi.framework.*; import org.osgi.util.tracker.ServiceTracker; public class Activator implements BundleActivator { - public static AgentLocation agentDataLocation = null; + public static IAgentLocation agentDataLocation = null; public static BundleContext context; private static final String DEFAULT_AGENT_LOCATION = "../p2"; //$NON-NLS-1$ @@ -51,12 +52,12 @@ public class Activator implements BundleActivator { * NOTE: This method is copied from LocationHelper in org.eclipse.osgi * due to access restrictions. */ - private static URL adjustTrailingSlash(URL url, boolean trailingSlash) throws MalformedURLException { - String file = url.getFile(); + private static URI adjustTrailingSlash(URI url, boolean trailingSlash) throws URISyntaxException { + String file = url.toString(); if (trailingSlash == (file.endsWith("/"))) //$NON-NLS-1$ return url; file = trailingSlash ? file + "/" : file.substring(0, file.length() - 1); //$NON-NLS-1$ - return new URL(url.getProtocol(), url.getHost(), file); + return new URI(file); } /** @@ -68,22 +69,22 @@ public class Activator implements BundleActivator { * @param trailingSlash flag to indicate a trailing slash on the spec * @return a URL */ - private static URL buildURL(String spec, boolean trailingSlash) { + private static URI buildURL(String spec, boolean trailingSlash) { if (spec == null) return null; boolean isFile = spec.startsWith("file:"); //$NON-NLS-1$ try { if (isFile) - return adjustTrailingSlash(new File(spec.substring(5)).toURL(), trailingSlash); - return new URL(spec); - } catch (MalformedURLException e) { + return adjustTrailingSlash(new File(spec.substring(5)).toURI(), trailingSlash); + return new URI(spec); + } catch (URISyntaxException e) { // if we failed and it is a file spec, there is nothing more we can do // otherwise, try to make the spec into a file URL. if (isFile) return null; try { - return adjustTrailingSlash(new File(spec).toURL(), trailingSlash); - } catch (MalformedURLException e1) { + return adjustTrailingSlash(new File(spec).toURI(), trailingSlash); + } catch (URISyntaxException e1) { return null; } } @@ -114,16 +115,16 @@ public class Activator implements BundleActivator { return value + source.substring(var.length()); } - private AgentLocation buildLocation(String property, URL defaultLocation, boolean readOnlyDefault, boolean addTrailingSlash) { + private IAgentLocation buildLocation(String property, URI defaultLocation, boolean readOnlyDefault, boolean addTrailingSlash) { String location = Activator.context.getProperty(property); // if the instance location is not set, predict where the workspace will be and // put the instance area inside the workspace meta area. if (location == null) - return new BasicLocation(defaultLocation); + return new AgentLocation(defaultLocation); if (location.equalsIgnoreCase(NONE)) return null; if (location.equalsIgnoreCase(NO_DEFAULT)) - return new BasicLocation(null); + return new AgentLocation(null); if (location.startsWith(VAR_USER_HOME)) { String base = substituteVar(location, VAR_USER_HOME, PROP_USER_HOME); location = new Path(base).toFile().getAbsolutePath(); @@ -134,10 +135,10 @@ public class Activator implements BundleActivator { //note the config dir system property is already a URL location = substituteVar(location, VAR_CONFIG_DIR, PROP_CONFIG_DIR); } - URL url = buildURL(location, addTrailingSlash); - BasicLocation result = null; + URI url = buildURL(location, addTrailingSlash); + AgentLocation result = null; if (url != null) { - result = new BasicLocation(url); + result = new AgentLocation(url); } return result; } @@ -156,12 +157,12 @@ public class Activator implements BundleActivator { public void start(BundleContext aContext) throws Exception { instance = this; Activator.context = aContext; - URL defaultLocation = new URL(aContext.getProperty(PROP_CONFIG_DIR) + DEFAULT_AGENT_LOCATION + '/'); + URI defaultLocation = URIUtil.fromString(aContext.getProperty(PROP_CONFIG_DIR) + DEFAULT_AGENT_LOCATION + '/'); agentDataLocation = buildLocation(PROP_AGENT_DATA_AREA, defaultLocation, false, true); - Dictionary locationProperties = new Hashtable(); + Dictionary locationProperties = new Hashtable(); if (agentDataLocation != null) { locationProperties.put("type", PROP_AGENT_DATA_AREA); //$NON-NLS-1$ - agentLocationRegistration = aContext.registerService(AgentLocation.SERVICE_NAME, agentDataLocation, locationProperties); + agentLocationRegistration = aContext.registerService(IAgentLocation.SERVICE_NAME, agentDataLocation, locationProperties); } } diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/AgentLocation.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/AgentLocation.java new file mode 100644 index 000000000..75849e02f --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/AgentLocation.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2004, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.core; + +import java.net.URI; +import org.eclipse.core.runtime.URIUtil; +import org.eclipse.equinox.p2.core.IAgentLocation; + +/** + * Internal class. + */ +public class AgentLocation implements IAgentLocation { + + private URI location = null; + + public AgentLocation(URI location) { + this.location = location; + } + + public synchronized URI getRootLocation() { + return location; + } + + public URI getDataArea(String touchpointId) { + return URIUtil.append(getRootLocation(), touchpointId + '/'); + } +} diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/BasicLocation.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/BasicLocation.java deleted file mode 100644 index 327d6a0a1..000000000 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/BasicLocation.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.core; - -import java.net.*; -import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; - -/** - * Internal class. - */ -public class BasicLocation implements AgentLocation { - - private URL location = null; - - public BasicLocation(URL location) { - this.location = location; - } - - public synchronized URL getURL() { - return location; - } - - public URI getArtifactRepositoryURI() { - //the cache is a co-located repository - return getMetadataRepositoryURI(); - } - - public URI getMetadataRepositoryURI() { - try { - return URIUtil.toURI(new URL(getDataArea(Activator.ID), "cache/")); //$NON-NLS-1$ - } catch (MalformedURLException e) { - // TODO Auto-generated catch block - } catch (URISyntaxException e) { - // TODO Auto-generated catch block - } - return null; - } - - public URL getDataArea(String touchpointId) { - try { - return new URL(getURL(), touchpointId + '/'); - } catch (MalformedURLException e) { - // TODO Auto-generated catch block - return null; - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/DefaultAgentProvider.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/DefaultAgentProvider.java index 2fd5b8f92..158e28177 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/DefaultAgentProvider.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/DefaultAgentProvider.java @@ -11,9 +11,10 @@ package org.eclipse.equinox.internal.p2.core; import java.net.URI; -import org.eclipse.equinox.p2.core.IProvisioningAgent; -import org.eclipse.equinox.p2.core.IProvisioningAgentProvider; -import org.osgi.framework.BundleContext; +import java.util.Dictionary; +import java.util.Hashtable; +import org.eclipse.equinox.p2.core.*; +import org.osgi.framework.*; /** * Default implementation of {@link IProvisioningAgentProvider}. @@ -27,9 +28,19 @@ public class DefaultAgentProvider implements IProvisioningAgentProvider { public IProvisioningAgent createAgent(URI location) { ProvisioningAgent result = new ProvisioningAgent(); - result.setLocation(location); result.setBundleContext(context); + result.setLocation(location); + IAgentLocation agentLocation = (IAgentLocation) result.getService(IAgentLocation.SERVICE_NAME); + Dictionary properties = new Hashtable(5); + if (agentLocation != null) + properties.put("locationURI", String.valueOf(agentLocation.getRootLocation())); //$NON-NLS-1$ + //make the currently running system have a higher service ranking + if (location == null) { + properties.put(Constants.SERVICE_RANKING, new Integer(100)); + properties.put(IProvisioningAgent.SERVICE_CURRENT, Boolean.TRUE.toString()); + } + ServiceRegistration reg = context.registerService(IProvisioningAgent.SERVICE_NAME, result, properties); + result.setServiceRegistration(reg); return result; } - } diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/ProvisioningAgent.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/ProvisioningAgent.java index aef7146b5..c0fd26504 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/ProvisioningAgent.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/ProvisioningAgent.java @@ -10,12 +10,9 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.core; -import java.net.MalformedURLException; import java.net.URI; import java.util.*; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; +import org.eclipse.equinox.p2.core.IAgentLocation; import org.eclipse.equinox.p2.core.IProvisioningAgent; import org.eclipse.equinox.p2.core.spi.IAgentServiceFactory; import org.osgi.framework.*; @@ -25,14 +22,23 @@ import org.osgi.framework.*; */ public class ProvisioningAgent implements IProvisioningAgent { - private final Map agentServices = Collections.synchronizedMap(new HashMap()); - + private final Map agentServices = Collections.synchronizedMap(new HashMap()); private BundleContext context; + private boolean stopped = false; + private ServiceRegistration reg; + + /** + * Instantiates a provisioning agent. + */ + public ProvisioningAgent() { + super(); + } /* (non-Javadoc) * @see org.eclipse.equinox.p2.core.IProvisioningAgent#getService(java.lang.String) */ public Object getService(String serviceName) { + checkRunning(); Object service = agentServices.get(serviceName); if (service != null) return service; @@ -59,7 +65,13 @@ public class ProvisioningAgent implements IProvisioningAgent { return service; } + private synchronized void checkRunning() { + if (stopped) + throw new RuntimeException("Attempt to access stopped agent: " + this); + } + public void registerService(String serviceName, Object service) { + checkRunning(); agentServices.put(serviceName, service); } @@ -68,18 +80,40 @@ public class ProvisioningAgent implements IProvisioningAgent { } public void setLocation(URI location) { - try { - AgentLocation agentLocation = new BasicLocation(URIUtil.toURL(location)); - agentServices.put(AgentLocation.SERVICE_NAME, agentLocation); - } catch (MalformedURLException e) { - LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "Invalid agent location", e)); //$NON-NLS-1$ + //treat a null location as using the currently running platform + IAgentLocation agentLocation = null; + if (location == null) { + ServiceReference ref = context.getServiceReference(IAgentLocation.SERVICE_NAME); + if (ref != null) { + agentLocation = (IAgentLocation) context.getService(ref); + context.ungetService(ref); + } + } else { + agentLocation = new AgentLocation(location); } + agentServices.put(IAgentLocation.SERVICE_NAME, agentLocation); } public void unregisterService(String serviceName, Object service) { + synchronized (this) { + if (stopped) + return; + } synchronized (agentServices) { if (agentServices.get(serviceName) == service) agentServices.remove(serviceName); } } + + public synchronized void stop() { + stopped = true; + if (reg != null) { + reg.unregister(); + reg = null; + } + } + + public void setServiceRegistration(ServiceRegistration reg) { + this.reg = reg; + } } diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/StringPool.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/StringPool.java index 930378462..f7ff68cd6 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/StringPool.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/StringPool.java @@ -23,7 +23,7 @@ import java.util.HashMap; */ public final class StringPool { private int savings; - private final HashMap map = new HashMap(); + private final HashMap map = new HashMap(); /** * Creates a new string pool. @@ -41,11 +41,11 @@ public final class StringPool { public String add(String string) { if (string == null) return string; - Object result = map.get(string); + String result = map.get(string); if (result != null) { if (result != string) savings += 44 + 2 * string.length(); - return (String) result; + return result; } //explicitly copy the string to trim excess baggage String trim = new String(string.toCharArray()); diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/CollectionUtils.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/CollectionUtils.java new file mode 100644 index 000000000..5bea8c961 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/CollectionUtils.java @@ -0,0 +1,263 @@ +/******************************************************************************* + * Copyright (c) 2009, 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.core.helpers; + +import java.io.*; +import java.lang.reflect.Array; +import java.util.*; + +/** + * Helper class that provides some useful support when dealing with collections. + */ +public class CollectionUtils { + + /** + * A unmodifiable {@link List} implementation on top of an object array. + * @param The element type. + */ + private static class UnmodifiableArrayList extends AbstractList implements RandomAccess, java.io.Serializable { + private static final long serialVersionUID = 7435304230643855579L; + final E[] array; + + UnmodifiableArrayList(E[] array) { + this.array = array; + } + + public boolean contains(Object o) { + return indexOf(o) != -1; + } + + public E get(int index) { + return array[index]; + } + + public int indexOf(Object o) { + int size = array.length; + if (o == null) { + for (int i = 0; i < size; i++) + if (array[i] == null) + return i; + } else { + for (int i = 0; i < size; i++) + if (o.equals(array[i])) + return i; + } + return -1; + } + + public Iterator iterator() { + return listIterator(); + } + + /** + * Rapid iterator, motivated by the fact that we don't need to check + * for concurrent modifications. + */ + public ListIterator listIterator() { + return new ListIterator() { + private int index = 0; + + public boolean hasNext() { + return index < array.length; + } + + public E next() { + if (index >= array.length) + throw new NoSuchElementException(); + return array[index++]; + } + + public boolean hasPrevious() { + return index > 0; + } + + public E previous() { + if (--index < 0) { + ++index; + throw new NoSuchElementException(); + } + return array[index]; + } + + public int nextIndex() { + return index; + } + + public int previousIndex() { + return index - 1; + } + + public void remove() { + throw new UnsupportedOperationException(); + } + + public void set(E e) { + throw new UnsupportedOperationException(); + } + + public void add(E e) { + throw new UnsupportedOperationException(); + } + }; + } + + public int lastIndexOf(Object o) { + int idx = array.length; + if (o == null) { + while (--idx >= 0) + if (array[idx] == null) + return idx; + } else { + while (--idx >= 0) + if (o.equals(array[idx])) + return idx; + } + return -1; + } + + public E set(int index, E element) { + throw new UnsupportedOperationException(); + } + + public int size() { + return array.length; + } + + public Object[] toArray() { + return array.clone(); + } + + @SuppressWarnings("unchecked") + public T[] toArray(T[] a) { + int size = array.length; + if (a.length < size) + a = (T[]) Array.newInstance(a.getClass().getComponentType(), size); + System.arraycopy(this.array, 0, a, 0, size); + while (size < a.length) + a[size++] = null; + return a; + } + } + + /** + * Creates a combined hash for an array of objects. + * @param objects The objects to hash + * @return The combined hashCode of the objects. + */ + public static int hashCode(Object objects[]) { + if (objects == null) + return 0; + + int result = 1; + int idx = objects.length; + while (--idx >= 0) { + Object object = objects[idx]; + result = 17 * result + (object == null ? 0 : object.hashCode()); + } + return result; + } + + /** + * The emptyList() method was introduced in Java 1.5 so we need this here to be able to + * down compile to 1.4. + * @param The type of the elements + * @return An empty list + */ + @SuppressWarnings("unchecked") + public static List emptyList() { + return Collections.EMPTY_LIST; + } + + /** + * The emptySet() method was introduced in Java 1.5 so we need this here to be able to + * down compile to 1.4. + * @param The type of the elements + * @return An empty set + */ + @SuppressWarnings("unchecked") + public static Set emptySet() { + return Collections.EMPTY_SET; + } + + /** + * The emptyMap() method was introduced in Java 1.5 so we need this here to be able to + * down compile to 1.4. + * @param The type of the map keys + * @param The type of the map values + * @return An empty set + */ + @SuppressWarnings("unchecked") + public static Map emptyMap() { + return Collections.EMPTY_MAP; + } + + /** + * Returns an unmodifiable list that is backed by the array. + * @param The list element type + * @param array The array of elements + * @return The unmodifiable list + */ + public static List unmodifiableList(T[] array) { + return array == null || array.length == 0 ? CollectionUtils. emptyList() : new UnmodifiableArrayList(array); + } + + /** + * Reads a property list using the {@link Properties#load(InputStream)} method. The + * properties are stored in a map. + * @param stream The stream to read from + * @return The resulting map + * @throws IOException propagated from the load method. + */ + public static Map loadProperties(InputStream stream) throws IOException { + Properties properties = new Properties(); + properties.load(stream); + return toMap(properties); + } + + /** + * Copies all elements from properties into a Map. The returned map might be unmodifiable + * @param properties + * @return The map containing all elements + */ + public static Map toMap(Properties properties) { + if (properties == null || properties.isEmpty()) + return emptyMap(); + + Map props = new HashMap(properties.size()); + putAll(properties, props); + return props; + } + + /** + * Copies all elements from properties into the given result. + * @param properties + * @param result + */ + public static void putAll(Properties properties, Map result) { + for (Enumeration keys = properties.keys(); keys.hasMoreElements();) { + String key = (String) keys.nextElement(); + result.put(key, properties.getProperty(key)); + } + } + + /** + * Stores the properties using {@link Properties#store(OutputStream, String)} on the given stream. + * @param properties The properties to store + * @param stream The stream to store to + * @param comment The comment to use + * @throws IOException + */ + public static void storeProperties(Map properties, OutputStream stream, String comment) throws IOException { + Properties props = new Properties(); + props.putAll(properties); + props.store(stream, comment); + } +} diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/FileUtils.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/FileUtils.java index 96a9f9810..ded76dffc 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/FileUtils.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/FileUtils.java @@ -21,10 +21,10 @@ public class FileUtils { private static File[] untarFile(File source, File outputDir) throws IOException, TarException { TarFile tarFile = new TarFile(source); - List untarredFiles = new ArrayList(); + List untarredFiles = new ArrayList(); try { - for (Enumeration e = tarFile.entries(); e.hasMoreElements();) { - TarEntry entry = (TarEntry) e.nextElement(); + for (Enumeration e = tarFile.entries(); e.hasMoreElements();) { + TarEntry entry = e.nextElement(); InputStream input = tarFile.getInputStream(entry); try { File outFile = new File(outputDir, entry.getName()); @@ -52,7 +52,7 @@ public class FileUtils { } finally { tarFile.close(); } - return (File[]) untarredFiles.toArray(new File[untarredFiles.size()]); + return untarredFiles.toArray(new File[untarredFiles.size()]); } /** @@ -107,7 +107,7 @@ public class FileUtils { in.close(); throw new IOException(Messages.Util_Invalid_Zip_File_Format); } - ArrayList unzippedFiles = new ArrayList(); + ArrayList unzippedFiles = new ArrayList(); do { File outFile = new File(outputDir, ze.getName()); unzippedFiles.add(outFile); @@ -131,7 +131,7 @@ public class FileUtils { } while ((ze = in.getNextEntry()) != null); in.close(); - return (File[]) unzippedFiles.toArray(new File[unzippedFiles.size()]); + return unzippedFiles.toArray(new File[unzippedFiles.size()]); } // Delete empty directories under dir, including dir itself. @@ -243,8 +243,8 @@ public class FileUtils { public static void zip(File[] inclusions, File[] exclusions, File destinationArchive, IPathComputer pathComputer) throws IOException { FileOutputStream fileOutput = new FileOutputStream(destinationArchive); ZipOutputStream output = new ZipOutputStream(fileOutput); - HashSet exclusionSet = exclusions == null ? new HashSet() : new HashSet(Arrays.asList(exclusions)); - HashSet directoryEntries = new HashSet(); + HashSet exclusionSet = exclusions == null ? new HashSet() : new HashSet(Arrays.asList(exclusions)); + HashSet directoryEntries = new HashSet(); try { for (int i = 0; i < inclusions.length; i++) { pathComputer.reset(); @@ -273,11 +273,11 @@ public class FileUtils { * @param pathComputer - computer used to create the path of the files in the result. * @throws IOException */ - public static void zip(ZipOutputStream output, File source, Set exclusions, IPathComputer pathComputer) throws IOException { - zip(output, source, exclusions, pathComputer, new HashSet()); + public static void zip(ZipOutputStream output, File source, Set exclusions, IPathComputer pathComputer) throws IOException { + zip(output, source, exclusions, pathComputer, new HashSet()); } - public static void zip(ZipOutputStream output, File source, Set exclusions, IPathComputer pathComputer, Set directoryEntries) throws IOException { + public static void zip(ZipOutputStream output, File source, Set exclusions, IPathComputer pathComputer, Set directoryEntries) throws IOException { if (exclusions.contains(source)) return; if (source.isDirectory()) //if the file path is a URL then isDir and isFile are both false @@ -286,7 +286,7 @@ public class FileUtils { zipFile(output, source, pathComputer, directoryEntries); } - private static void zipDirectoryEntry(ZipOutputStream output, IPath entry, long time, Set directoryEntries) throws IOException { + private static void zipDirectoryEntry(ZipOutputStream output, IPath entry, long time, Set directoryEntries) throws IOException { entry = entry.addTrailingSeparator(); if (!directoryEntries.contains(entry)) { //make sure parent entries are in the zip @@ -314,7 +314,7 @@ public class FileUtils { * Zip the contents of the given directory into the zip file represented by * the given zip stream. Prepend the given prefix to the file paths. */ - private static void zipDir(ZipOutputStream output, File source, Set exclusions, IPathComputer pathComputer, Set directoryEntries) throws IOException { + private static void zipDir(ZipOutputStream output, File source, Set exclusions, IPathComputer pathComputer, Set directoryEntries) throws IOException { File[] files = source.listFiles(); if (files.length == 0) { zipDirectoryEntry(output, pathComputer.computePath(source), source.lastModified(), directoryEntries); @@ -326,16 +326,16 @@ public class FileUtils { // foo/bar.txt // foo/something/bar2.txt // foo/something/else/bar3.txt - Arrays.sort(files, new Comparator() { - public int compare(Object arg0, Object arg1) { - Path a = new Path(((File) arg0).getAbsolutePath()); - Path b = new Path(((File) arg1).getAbsolutePath()); + Arrays.sort(files, new Comparator() { + public int compare(File arg0, File arg1) { + Path a = new Path(arg0.getAbsolutePath()); + Path b = new Path(arg1.getAbsolutePath()); if (a.segmentCount() == b.segmentCount()) { - if (((File) arg0).isDirectory() && ((File) arg1).isFile()) + if (arg0.isDirectory() && arg1.isFile()) return 1; - else if (((File) arg0).isDirectory() && ((File) arg1).isDirectory()) + else if (arg0.isDirectory() && arg1.isDirectory()) return 0; - else if (((File) arg0).isFile() && ((File) arg1).isDirectory()) + else if (arg0.isFile() && arg1.isDirectory()) return -1; else return 0; @@ -352,7 +352,7 @@ public class FileUtils { * Add the given file to the zip file represented by the specified stream. * Prepend the given prefix to the path of the file. */ - private static void zipFile(ZipOutputStream output, File source, IPathComputer pathComputer, Set directoryEntries) throws IOException { + private static void zipFile(ZipOutputStream output, File source, IPathComputer pathComputer, Set directoryEntries) throws IOException { boolean isManifest = false; //manifest files are special InputStream input = new BufferedInputStream(new FileInputStream(source)); try { diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/LogHelper.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/LogHelper.java index cb3fd613a..749401c68 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/LogHelper.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/LogHelper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,7 +13,7 @@ package org.eclipse.equinox.internal.p2.core.helpers; import java.util.ArrayList; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.Activator; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.core.ProvisionException; import org.eclipse.osgi.framework.log.FrameworkLog; import org.eclipse.osgi.framework.log.FrameworkLogEntry; @@ -39,7 +39,7 @@ public class LogHelper { */ private static FrameworkLogEntry getLog(IStatus status) { Throwable t = status.getException(); - ArrayList childlist = new ArrayList(); + ArrayList childlist = new ArrayList(); int stackCode = t instanceof CoreException ? 1 : 0; // ensure a substatus inside a CoreException is properly logged @@ -57,7 +57,7 @@ public class LogHelper { } } - FrameworkLogEntry[] children = (FrameworkLogEntry[]) (childlist.size() == 0 ? null : childlist.toArray(new FrameworkLogEntry[childlist.size()])); + FrameworkLogEntry[] children = (childlist.size() == 0 ? null : childlist.toArray(new FrameworkLogEntry[childlist.size()])); return new FrameworkLogEntry(status.getPlugin(), status.getSeverity(), status.getCode(), status.getMessage(), stackCode, t, children); } diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/OrderedProperties.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/OrderedProperties.java index 442132bf6..2520f2d0d 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/OrderedProperties.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/OrderedProperties.java @@ -26,11 +26,11 @@ import java.util.*; * The class does not support default properties as they can be expressed by * creating java.util.Properties hierarchies. */ -public class OrderedProperties extends Dictionary implements Map { +public class OrderedProperties extends Dictionary implements Map { - LinkedHashMap propertyMap = null; + LinkedHashMap propertyMap = null; - public static OrderedProperties unmodifiableProperties(Map properties) { + public static OrderedProperties unmodifiableProperties(Map properties) { return new UnmodifiableProperties(properties); } @@ -40,12 +40,12 @@ public class OrderedProperties extends Dictionary implements Map { public OrderedProperties(int size) { super(); - propertyMap = new LinkedHashMap(size); + propertyMap = new LinkedHashMap(size); } public OrderedProperties(OrderedProperties properties) { super(); - propertyMap = new LinkedHashMap(properties.size()); + propertyMap = new LinkedHashMap(properties.size()); putAll(properties); } @@ -67,11 +67,11 @@ public class OrderedProperties extends Dictionary implements Map { } public String getProperty(String key) { - return (String) (propertyMap == null ? null : propertyMap.get(key)); + return (propertyMap == null ? null : propertyMap.get(key)); } public void putAll(OrderedProperties properties) { - putAll((Map) properties); + putAll(properties); } /** @@ -79,7 +79,7 @@ public class OrderedProperties extends Dictionary implements Map { */ private void init() { if (propertyMap == null) { - propertyMap = new LinkedHashMap(); + propertyMap = new LinkedHashMap(); } } @@ -95,9 +95,9 @@ public class OrderedProperties extends Dictionary implements Map { propertyMap = null; } - public Object put(Object arg0, Object arg1) { + public String put(String key, String value) { init(); - return propertyMap.put(arg0, arg1); + return propertyMap.put(key, value); } public boolean containsKey(Object key) { @@ -108,29 +108,29 @@ public class OrderedProperties extends Dictionary implements Map { return propertyMap != null ? propertyMap.containsValue(value) : false; } - public Set entrySet() { - return propertyMap != null ? propertyMap.entrySet() : Collections.EMPTY_SET; + public Set> entrySet() { + return propertyMap != null ? propertyMap.entrySet() : CollectionUtils.> emptySet(); } - public Object get(Object key) { + public String get(Object key) { return propertyMap != null ? propertyMap.get(key) : null; } - public Set keySet() { - return propertyMap != null ? propertyMap.keySet() : Collections.EMPTY_SET; + public Set keySet() { + return propertyMap != null ? propertyMap.keySet() : CollectionUtils. emptySet(); } - public void putAll(Map arg0) { + public void putAll(Map arg0) { init(); propertyMap.putAll(arg0); } - public Object remove(Object key) { + public String remove(Object key) { return propertyMap != null ? propertyMap.remove(key) : null; } - public Collection values() { - return propertyMap != null ? propertyMap.values() : Collections.EMPTY_LIST; + public Collection values() { + return propertyMap != null ? propertyMap.values() : CollectionUtils. emptyList(); } public boolean equals(Object o) { @@ -147,8 +147,8 @@ public class OrderedProperties extends Dictionary implements Map { return rhs.propertyMap.equals(this.propertyMap); } if (this.propertyMap == null) { - if (o instanceof Map) - return ((Map) o).isEmpty(); + if (o instanceof Map) + return ((Map) o).isEmpty(); return false; } return this.propertyMap.equals(o); @@ -164,54 +164,36 @@ public class OrderedProperties extends Dictionary implements Map { return sb.toString(); } - private class ElementsEnum implements Enumeration { + private class StringsEnum implements Enumeration { - Iterator iterator = null; + private final Iterator iterator; - public ElementsEnum(OrderedProperties properties) { - iterator = properties.propertyMap.values().iterator(); + public StringsEnum(Collection elems) { + this.iterator = elems.iterator(); } public boolean hasMoreElements() { return iterator.hasNext(); } - public Object nextElement() { + public String nextElement() { return iterator.next(); } } - public Enumeration elements() { - return new ElementsEnum(this); - } - - private class KeysEnum implements Enumeration { - - Iterator iterator = null; - - public KeysEnum(OrderedProperties properties) { - iterator = properties.propertyMap.keySet().iterator(); - } - - public boolean hasMoreElements() { - return iterator.hasNext(); - } - - public Object nextElement() { - return iterator.next(); - } + public Enumeration elements() { + return new StringsEnum(propertyMap.values()); } - public Enumeration keys() { - return new KeysEnum(this); + public Enumeration keys() { + return new StringsEnum(propertyMap.keySet()); } private static class UnmodifiableProperties extends OrderedProperties { - UnmodifiableProperties(Map properties) { + UnmodifiableProperties(Map properties) { super(); - for (Iterator iter = properties.entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); + for (Map.Entry entry : properties.entrySet()) { super.put(entry.getKey(), entry.getValue()); } } @@ -220,15 +202,15 @@ public class OrderedProperties extends Dictionary implements Map { throw new UnsupportedOperationException(); } - public synchronized Object put(Object key, Object value) { + public synchronized String put(String key, String value) { throw new UnsupportedOperationException(); } - public synchronized Object remove(Object key) { + public synchronized String remove(Object key) { throw new UnsupportedOperationException(); } - public synchronized void putAll(Map t) { + public synchronized void putAll(Map t) { throw new UnsupportedOperationException(); } diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/StringHelper.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/StringHelper.java index c1995c27f..2d6a9e557 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/StringHelper.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/StringHelper.java @@ -26,7 +26,7 @@ public class StringHelper { if (spec.length() > 0) resultArr = new String[] {spec}; } else { - List result = new ArrayList(); + List result = new ArrayList(); while (splitIdx >= 0) { String part = spec.substring(0, splitIdx).trim(); if (part.length() > 0) @@ -37,7 +37,7 @@ public class StringHelper { spec = spec.trim(); if (spec.length() > 0) result.add(spec); - resultArr = (String[]) result.toArray(new String[result.size()]); + resultArr = result.toArray(new String[result.size()]); } } return resultArr; diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/TarFile.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/TarFile.java index 5500bc765..4b4971236 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/TarFile.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/core/helpers/TarFile.java @@ -70,13 +70,13 @@ public class TarFile { * * @return enumeration of all files in the archive */ - public Enumeration entries() { - return new Enumeration() { + public Enumeration entries() { + return new Enumeration() { public boolean hasMoreElements() { return (curEntry != null); } - public Object nextElement() { + public TarEntry nextElement() { TarEntry oldEntry = curEntry; try { curEntry = entryEnumerationStream.getNextEntry(); diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/provisional/p2/core/IServiceUI.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/provisional/p2/core/IServiceUI.java index 0b339d5a2..89fe5231e 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/provisional/p2/core/IServiceUI.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/provisional/p2/core/IServiceUI.java @@ -23,6 +23,11 @@ import java.security.cert.Certificate; * bundle providing the service is partitioned appropriately. */ public interface IServiceUI { + /** + * Service name constant for the UI service. + */ + public static final String SERVICE_NAME = IServiceUI.class.getName(); + /** * Authentication information returned from an authentication prompt request. */ diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/provisional/p2/core/ProvisionException.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/provisional/p2/core/ProvisionException.java deleted file mode 100644 index dd1feee10..000000000 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/provisional/p2/core/ProvisionException.java +++ /dev/null @@ -1,133 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.core; - -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.Activator; - -/** - * A checked exception indicating a recoverable error occurred while provisioning. - * The status provides a further description of the problem. - * - * @noextend This class is not intended to be subclassed by clients. - */ -public class ProvisionException extends CoreException { - private static final long serialVersionUID = 1L; - - //General and core status codes [0-1000] - /** - * Status code constant (value 1) for an uncategorized error. - */ - public static final int INTERNAL_ERROR = 1; - - //Repository status codes [1000-1999] - //General repository codes [1000-1099] - /** - * Status code constant (value 1000) indicating a repository - * unexpectedly does not exist. - */ - public static final int REPOSITORY_NOT_FOUND = 1000; - - /** - * Status code constant (value 1001) indicating a repository - * unexpectedly exists. - */ - public static final int REPOSITORY_EXISTS = 1001; - - /** - * Status code constant (value 1002) indicating a repository - * could not be read - */ - public static final int REPOSITORY_FAILED_READ = 1002; - - /** - * Status code constant (value 1003) indicating a failure occurred - * while writing to a repository. - */ - public static final int REPOSITORY_FAILED_WRITE = 1003; - - /** - * Status code constant (value 1004) indicating a repository - * could not be written because it is a read-only repository. - */ - public static final int REPOSITORY_READ_ONLY = 1004; - - /** - * Status code constant (value 1005) indicating an attempt was - * made to create or access a repository of unknown type. - */ - public static final int REPOSITORY_UNKNOWN_TYPE = 1005; - /** - * Status code constant (value 1006) indicating that a specified - * repository location is not valid. - */ - public static final int REPOSITORY_INVALID_LOCATION = 1006; - - /** - * Status code constant (value 1007) indicating that there was - * an authentication error while reading a repository - */ - public static final int REPOSITORY_FAILED_AUTHENTICATION = 1007; - - //Metadata repository codes [1100-1199] - - //Artifact repository codes [1200-1299] - - /** - * Status code constant (value 1200) indicating an artifact unexpectedly - * does not exist. - */ - public static final int ARTIFACT_NOT_FOUND = 1200; - - /** - * Status code constant (value 1201) indicating an artifact unexpectedly - * already exists. - */ - public static final int ARTIFACT_EXISTS = 1201; - - /** - * Status code constant (value 1202) indicating an artifact's size - * could not be found. - */ - public static final int ARTIFACT_INCOMPLETE_SIZING = 1202; - - /** - * Creates a new exception with the given status object. The message - * of the given status is used as the exception message. - * - * @param status the status object to be associated with this exception - */ - public ProvisionException(IStatus status) { - super(status); - } - - /** - * Creates a new exception with the given message and a severity of - * {@link IStatus#ERROR}. - * - * @param message The human-readable problem message - */ - public ProvisionException(String message) { - super(new Status(IStatus.ERROR, Activator.ID, message)); - } - - /** - * Creates a new exception with the given message and cause, and - * a severity of {@link IStatus#ERROR}. - * - * @param message The human-readable problem message - * @param cause The underlying cause of the exception - */ - public ProvisionException(String message, Throwable cause) { - super(new Status(IStatus.ERROR, Activator.ID, message, cause)); - } - -} diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/provisional/p2/core/location/AgentLocation.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/provisional/p2/core/location/AgentLocation.java deleted file mode 100644 index aacd84ac4..000000000 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/provisional/p2/core/location/AgentLocation.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.core.location; - -import java.net.URI; -import java.net.URL; - -public interface AgentLocation { - public static final String SERVICE_NAME = AgentLocation.class.getName(); - - public URI getArtifactRepositoryURI(); - - public URI getMetadataRepositoryURI(); - - /** - * Returns the location where the bundle with the given namespace - * may write its agent-related data. - * @param namespace The namespace of the bundle storing the data - * @return The data location - */ - public URL getDataArea(String namespace); - - /** - * Returns the actual {@link URL} of this location. If the location's value has been set, - * that value is returned. If the value is not set and the location allows defaults, - * the value is set to the default and returned. In all other cases null - * is returned. - * - * @return the URL for this location or null if none - */ - public URL getURL(); - -} diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/IAgentLocation.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/IAgentLocation.java new file mode 100644 index 000000000..13b18ab3a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/IAgentLocation.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.core; + +import java.net.URI; + +/** + * An instance of this service represents the location of a provisioning agent's + * metadata. + * + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface IAgentLocation { + /** + * Service name constant for the agent location service. + */ + public static final String SERVICE_NAME = IAgentLocation.class.getName(); + + /** + * Returns the location where the bundle with the given namespace + * may write its agent-related data. + * @param namespace The namespace of the bundle storing the data + * @return The data location + */ + public URI getDataArea(String namespace); + + /** + * Returns the root {@link URI} of the agent metadata. + * + * @return the location of the agent metadata + */ + public URI getRootLocation(); + +} diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/IProvisioningAgent.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/IProvisioningAgent.java index 6bcada44b..52e9470aa 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/IProvisioningAgent.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/IProvisioningAgent.java @@ -25,9 +25,30 @@ import org.eclipse.equinox.p2.core.spi.IAgentServiceFactory; *

* @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. - * @since 1.1 + * @since 2.0 */ public interface IProvisioningAgent { + /** + * Service name constant for the agent service. Note that an agent obtained directly + * as a service typically represents the agent of the currently running system. To + * obtain an agent for a different system the {@link IProvisioningAgentProvider} + * service must be used. + */ + public static final String SERVICE_NAME = IProvisioningAgent.class.getName(); + + /** + * Service property identifying whether an agent is the default agent. + * + *

+ * This property may be used by clients wishing to obtain or track the + * provisioning agent for the currently running system. When the value of + * this property is "true" then the corresponding service is + * the agent for the currently running system. If the property is undefined or + * has any other value, then the service is not the agent for the currently running system. + *

+ */ + public static final String SERVICE_CURRENT = "agent.current"; //$NON-NLS-1$ + /** * Returns the service with the given service name, or null * if no such service is available in this agent. @@ -42,6 +63,18 @@ public interface IProvisioningAgent { */ public void registerService(String serviceName, Object service); + /** + * Stops the provisioning agent. This causes services provided by this + * agent to be cleaned up and discarded. No services provided by the agent + * should be referenced after the agent has been stopped, and subsequent + * attempts to obtain services after the agent has stopped will fail. + *

+ * An agent should only be stopped by the client who first created the agent + * by invoking {@link IProvisioningAgentProvider#createAgent(java.net.URI)}. + *

+ */ + public void stop(); + /** * Unregisters a service that has previously been registered with this * agent via {@link #registerService(String, Object)}. This method has diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/IProvisioningAgentProvider.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/IProvisioningAgentProvider.java index b3067c00c..462b56d60 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/IProvisioningAgentProvider.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/IProvisioningAgentProvider.java @@ -11,12 +11,11 @@ package org.eclipse.equinox.p2.core; import java.net.URI; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; /** * A service that is used to create or obtain instances of an * {@link IProvisioningAgent}. - * @since 1.1 + * @since 2.0 */ public interface IProvisioningAgentProvider { @@ -31,7 +30,10 @@ public interface IProvisioningAgentProvider { * currently running system is returned, if available. If a null * location is provided and the currently running system has not been provisioned * by any known agent, null is returned. - * + *

+ * Callers of this method are responsible for stopping the agent + * when they are finished using it by invoking {@link IProvisioningAgent#stop()}. + *

* @param location The location where the agent metadata is stored * @return A provisioning agent, or null if a null * parameter is provided an there is no currently running agent. @@ -39,6 +41,7 @@ public interface IProvisioningAgentProvider { *
    *
  • The location is not writeable.
  • *
+ * @see IProvisioningAgent#stop() */ public IProvisioningAgent createAgent(URI location) throws ProvisionException; } diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/ProvisionException.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/ProvisionException.java new file mode 100644 index 000000000..af5b6786a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/ProvisionException.java @@ -0,0 +1,134 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.core; + +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.core.Activator; + +/** + * A checked exception indicating a recoverable error occurred while provisioning. + * The status provides a further description of the problem. + * + * @noextend This class is not intended to be subclassed by clients. + * @since 2.0 + */ +public class ProvisionException extends CoreException { + private static final long serialVersionUID = 1L; + + //General and core status codes [0-1000] + /** + * Status code constant (value 1) for an uncategorized error. + */ + public static final int INTERNAL_ERROR = 1; + + //Repository status codes [1000-1999] + //General repository codes [1000-1099] + /** + * Status code constant (value 1000) indicating a repository + * unexpectedly does not exist. + */ + public static final int REPOSITORY_NOT_FOUND = 1000; + + /** + * Status code constant (value 1001) indicating a repository + * unexpectedly exists. + */ + public static final int REPOSITORY_EXISTS = 1001; + + /** + * Status code constant (value 1002) indicating a repository + * could not be read + */ + public static final int REPOSITORY_FAILED_READ = 1002; + + /** + * Status code constant (value 1003) indicating a failure occurred + * while writing to a repository. + */ + public static final int REPOSITORY_FAILED_WRITE = 1003; + + /** + * Status code constant (value 1004) indicating a repository + * could not be written because it is a read-only repository. + */ + public static final int REPOSITORY_READ_ONLY = 1004; + + /** + * Status code constant (value 1005) indicating an attempt was + * made to create or access a repository of unknown type. + */ + public static final int REPOSITORY_UNKNOWN_TYPE = 1005; + /** + * Status code constant (value 1006) indicating that a specified + * repository location is not valid. + */ + public static final int REPOSITORY_INVALID_LOCATION = 1006; + + /** + * Status code constant (value 1007) indicating that there was + * an authentication error while reading a repository + */ + public static final int REPOSITORY_FAILED_AUTHENTICATION = 1007; + + //Metadata repository codes [1100-1199] + + //Artifact repository codes [1200-1299] + + /** + * Status code constant (value 1200) indicating an artifact unexpectedly + * does not exist. + */ + public static final int ARTIFACT_NOT_FOUND = 1200; + + /** + * Status code constant (value 1201) indicating an artifact unexpectedly + * already exists. + */ + public static final int ARTIFACT_EXISTS = 1201; + + /** + * Status code constant (value 1202) indicating an artifact's size + * could not be found. + */ + public static final int ARTIFACT_INCOMPLETE_SIZING = 1202; + + /** + * Creates a new exception with the given status object. The message + * of the given status is used as the exception message. + * + * @param status the status object to be associated with this exception + */ + public ProvisionException(IStatus status) { + super(status); + } + + /** + * Creates a new exception with the given message and a severity of + * {@link IStatus#ERROR}. + * + * @param message The human-readable problem message + */ + public ProvisionException(String message) { + super(new Status(IStatus.ERROR, Activator.ID, message)); + } + + /** + * Creates a new exception with the given message and cause, and + * a severity of {@link IStatus#ERROR}. + * + * @param message The human-readable problem message + * @param cause The underlying cause of the exception + */ + public ProvisionException(String message, Throwable cause) { + super(new Status(IStatus.ERROR, Activator.ID, message, cause)); + } + +} diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/spi/IAgentServiceFactory.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/spi/IAgentServiceFactory.java index 8fd467b67..0c1b7de12 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/spi/IAgentServiceFactory.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/p2/core/spi/IAgentServiceFactory.java @@ -16,7 +16,7 @@ import org.eclipse.equinox.p2.core.IProvisioningAgent; * A factory for creating a service that forms part of a provisioning agent instance. * Factories themselves are registered in the OSGi service registry so that they * can be obtained by a provisioning agent. - * @since 1.1 + * @since 2.0 */ public interface IAgentServiceFactory { /** diff --git a/bundles/org.eclipse.equinox.p2.director.app/.classpath b/bundles/org.eclipse.equinox.p2.director.app/.classpath index 75116d75c..834ea833e 100644 --- a/bundles/org.eclipse.equinox.p2.director.app/.classpath +++ b/bundles/org.eclipse.equinox.p2.director.app/.classpath @@ -1,6 +1,6 @@ - + diff --git a/bundles/org.eclipse.equinox.p2.director.app/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.director.app/.settings/org.eclipse.jdt.core.prefs index 802d3818a..2c6d536a4 100644 --- a/bundles/org.eclipse.equinox.p2.director.app/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.director.app/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Wed Oct 07 15:35:11 EDT 2009 +#Mon Dec 28 07:04:08 CET 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.builder.cleanOutputFolder=clean org.eclipse.jdt.core.builder.duplicateResourceTask=warning @@ -8,17 +8,17 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning org.eclipse.jdt.core.compiler.problem.deadCode=warning @@ -27,7 +27,7 @@ org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=warning @@ -90,7 +90,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enab org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 diff --git a/bundles/org.eclipse.equinox.p2.director.app/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.director.app/META-INF/MANIFEST.MF index d11686979..a40324f0f 100644 --- a/bundles/org.eclipse.equinox.p2.director.app/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.director.app/META-INF/MANIFEST.MF @@ -4,19 +4,23 @@ Bundle-SymbolicName: org.eclipse.equinox.p2.director.app;singleton:=true Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-Localization: plugin -Bundle-Version: 1.0.100.qualifier +Bundle-Version: 1.0.200.qualifier Import-Package: org.eclipse.equinox.app, org.eclipse.equinox.internal.p2.console, org.eclipse.equinox.internal.p2.core.helpers, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, + org.eclipse.equinox.internal.p2.metadata, + org.eclipse.equinox.internal.p2.metadata.query, org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.director, - org.eclipse.equinox.internal.provisional.p2.engine, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.p2.repository, org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.metadata, org.eclipse.osgi.framework.log, org.eclipse.osgi.service.environment, org.eclipse.osgi.util, @@ -24,7 +28,8 @@ Import-Package: org.eclipse.equinox.app, org.osgi.service.packageadmin Bundle-Activator: org.eclipse.equinox.internal.p2.director.app.Activator Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, - J2SE-1.4 +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 Require-Bundle: org.eclipse.equinox.common;bundle-version="[3.5.0,4.0.0)" Export-Package: org.eclipse.equinox.internal.p2.director.app;x-internal:=true diff --git a/bundles/org.eclipse.equinox.p2.director.app/build.properties b/bundles/org.eclipse.equinox.p2.director.app/build.properties index fd5507d03..d80a7ff0d 100644 --- a/bundles/org.eclipse.equinox.p2.director.app/build.properties +++ b/bundles/org.eclipse.equinox.p2.director.app/build.properties @@ -21,3 +21,5 @@ src.includes = about.html jars.compile.order=.,ant_tasks/director-ant.jar extra.ant_tasks/director-ant.jar = platform:/plugin/org.apache.ant jars.extra.classpath = platform:/plugin/org.apache.ant/lib/ant.jar +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.director.app/plugin.xml b/bundles/org.eclipse.equinox.p2.director.app/plugin.xml index d4294922f..6d9af373f 100644 --- a/bundles/org.eclipse.equinox.p2.director.app/plugin.xml +++ b/bundles/org.eclipse.equinox.p2.director.app/plugin.xml @@ -23,4 +23,11 @@ + + + + diff --git a/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/Application.java b/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/Application.java index e15e67d94..b12210335 100644 --- a/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/Application.java +++ b/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/Application.java @@ -12,9 +12,6 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.director.app; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.io.File; import java.net.URI; import java.net.URISyntaxException; @@ -25,13 +22,16 @@ import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.equinox.internal.p2.console.ProvisioningHelper; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.*; +import org.eclipse.equinox.internal.p2.metadata.query.LatestIUVersionQuery; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.framework.log.FrameworkLog; import org.eclipse.osgi.util.NLS; import org.osgi.framework.*; @@ -48,8 +48,6 @@ public class Application implements IApplication { static private final String ANT_PROPERTY_PREFIX = "${"; //$NON-NLS-1$ static private final String FLAVOR_DEFAULT = "tooling"; //$NON-NLS-1$ static private final String EXEMPLARY_SETUP = "org.eclipse.equinox.p2.exemplarysetup"; //$NON-NLS-1$ - static private final String FRAMEWORKADMIN_EQUINOX = "org.eclipse.equinox.frameworkadmin.equinox"; //$NON-NLS-1$ - static private final String SIMPLE_CONFIGURATOR_MANIPULATOR = "org.eclipse.equinox.simpleconfigurator.manipulator"; //$NON-NLS-1$ public static final int COMMAND_INSTALL = 0; public static final int COMMAND_UNINSTALL = 1; @@ -91,13 +89,13 @@ public class Application implements IApplication { throw new CoreException(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.Ambigous_Command, new Object[] {COMMAND_NAMES[cmd1], COMMAND_NAMES[cmd2]}))); } - private ProfileChangeRequest buildProvisioningRequest(IProfile profile, Collector roots, boolean install) { + private ProfileChangeRequest buildProvisioningRequest(IProfile profile, IQueryResult roots, boolean install) { ProfileChangeRequest request = new ProfileChangeRequest(profile); markRoots(request, roots); if (install) { - request.addInstallableUnits((IInstallableUnit[]) roots.toArray(IInstallableUnit.class)); + request.addInstallableUnits(roots); } else { - request.removeInstallableUnits((IInstallableUnit[]) roots.toArray(IInstallableUnit.class)); + request.removeInstallableUnits(roots); } return request; } @@ -119,7 +117,7 @@ public class Application implements IApplication { } private String getEnvironmentProperty() { - Properties values = new Properties(); + Map values = new HashMap(); if (os != null) values.put("osgi.os", os); //$NON-NLS-1$ if (nl != null) @@ -145,26 +143,22 @@ public class Application implements IApplication { if (flavor == null) flavor = System.getProperty("eclipse.p2.configurationFlavor", FLAVOR_DEFAULT); //$NON-NLS-1$ - Properties props = new Properties(); - props.setProperty(IProfile.PROP_INSTALL_FOLDER, destination.toOSString()); - props.setProperty(IProfile.PROP_FLAVOR, flavor); + Map props = new HashMap(); + props.put(IProfile.PROP_INSTALL_FOLDER, destination.toOSString()); if (bundlePool == null || bundlePool.equals(Messages.destination_commandline)) - props.setProperty(IProfile.PROP_CACHE, destination.toOSString()); + props.put(IProfile.PROP_CACHE, destination.toOSString()); else - props.setProperty(IProfile.PROP_CACHE, bundlePool); + props.put(IProfile.PROP_CACHE, bundlePool); if (roamingProfile) - props.setProperty(IProfile.PROP_ROAMING, Boolean.TRUE.toString()); + props.put(IProfile.PROP_ROAMING, Boolean.TRUE.toString()); String env = getEnvironmentProperty(); if (env != null) - props.setProperty(IProfile.PROP_ENVIRONMENTS, env); + props.put(IProfile.PROP_ENVIRONMENTS, env); if (profileProperties != null) { putProperties(profileProperties, props); } profile = ProvisioningHelper.addProfile(profileId, props); - String currentFlavor = profile.getProperty(IProfile.PROP_FLAVOR); - if (currentFlavor != null && !currentFlavor.endsWith(flavor)) - throw new RuntimeException(NLS.bind("Install flavor {0} not consistent with profile flavor {1}", flavor, currentFlavor)); //$NON-NLS-1$ } return profile; } @@ -174,7 +168,15 @@ public class Application implements IApplication { if (throwException) missingArgument("artifactRepository"); //$NON-NLS-1$ } else { - artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); + artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); + if (artifactManager == null) { + IProvisioningAgent agent = (IProvisioningAgent) ServiceHelper.getService(Activator.getContext(), IProvisioningAgent.SERVICE_CURRENT); + if (agent == null) { + IProvisioningAgentProvider provider = (IProvisioningAgentProvider) ServiceHelper.getService(Activator.getContext(), IProvisioningAgentProvider.SERVICE_NAME); + agent = provider.createAgent(null); + } + artifactManager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME); + } if (artifactManager == null) { if (throwException) throw new ProvisionException(Messages.Application_NoManager); @@ -204,7 +206,7 @@ public class Application implements IApplication { if (throwException) missingArgument("metadataRepository"); //$NON-NLS-1$ } else { - metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); if (metadataManager == null) { if (throwException) throw new ProvisionException(Messages.Application_NoManager); @@ -232,11 +234,11 @@ public class Application implements IApplication { } private void initializeServices() { - IDirector director = (IDirector) ServiceHelper.getService(Activator.getContext(), IDirector.class.getName()); + IDirector director = (IDirector) ServiceHelper.getService(Activator.getContext(), IDirector.SERVICE_NAME); if (director == null) throw new RuntimeException(Messages.Missing_director); - planner = (IPlanner) ServiceHelper.getService(Activator.getContext(), IPlanner.class.getName()); + planner = (IPlanner) ServiceHelper.getService(Activator.getContext(), IPlanner.SERVICE_NAME); if (planner == null) throw new RuntimeException(Messages.Missing_planner); @@ -245,9 +247,9 @@ public class Application implements IApplication { throw new RuntimeException(Messages.Missing_Engine); } - private void markRoots(ProfileChangeRequest request, Collector roots) { - for (Iterator iterator = roots.iterator(); iterator.hasNext();) { - request.setInstallableUnitProfileProperty((IInstallableUnit) iterator.next(), IInstallableUnit.PROP_PROFILE_ROOT_IU, Boolean.TRUE.toString()); + private void markRoots(ProfileChangeRequest request, IQueryResult roots) { + for (Iterator iterator = roots.iterator(); iterator.hasNext();) { + request.setInstallableUnitProfileProperty(iterator.next(), IProfile.PROP_PROFILE_ROOT_IU, Boolean.TRUE.toString()); } } @@ -256,7 +258,7 @@ public class Application implements IApplication { } private IStatus planAndExecute(IProfile profile, ProvisioningContext context, ProfileChangeRequest request) { - ProvisioningPlan result; + IProvisioningPlan result; IStatus operationStatus; result = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); if (!result.getStatus().isOK()) @@ -345,7 +347,7 @@ public class Application implements IApplication { if (opt.equalsIgnoreCase("-version")) { //$NON-NLS-1$ if (arg != null && !arg.startsWith(ANT_PROPERTY_PREFIX)) - version = new Version(arg); + version = Version.create(arg); } if (opt.equalsIgnoreCase(COMMAND_NAMES[COMMAND_UNINSTALL])) { @@ -375,7 +377,7 @@ public class Application implements IApplication { * @param pairs a comma separated list of tag=value pairs * @param properties the collection into which the pairs are put */ - private void putProperties(String pairs, Properties properties) { + private void putProperties(String pairs, Map properties) { StringTokenizer tok = new StringTokenizer(pairs, ",", true); //$NON-NLS-1$ while (tok.hasMoreTokens()) { String next = tok.nextToken().trim(); @@ -391,14 +393,14 @@ public class Application implements IApplication { } public Object run(String[] args) throws Exception { - System.out.println("This application is deprecated. Please use the org.eclipse.equinox.p2.director application."); + System.out.println(Messages.Deprecated_application); long time = -System.currentTimeMillis(); initializeServices(); processArguments(args); IStatus operationStatus = Status.OK_STATUS; InstallableUnitQuery query; - Collector roots; + IQueryResult roots; try { initializeRepositories(command == COMMAND_INSTALL); switch (command) { @@ -407,10 +409,10 @@ public class Application implements IApplication { IProfile profile = initializeProfile(); query = new InstallableUnitQuery(root, version == null ? VersionRange.emptyRange : new VersionRange(version, true, version, true)); - roots = collectRootIUs(metadataRepositoryLocations, new CompositeQuery(new Query[] {query, new LatestIUVersionQuery()}), new Collector()); - if (roots.size() <= 0) - roots = profile.query(query, roots, new NullProgressMonitor()); - if (roots.size() <= 0) { + roots = collectRootIUs(metadataRepositoryLocations, new PipedQuery(query, new LatestIUVersionQuery())); + if (roots.isEmpty()) + roots = profile.query(query, new NullProgressMonitor()); + if (roots.isEmpty()) { System.out.println(NLS.bind(Messages.Missing_IU, root)); logFailure(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.Missing_IU, root))); return EXIT_ERROR; @@ -443,10 +445,10 @@ public class Application implements IApplication { if (metadataRepositoryLocations == null) missingArgument("metadataRepository"); //$NON-NLS-1$ - roots = collectRootIUs(metadataRepositoryLocations, query, null); - Iterator unitIterator = roots.iterator(); + roots = collectRootIUs(metadataRepositoryLocations, query); + Iterator unitIterator = roots.iterator(); while (unitIterator.hasNext()) { - IInstallableUnit iu = (IInstallableUnit) unitIterator.next(); + IInstallableUnit iu = unitIterator.next(); System.out.println(iu.getId()); } break; @@ -479,30 +481,28 @@ public class Application implements IApplication { } } - class LocationQueryable implements IQueryable { + class LocationQueryable implements IQueryable { private URI location; public LocationQueryable(URI location) { this.location = location; } - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - return ProvisioningHelper.getInstallableUnits(location, query, collector, monitor); + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return ProvisioningHelper.getInstallableUnits(location, query, monitor); } } - private Collector collectRootIUs(URI[] locations, Query query, Collector collector) { + private IQueryResult collectRootIUs(URI[] locations, IQuery query) { IProgressMonitor nullMonitor = new NullProgressMonitor(); if (locations == null || locations.length == 0) - return ProvisioningHelper.getInstallableUnits(null, query, collector, nullMonitor); + return ProvisioningHelper.getInstallableUnits((URI) null, query, nullMonitor); - Collector result = collector != null ? collector : new Collector(); - IQueryable[] locationQueryables = new IQueryable[locations.length]; - for (int i = 0; i < locations.length; i++) { - locationQueryables[i] = new LocationQueryable(locations[i]); - } - return new CompoundQueryable(locationQueryables).query(query, result, nullMonitor); + List> locationQueryables = new ArrayList>(locations.length); + for (int i = 0; i < locations.length; i++) + locationQueryables.add(new LocationQueryable(locations[i])); + return new CompoundQueryable(locationQueryables).query(query, nullMonitor); } private synchronized void setPackageAdmin(PackageAdmin service) { @@ -513,6 +513,7 @@ public class Application implements IApplication { Bundle bundle = getBundle(bundleName); if (bundle == null) return false; + bundle.start(Bundle.START_ACTIVATION_POLICY); bundle.start(Bundle.START_TRANSIENT); return true; } @@ -524,15 +525,6 @@ public class Application implements IApplication { logFailure(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.Missing_bundle, EXEMPLARY_SETUP))); return EXIT_ERROR; } - if (!startEarly(SIMPLE_CONFIGURATOR_MANIPULATOR)) { - logFailure(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.Missing_bundle, SIMPLE_CONFIGURATOR_MANIPULATOR))); - return EXIT_ERROR; - } - if (!startEarly(FRAMEWORKADMIN_EQUINOX)) { - logFailure(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.Missing_bundle, FRAMEWORKADMIN_EQUINOX))); - return EXIT_ERROR; - } - return run((String[]) context.getArguments().get("application.args")); //$NON-NLS-1$ } @@ -541,15 +533,17 @@ public class Application implements IApplication { Activator.getContext().ungetService(packageAdminRef); } - private String toString(Properties context) { + private String toString(Map context) { StringBuffer result = new StringBuffer(); - for (Enumeration iter = context.keys(); iter.hasMoreElements();) { - String key = (String) iter.nextElement(); + boolean first = true; + for (String key : context.keySet()) { + if (first) + first = false; + else + result.append(','); result.append(key); result.append('='); result.append(context.get(key)); - if (iter.hasMoreElements()) - result.append(','); } return result.toString(); } @@ -586,7 +580,7 @@ public class Application implements IApplication { ProvisioningContext context = new ProvisioningContext(new URI[0]); context.setArtifactRepositories(new URI[0]); - ProvisioningPlan result = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); + IProvisioningPlan result = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); return PlanExecutionHelper.executePlan(result, engine, context, new NullProgressMonitor()); } @@ -598,7 +592,7 @@ public class Application implements IApplication { request.setProfileProperty(IProfile.PROP_ROAMING, "true"); //$NON-NLS-1$ ProvisioningContext context = new ProvisioningContext(new URI[0]); context.setArtifactRepositories(new URI[0]); - ProvisioningPlan result = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); + IProvisioningPlan result = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); return PlanExecutionHelper.executePlan(result, engine, context, new NullProgressMonitor()); } @@ -606,7 +600,7 @@ public class Application implements IApplication { if (spec == null) return null; String[] urlSpecs = getArrayFromString(spec, ","); //$NON-NLS-1$ - ArrayList result = new ArrayList(urlSpecs.length); + ArrayList result = new ArrayList(urlSpecs.length); for (int i = 0; i < urlSpecs.length; i++) { try { result.add(URIUtil.fromString(urlSpecs[i])); @@ -616,7 +610,7 @@ public class Application implements IApplication { } if (result.size() == 0) return null; - return (URI[]) result.toArray(new URI[result.size()]); + return result.toArray(new URI[result.size()]); } /** @@ -626,13 +620,13 @@ public class Application implements IApplication { public static String[] getArrayFromString(String list, String separator) { if (list == null || list.trim().equals("")) //$NON-NLS-1$ return new String[0]; - List result = new ArrayList(); + List result = new ArrayList(); for (StringTokenizer tokens = new StringTokenizer(list, separator); tokens.hasMoreTokens();) { String token = tokens.nextToken().trim(); if (!token.equals("")) //$NON-NLS-1$ result.add(token); } - return (String[]) result.toArray(new String[result.size()]); + return result.toArray(new String[result.size()]); } private void logFailure(IStatus status) { diff --git a/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/DirectorApplication.java b/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/DirectorApplication.java index 1823b20f4..992aa1ef0 100644 --- a/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/DirectorApplication.java +++ b/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/DirectorApplication.java @@ -16,19 +16,22 @@ import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.util.*; +import java.util.Map.Entry; import org.eclipse.core.runtime.*; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; -import org.eclipse.equinox.internal.p2.console.ProvisioningHelper; import org.eclipse.equinox.internal.p2.core.helpers.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.internal.p2.metadata.VersionedId; +import org.eclipse.equinox.internal.p2.metadata.query.LatestIUVersionQuery; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.framework.log.FrameworkLog; import org.eclipse.osgi.service.environment.EnvironmentInfo; import org.eclipse.osgi.util.NLS; @@ -42,15 +45,16 @@ import org.osgi.service.packageadmin.PackageAdmin; * p2 data location. See bug 268138 for related discussion. */ public class DirectorApplication implements IApplication { - class LocationQueryable implements IQueryable { + class LocationQueryable implements IQueryable { private URI location; public LocationQueryable(URI location) { this.location = location; + Assert.isNotNull(location); } - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - return ProvisioningHelper.getInstallableUnits(location, query, collector, monitor); + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return getInstallableUnits(location, query, monitor); } } @@ -110,20 +114,13 @@ public class DirectorApplication implements IApplication { private static final CommandLineOption OPTION_P2_ARCH = new CommandLineOption(new String[] {"-p2.arch"}, null, Messages.Help_The_ARCH_when_profile_is_created); //$NON-NLS-1$ private static final CommandLineOption OPTION_P2_NL = new CommandLineOption(new String[] {"-p2.nl"}, null, Messages.Help_The_NL_when_profile_is_created); //$NON-NLS-1$ - static private final String BUNDLE_CORE = "org.eclipse.equinox.p2.core"; //$NON-NLS-1$ - static private final String BUNDLE_ENGINE = "org.eclipse.equinox.p2.engine"; //$NON-NLS-1$ - static private final String BUNDLE_EXEMPLARY_SETUP = "org.eclipse.equinox.p2.exemplarysetup"; //$NON-NLS-1$ - static private final String BUNDLE_FRAMEWORKADMIN_EQUINOX = "org.eclipse.equinox.frameworkadmin.equinox"; //$NON-NLS-1$ - static private final String BUNDLE_SIMPLE_CONFIGURATOR_MANIPULATOR = "org.eclipse.equinox.simpleconfigurator.manipulator"; //$NON-NLS-1$ private static final Integer EXIT_ERROR = new Integer(13); static private final String FLAVOR_DEFAULT = "tooling"; //$NON-NLS-1$ - static private final String PROP_P2_DATA_AREA = "eclipse.p2.data.area"; //$NON-NLS-1$ - static private final String PROP_P2_PROFILE = "eclipse.p2.profile"; //$NON-NLS-1$ public static final String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$ - private static void getURIs(List uris, String spec) throws CoreException { + private static void getURIs(List uris, String spec) throws CoreException { if (spec == null) return; String[] urlSpecs = StringHelper.getArrayFromString(spec, ','); @@ -156,35 +153,35 @@ public class DirectorApplication implements IApplication { return null; } - private static void parseIUsArgument(List vnames, String arg) { + private static void parseIUsArgument(List vnames, String arg) { String[] roots = StringHelper.getArrayFromString(arg, ','); for (int i = 0; i < roots.length; ++i) vnames.add(VersionedId.parse(roots[i])); } - private static String processFileArgument(String arg) { + private static File processFileArgument(String arg) { if (arg.startsWith("file:")) //$NON-NLS-1$ arg = arg.substring(5); // we create a path object here to handle ../ entries in the middle of paths - return Path.fromOSString(arg).toOSString(); + return Path.fromOSString(arg).toFile(); } private IArtifactRepositoryManager artifactManager; - private IMetadataRepositoryManager metadataManager; + IMetadataRepositoryManager metadataManager; private URI[] artifactReposForRemoval; private URI[] metadataReposForRemoval; - private final List artifactRepositoryLocations = new ArrayList(); - private final List metadataRepositoryLocations = new ArrayList(); - private final List rootsToInstall = new ArrayList(); - private final List rootsToUninstall = new ArrayList(); - private final List rootsToList = new ArrayList(); + private final List artifactRepositoryLocations = new ArrayList(); + private final List metadataRepositoryLocations = new ArrayList(); + private final List rootsToInstall = new ArrayList(); + private final List rootsToUninstall = new ArrayList(); + private final List rootsToList = new ArrayList(); - private String bundlePool = null; - private String destination; - private String sharedLocation; + private File bundlePool = null; + private File destination; + private File sharedLocation; private String flavor; private boolean printHelpInfo = false; private boolean printIUList = false; @@ -204,12 +201,9 @@ public class DirectorApplication implements IApplication { private PackageAdmin packageAdmin; private ServiceReference packageAdminRef; private IPlanner planner; + private ILog log = null; - private String preservedDataArea; - private String preservedProfile; - private boolean restartCore; - private boolean restartEngine; - private boolean restartExemplarySetup; + private IProvisioningAgent agent; private ProfileChangeRequest buildProvisioningRequest(IProfile profile, IInstallableUnit[] installs, IInstallableUnit[] uninstalls) { ProfileChangeRequest request = new ProfileChangeRequest(profile); @@ -233,40 +227,41 @@ public class DirectorApplication implements IApplication { } } - private Collector collectRootIUs(Query query, Collector collector) { + private IQueryResult collectRootIUs(IQuery query) { IProgressMonitor nullMonitor = new NullProgressMonitor(); int top = metadataRepositoryLocations.size(); if (top == 0) - return ProvisioningHelper.getInstallableUnits(null, query, collector, nullMonitor); + return getInstallableUnits(null, query, nullMonitor); - Collector result = collector != null ? collector : new Collector(); - IQueryable[] locationQueryables = new IQueryable[top]; + List> locationQueryables = new ArrayList>(top); for (int i = 0; i < top; i++) - locationQueryables[i] = new LocationQueryable((URI) metadataRepositoryLocations.get(i)); - return new CompoundQueryable(locationQueryables).query(query, result, nullMonitor); + locationQueryables.add(new LocationQueryable(metadataRepositoryLocations.get(i))); + return new CompoundQueryable(locationQueryables).query(query, nullMonitor); } - private IInstallableUnit[] collectRoots(IProfile profile, List rootNames, boolean forInstall) throws CoreException { - ArrayList allRoots = new ArrayList(); + private IInstallableUnit[] collectRoots(IProfile profile, List rootNames, boolean forInstall) throws CoreException { + ArrayList allRoots = new ArrayList(); int top = rootNames.size(); for (int i = 0; i < top; ++i) { - IVersionedId rootName = (IVersionedId) rootNames.get(i); + IVersionedId rootName = rootNames.get(i); Version v = rootName.getVersion(); - Query query = new InstallableUnitQuery(rootName.getId(), Version.emptyVersion.equals(v) ? VersionRange.emptyRange : new VersionRange(v, true, v, true)); - Collector roots; + IQuery query = new InstallableUnitQuery(rootName.getId(), Version.emptyVersion.equals(v) ? VersionRange.emptyRange : new VersionRange(v, true, v, true)); + IQueryResult roots = null; if (forInstall) - roots = collectRootIUs(new CompositeQuery(new Query[] {query, new LatestIUVersionQuery()}), new Collector()); - else - roots = new Collector(); - if (roots.size() <= 0) - roots = profile.query(query, roots, new NullProgressMonitor()); - if (roots.size() <= 0) + roots = collectRootIUs(new PipedQuery(query, new LatestIUVersionQuery())); + + if (roots == null || roots.isEmpty()) + roots = profile.query(query, new NullProgressMonitor()); + + Iterator itor = roots.iterator(); + if (!itor.hasNext()) throw new CoreException(new Status(IStatus.ERROR, org.eclipse.equinox.internal.p2.director.app.Activator.ID, NLS.bind(Messages.Missing_IU, rootName))); - allRoots.addAll(roots.toCollection()); + do { + allRoots.add(itor.next()); + } while (itor.hasNext()); } - return (IInstallableUnit[]) allRoots.toArray(new IInstallableUnit[allRoots.size()]); - + return allRoots.toArray(new IInstallableUnit[allRoots.size()]); } synchronized Bundle getBundle(String symbolicName) { @@ -286,7 +281,7 @@ public class DirectorApplication implements IApplication { } private String getEnvironmentProperty() { - HashMap values = new HashMap(); + HashMap values = new HashMap(); if (os != null) values.put("osgi.os", os); //$NON-NLS-1$ if (nl != null) @@ -299,36 +294,33 @@ public class DirectorApplication implements IApplication { } private IProfile initializeProfile() throws CoreException { + IProfileRegistry profileRegistry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME); if (profileId == null) { profileId = IProfileRegistry.SELF; noProfileId = true; } - IProfile profile = ProvisioningHelper.getProfile(profileId); + IProfile profile = profileRegistry.getProfile(profileId); if (profile == null) { if (destination == null) missingArgument("destination"); //$NON-NLS-1$ if (flavor == null) flavor = System.getProperty("eclipse.p2.configurationFlavor", FLAVOR_DEFAULT); //$NON-NLS-1$ - Properties props = new Properties(); - props.setProperty(IProfile.PROP_INSTALL_FOLDER, destination); - props.setProperty(IProfile.PROP_FLAVOR, flavor); + Map props = new HashMap(); + props.put(IProfile.PROP_INSTALL_FOLDER, destination.toString()); if (bundlePool == null) - props.setProperty(IProfile.PROP_CACHE, sharedLocation == null ? destination : sharedLocation); + props.put(IProfile.PROP_CACHE, sharedLocation == null ? destination.getAbsolutePath() : sharedLocation.getAbsolutePath()); else - props.setProperty(IProfile.PROP_CACHE, bundlePool); + props.put(IProfile.PROP_CACHE, bundlePool.getAbsolutePath()); if (roamingProfile) - props.setProperty(IProfile.PROP_ROAMING, Boolean.TRUE.toString()); + props.put(IProfile.PROP_ROAMING, Boolean.TRUE.toString()); String env = getEnvironmentProperty(); if (env != null) - props.setProperty(IProfile.PROP_ENVIRONMENTS, env); + props.put(IProfile.PROP_ENVIRONMENTS, env); if (profileProperties != null) putProperties(profileProperties, props); - profile = ProvisioningHelper.addProfile(profileId, props); - String currentFlavor = profile.getProperty(IProfile.PROP_FLAVOR); - if (currentFlavor != null && !currentFlavor.endsWith(flavor)) - throw new RuntimeException(NLS.bind(Messages.flavor_0_inconsistent_with_flavor_1, flavor, currentFlavor)); + profile = profileRegistry.addProfile(profileId, props); } return profile; } @@ -337,11 +329,10 @@ public class DirectorApplication implements IApplication { if (rootsToInstall.isEmpty() && revertToPreviousState == -1) // Not much point initializing repositories if we have nothing to install return; - if (artifactRepositoryLocations == null) missingArgument("-artifactRepository"); //$NON-NLS-1$ - artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); + artifactManager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME); if (artifactManager == null) throw new ProvisionException(Messages.Application_NoManager); @@ -349,7 +340,7 @@ public class DirectorApplication implements IApplication { boolean anyValid = false; // do we have any valid repos or did they all fail to load? artifactReposForRemoval = new URI[artifactRepositoryLocations.size()]; for (int i = 0; i < artifactRepositoryLocations.size(); i++) { - URI location = (URI) artifactRepositoryLocations.get(i); + URI location = artifactRepositoryLocations.get(i); try { if (!artifactManager.contains(location)) { artifactManager.loadRepository(location, null); @@ -358,7 +349,7 @@ public class DirectorApplication implements IApplication { anyValid = true; } catch (ProvisionException e) { //one of the repositories did not load - LogHelper.log(e.getStatus()); + logStatus(e.getStatus()); } } if (!anyValid) @@ -368,7 +359,7 @@ public class DirectorApplication implements IApplication { if (metadataRepositoryLocations == null) missingArgument("metadataRepository"); //$NON-NLS-1$ - metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + metadataManager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME); if (metadataManager == null) throw new ProvisionException(Messages.Application_NoManager); @@ -377,7 +368,7 @@ public class DirectorApplication implements IApplication { int top = metadataRepositoryLocations.size(); metadataReposForRemoval = new URI[top]; for (int i = 0; i < top; i++) { - URI location = (URI) metadataRepositoryLocations.get(i); + URI location = metadataRepositoryLocations.get(i); try { if (!metadataManager.contains(location)) { metadataManager.loadRepository(location, null); @@ -386,7 +377,7 @@ public class DirectorApplication implements IApplication { anyValid = true; } catch (ProvisionException e) { //one of the repositories did not load - LogHelper.log(e.getStatus()); + logStatus(e.getStatus()); } } if (!anyValid) @@ -398,79 +389,85 @@ public class DirectorApplication implements IApplication { BundleContext context = Activator.getContext(); packageAdminRef = context.getServiceReference(PackageAdmin.class.getName()); packageAdmin = (PackageAdmin) context.getService(packageAdminRef); + ServiceReference agentProviderRef = context.getServiceReference(IProvisioningAgentProvider.SERVICE_NAME); + IProvisioningAgentProvider provider = (IProvisioningAgentProvider) context.getService(agentProviderRef); + URI p2DataArea; if (destination != null || sharedLocation != null) { - restartExemplarySetup = stopTransient(BUNDLE_EXEMPLARY_SETUP); - restartEngine = stopTransient(BUNDLE_ENGINE); // Since it uses the agent data location - restartCore = stopTransient(BUNDLE_CORE); // Since it manages the agent data location - - // Set/Clear properties that we don't want to inherit from the caller - String p2DataArea = sharedLocation == null ? new File(destination, "p2").getAbsolutePath() : sharedLocation; //$NON-NLS-1$ - preservedDataArea = System.setProperty(PROP_P2_DATA_AREA, p2DataArea); - if (profileId == null) { - if (destination != null) { - File configIni = new File(destination, "configuration/config.ini"); //$NON-NLS-1$ - InputStream in = null; - try { - Properties ciProps = new Properties(); - in = new BufferedInputStream(new FileInputStream(configIni)); - ciProps.load(in); - profileId = ciProps.getProperty(PROP_P2_PROFILE); - } catch (IOException e) { - // Ignore - } finally { - if (in != null) - try { - in.close(); - } catch (IOException e) { - // Ignore; - } - } - if (profileId == null) - profileId = destination; + File dataAreaFile = sharedLocation == null ? new File(destination, "p2") : sharedLocation;//$NON-NLS-1$ + p2DataArea = dataAreaFile.toURI(); + } else { + p2DataArea = null; + } + agent = provider.createAgent(p2DataArea); + context.ungetService(agentProviderRef); + if (profileId == null) { + if (destination != null) { + File configIni = new File(destination, "configuration/config.ini"); //$NON-NLS-1$ + InputStream in = null; + try { + Properties ciProps = new Properties(); + in = new BufferedInputStream(new FileInputStream(configIni)); + ciProps.load(in); + profileId = ciProps.getProperty(PROP_P2_PROFILE); + } catch (IOException e) { + // Ignore + } finally { + if (in != null) + try { + in.close(); + } catch (IOException e) { + // Ignore; + } } + if (profileId == null) + profileId = destination.toString(); } - //note this condition is bogus but we currently rely on the property being - //cleared for the director to run successfully. See bug 295269 for details. - if (profileId == null) - preservedProfile = System.setProperty(PROP_P2_PROFILE, profileId); - else - preservedProfile = (String) System.getProperties().remove(PROP_P2_PROFILE); } + if (profileId != null) + agent.registerService(PROP_P2_PROFILE, profileId); + else + agent.unregisterService(PROP_P2_PROFILE, null); - if (!startTransient(BUNDLE_SIMPLE_CONFIGURATOR_MANIPULATOR)) - throw new ProvisionException(NLS.bind(Messages.Missing_bundle, BUNDLE_SIMPLE_CONFIGURATOR_MANIPULATOR)); - if (!startTransient(BUNDLE_FRAMEWORKADMIN_EQUINOX)) - throw new ProvisionException(NLS.bind(Messages.Missing_bundle, BUNDLE_FRAMEWORKADMIN_EQUINOX)); - if (!startTransient(BUNDLE_CORE)) - throw new ProvisionException(NLS.bind(Messages.Missing_bundle, BUNDLE_CORE)); - if (!startTransient(BUNDLE_ENGINE)) - throw new ProvisionException(NLS.bind(Messages.Missing_bundle, BUNDLE_ENGINE)); - if (!startTransient(BUNDLE_EXEMPLARY_SETUP)) - throw new ProvisionException(NLS.bind(Messages.Missing_bundle, BUNDLE_EXEMPLARY_SETUP)); - - IDirector director = (IDirector) ServiceHelper.getService(context, IDirector.class.getName()); + IDirector director = (IDirector) agent.getService(IDirector.SERVICE_NAME); if (director == null) throw new ProvisionException(Messages.Missing_director); - planner = (IPlanner) ServiceHelper.getService(context, IPlanner.class.getName()); + planner = (IPlanner) agent.getService(IPlanner.SERVICE_NAME); if (planner == null) throw new ProvisionException(Messages.Missing_planner); - engine = (IEngine) ServiceHelper.getService(context, IEngine.SERVICE_NAME); + engine = (IEngine) agent.getService(IEngine.SERVICE_NAME); if (engine == null) throw new ProvisionException(Messages.Missing_Engine); } - private void logFailure(IStatus status) { - FrameworkLog log = (FrameworkLog) ServiceHelper.getService(Activator.getContext(), FrameworkLog.class.getName()); + private void logStatus(IStatus status) { if (log != null) - System.err.println("Application failed, log file location: " + log.getFile()); //$NON-NLS-1$ - LogHelper.log(status); + log.log(status); + else + LogHelper.log(status); + } + + private void printMessage(String message) { + if (log != null) + log.log(message); + else + System.out.println(message); + } + + private void logFailure(IStatus status) { + if (log == null) { + FrameworkLog frameworkLog = (FrameworkLog) ServiceHelper.getService(Activator.getContext(), FrameworkLog.class.getName()); + if (frameworkLog != null) + System.err.println("Application failed, log file location: " + frameworkLog.getFile()); //$NON-NLS-1$ + } + + logStatus(status); } private void markRoots(ProfileChangeRequest request, IInstallableUnit[] roots) { for (int idx = 0; idx < roots.length; ++idx) - request.setInstallableUnitProfileProperty(roots[idx], IInstallableUnit.PROP_PROFILE_ROOT_IU, Boolean.TRUE.toString()); + request.setInstallableUnitProfileProperty(roots[idx], IProfile.PROP_PROFILE_ROOT_IU, Boolean.TRUE.toString()); } private void missingArgument(String argumentName) throws CoreException { @@ -481,25 +478,23 @@ public class DirectorApplication implements IApplication { if (metadataRepositoryLocations.isEmpty()) missingArgument("metadataRepository"); //$NON-NLS-1$ - ArrayList allRoots = new ArrayList(); + ArrayList allRoots = new ArrayList(); if (rootsToList.size() == 0) { - Collector roots = collectRootIUs(InstallableUnitQuery.ANY, null); - allRoots.addAll(roots.toCollection()); + Iterator roots = collectRootIUs(InstallableUnitQuery.ANY).iterator(); + while (roots.hasNext()) + allRoots.add(roots.next()); } else { - Iterator r = rootsToList.iterator(); - while (r.hasNext()) { - IVersionedId rootName = (IVersionedId) r.next(); + for (IVersionedId rootName : rootsToList) { Version v = rootName.getVersion(); - Query query = new InstallableUnitQuery(rootName.getId(), Version.emptyVersion.equals(v) ? VersionRange.emptyRange : new VersionRange(v, true, v, true)); - Collector roots = collectRootIUs(query, null); - allRoots.addAll(roots.toCollection()); + IQuery query = new InstallableUnitQuery(rootName.getId(), Version.emptyVersion.equals(v) ? VersionRange.emptyRange : new VersionRange(v, true, v, true)); + Iterator roots = collectRootIUs(query).iterator(); + while (roots.hasNext()) + allRoots.add(roots.next()); } } Collections.sort(allRoots); - Iterator i = allRoots.iterator(); - while (i.hasNext()) { - IInstallableUnit iu = (IInstallableUnit) i.next(); + for (IInstallableUnit iu : allRoots) { System.out.println(iu.getId() + '=' + iu.getVersion()); } } @@ -513,8 +508,8 @@ public class DirectorApplication implements IApplication { boolean wasRoaming = Boolean.valueOf(profile.getProperty(IProfile.PROP_ROAMING)).booleanValue(); try { updateRoamingProperties(profile); - ProvisioningContext context = new ProvisioningContext((URI[]) metadataRepositoryLocations.toArray(new URI[metadataRepositoryLocations.size()])); - context.setArtifactRepositories((URI[]) artifactRepositoryLocations.toArray(new URI[artifactRepositoryLocations.size()])); + ProvisioningContext context = new ProvisioningContext(metadataRepositoryLocations.toArray(new URI[metadataRepositoryLocations.size()])); + context.setArtifactRepositories(artifactRepositoryLocations.toArray(new URI[artifactRepositoryLocations.size()])); ProfileChangeRequest request = buildProvisioningRequest(profile, installs, uninstalls); printRequest(request); planAndExecute(profile, context, request); @@ -526,14 +521,14 @@ public class DirectorApplication implements IApplication { } private void planAndExecute(IProfile profile, ProvisioningContext context, ProfileChangeRequest request) throws CoreException { - ProvisioningPlan result = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); + IProvisioningPlan result = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); IStatus operationStatus = result.getStatus(); if (!operationStatus.isOK()) throw new CoreException(operationStatus); executePlan(context, result); } - private void executePlan(ProvisioningContext context, ProvisioningPlan result) throws CoreException { + private void executePlan(ProvisioningContext context, IProvisioningPlan result) throws CoreException { IStatus operationStatus; if (!verifyOnly) { operationStatus = PlanExecutionHelper.executePlan(result, engine, context, new NullProgressMonitor()); @@ -545,11 +540,11 @@ public class DirectorApplication implements IApplication { private void printRequest(ProfileChangeRequest request) { IInstallableUnit[] toAdd = request.getAddedInstallableUnits(); for (int i = 0; i < toAdd.length; i++) { - System.out.println(NLS.bind(Messages.Installing, toAdd[i].getId(), toAdd[i].getVersion())); + printMessage(NLS.bind(Messages.Installing, toAdd[i].getId(), toAdd[i].getVersion())); } IInstallableUnit[] toRemove = request.getRemovedInstallableUnits(); for (int i = 0; i < toRemove.length; i++) { - System.out.println(NLS.bind(Messages.Uninstalling, toRemove[i].getId(), toRemove[i].getVersion())); + printMessage(NLS.bind(Messages.Uninstalling, toRemove[i].getId(), toRemove[i].getVersion())); } } @@ -618,7 +613,7 @@ public class DirectorApplication implements IApplication { } if (sharedLocation == null) // -shared without an argument means "Use default shared area" - sharedLocation = Path.fromOSString(System.getProperty("user.home")).append(".p2/").toOSString(); //$NON-NLS-1$ //$NON-NLS-2$ + sharedLocation = Path.fromOSString(System.getProperty("user.home")).append(".p2/").toFile(); //$NON-NLS-1$ //$NON-NLS-2$ continue; } @@ -687,7 +682,7 @@ public class DirectorApplication implements IApplication { } if (!printHelpInfo && !printIUList && rootsToInstall.isEmpty() && rootsToUninstall.isEmpty() && revertToPreviousState == -1) { - System.out.println(Messages.Help_Missing_argument); + printMessage(Messages.Help_Missing_argument); printHelpInfo = true; } } @@ -696,7 +691,7 @@ public class DirectorApplication implements IApplication { * @param pairs a comma separated list of tag=value pairs * @param properties the collection into which the pairs are put */ - private void putProperties(String pairs, Properties properties) { + private void putProperties(String pairs, Map properties) { String[] propPairs = StringHelper.getArrayFromString(pairs, ','); for (int i = 0; i < propPairs.length; ++i) { String propPair = propPairs[i]; @@ -712,37 +707,18 @@ public class DirectorApplication implements IApplication { } } - private void restoreServices() throws CoreException { + private void cleanupServices() { BundleContext context = Activator.getContext(); - try { - if (destination == null && sharedLocation == null) - return; - - stopTransient(BUNDLE_EXEMPLARY_SETUP); - stopTransient(BUNDLE_CORE); // Since it manages the agent data location - - if (preservedDataArea != null) - System.setProperty(PROP_P2_DATA_AREA, preservedDataArea); - else - System.getProperties().remove(PROP_P2_DATA_AREA); - - if (preservedProfile != null) - System.setProperty(PROP_P2_PROFILE, preservedProfile); - else - System.getProperties().remove(PROP_P2_PROFILE); - - if (restartCore) - startTransient(BUNDLE_CORE); - if (restartEngine) - startTransient(BUNDLE_ENGINE); - if (restartExemplarySetup) - startTransient(BUNDLE_EXEMPLARY_SETUP); - } finally { - context.ungetService(packageAdminRef); + //dispose agent + if (agent != null) { + agent.stop(); + agent = null; } + if (packageAdminRef != null) + context.ungetService(packageAdminRef); } - public Object run(String[] args) throws CoreException { + public Object run(String[] args) { long time = System.currentTimeMillis(); try { @@ -758,10 +734,11 @@ public class DirectorApplication implements IApplication { performProvisioningActions(); if (printIUList) performList(); - System.out.println(NLS.bind(Messages.Operation_complete, new Long(System.currentTimeMillis() - time))); + printMessage(NLS.bind(Messages.Operation_complete, new Long(System.currentTimeMillis() - time))); } return IApplication.EXIT_OK; } catch (CoreException e) { + printMessage(Messages.Operation_failed); deeplyPrint(e.getStatus(), System.err, 0); logFailure(e.getStatus()); //set empty exit data to suppress error dialog from launcher @@ -770,14 +747,14 @@ public class DirectorApplication implements IApplication { } finally { if (packageAdminRef != null) { cleanupRepositories(); - restoreServices(); + cleanupServices(); } } } private void revertToPreviousState() throws CoreException { IProfile profile = initializeProfile(); - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(Activator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME); IProfile targetProfile = null; if (revertToPreviousState == 0) { long[] profiles = profileRegistry.listProfileTimestamps(profile.getProfileId()); @@ -789,10 +766,10 @@ public class DirectorApplication implements IApplication { } if (targetProfile == null) throw new CoreException(new Status(IStatus.ERROR, Activator.ID, Messages.Missing_profile)); - ProvisioningPlan plan = planner.getDiffPlan(profile, targetProfile, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getDiffPlan(profile, targetProfile, new NullProgressMonitor()); - ProvisioningContext context = new ProvisioningContext((URI[]) metadataRepositoryLocations.toArray(new URI[metadataRepositoryLocations.size()])); - context.setArtifactRepositories((URI[]) artifactRepositoryLocations.toArray(new URI[artifactRepositoryLocations.size()])); + ProvisioningContext context = new ProvisioningContext(metadataRepositoryLocations.toArray(new URI[metadataRepositoryLocations.size()])); + context.setArtifactRepositories(artifactRepositoryLocations.toArray(new URI[artifactRepositoryLocations.size()])); executePlan(context, plan); } @@ -813,6 +790,22 @@ public class DirectorApplication implements IApplication { strm.print(' '); } + IQueryResult getInstallableUnits(URI location, IQuery query, IProgressMonitor monitor) { + IQueryable queryable = null; + if (location == null) { + queryable = metadataManager; + } else { + try { + queryable = metadataManager.loadRepository(location, monitor); + } catch (ProvisionException e) { + //repository is not available - just return empty result + } + } + if (queryable != null) + return queryable.query(query, monitor); + return Collector.emptyCollector(); + } + private void deeplyPrint(CoreException ce, PrintStream strm, int level) { appendLevelPrefix(strm, level); if (stackTrace) @@ -871,7 +864,7 @@ public class DirectorApplication implements IApplication { request.setProfileProperty(IProfile.PROP_ROAMING, "true"); //$NON-NLS-1$ ProvisioningContext context = new ProvisioningContext(new URI[0]); context.setArtifactRepositories(new URI[0]); - ProvisioningPlan result = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); + IProvisioningPlan result = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); return PlanExecutionHelper.executePlan(result, engine, context, new NullProgressMonitor()); } @@ -879,47 +872,14 @@ public class DirectorApplication implements IApplication { return run((String[]) context.getArguments().get("application.args")); //$NON-NLS-1$ } - private boolean startTransient(String bundleName) throws CoreException { - Bundle bundle = getBundle(bundleName); - if (bundle == null) - return false; - try { - bundle.start(Bundle.START_TRANSIENT); - } catch (BundleException e) { - throw new ProvisionException(NLS.bind(Messages.unable_to_start_bundle_0, bundleName)); - } - return true; - } - - public void stop() { - // Nothing left to do here - } - - private boolean stopTransient(String bundleName) throws CoreException { - Bundle bundle = getBundle(bundleName); - boolean wasActive = false; - if (bundle != null) { - wasActive = (bundle.getState() & (Bundle.ACTIVE | Bundle.STARTING)) != 0; - if (wasActive) - try { - bundle.stop(Bundle.STOP_TRANSIENT); - } catch (BundleException e) { - throw new ProvisionException(NLS.bind(Messages.unable_to_stop_bundle_0, bundleName)); - } - } - return wasActive; - } - - private String toString(Map context) { + private String toString(Map context) { StringBuffer result = new StringBuffer(); - Iterator entries = context.entrySet().iterator(); - while (entries.hasNext()) { - Map.Entry entry = (Map.Entry) entries.next(); + for (Entry entry : context.entrySet()) { if (result.length() > 0) result.append(','); - result.append((String) entry.getKey()); + result.append(entry.getKey()); result.append('='); - result.append((String) entry.getValue()); + result.append(entry.getValue()); } return result.toString(); } @@ -941,11 +901,10 @@ public class DirectorApplication implements IApplication { return; ProfileChangeRequest request = new ProfileChangeRequest(profile); - File destinationFile = new File(destination); - if (!destinationFile.equals(new File(profile.getProperty(IProfile.PROP_INSTALL_FOLDER)))) - request.setProfileProperty(IProfile.PROP_INSTALL_FOLDER, destination); - if (!destinationFile.equals(new File(profile.getProperty(IProfile.PROP_CACHE)))) - request.setProfileProperty(IProfile.PROP_CACHE, destination); + if (!destination.equals(new File(profile.getProperty(IProfile.PROP_INSTALL_FOLDER)))) + request.setProfileProperty(IProfile.PROP_INSTALL_FOLDER, destination.getAbsolutePath()); + if (!destination.equals(new File(profile.getProperty(IProfile.PROP_CACHE)))) + request.setProfileProperty(IProfile.PROP_CACHE, destination.getAbsolutePath()); if (request.getProfileProperties().size() == 0) return; @@ -956,9 +915,18 @@ public class DirectorApplication implements IApplication { ProvisioningContext context = new ProvisioningContext(new URI[0]); context.setArtifactRepositories(new URI[0]); - ProvisioningPlan result = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); + IProvisioningPlan result = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); IStatus status = PlanExecutionHelper.executePlan(result, engine, context, new NullProgressMonitor()); if (!status.isOK()) throw new CoreException(new MultiStatus(org.eclipse.equinox.internal.p2.director.app.Activator.ID, IStatus.ERROR, new IStatus[] {status}, NLS.bind(Messages.Cant_change_roaming, profile.getProfileId()), null)); } + + public void stop() { + if (log != null) + log.close(); + } + + public void setLog(ILog log) { + this.log = log; + } } \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/ILog.java b/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/ILog.java new file mode 100644 index 000000000..7d12bf3f2 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/ILog.java @@ -0,0 +1,14 @@ +package org.eclipse.equinox.internal.p2.director.app; + +import org.eclipse.core.runtime.IStatus; + +public interface ILog { + + // Log a status + public void log(IStatus status); + + public void log(String message); + + // Notify that logging is completed & cleanup resources + public void close(); +} diff --git a/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/Messages.java b/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/Messages.java index 18a6ea678..6a0ba4b25 100644 --- a/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/Messages.java +++ b/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/Messages.java @@ -23,8 +23,6 @@ public class Messages extends NLS { public static String Cant_change_roaming; public static String destination_commandline; - public static String flavor_0_inconsistent_with_flavor_1; - public static String Help_A_list_of_properties_in_the_form_key_value_pairs; public static String Help_A_list_of_URLs_denoting_artifact_repositories; public static String Help_A_list_of_URLs_denoting_colocated_repositories; @@ -63,16 +61,17 @@ public class Messages extends NLS { public static String Missing_Required_Argument; public static String Missing_profile; - public static String Missing_registry; public static String Operation_complete; public static String Operation_failed; public static String option_0_requires_an_argument; public static String unable_to_parse_0_to_uri_1; - public static String unable_to_start_bundle_0; - public static String unable_to_stop_bundle_0; public static String Uninstalling; public static String unknown_option_0; + public static String problem_CallingDirector; + public static String problem_repoMustBeURI; + public static String unableToWriteLogFile; + static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, Messages.class); diff --git a/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/messages.properties b/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/messages.properties index 30795ebff..65bb3e0b1 100644 --- a/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/messages.properties +++ b/bundles/org.eclipse.equinox.p2.director.app/src/org/eclipse/equinox/internal/p2/director/app/messages.properties @@ -25,14 +25,13 @@ Missing_IU=The installable unit {0} has not been found. Missing_Required_Argument=Missing required argument -{0}. Help_A_list_of_properties_in_the_form_key_value_pairs=A list of properties in the form key=value pairs. Effective only when a new profile is created. Help_A_list_of_URLs_denoting_artifact_repositories=A list of URL's denoting artifact repositories. -Help_A_list_of_URLs_denoting_colocated_repositories=A list of URL's denoting colocated meta-data and artifact repositories. +Help_A_list_of_URLs_denoting_colocated_repositories=A list of URL's denoting co-located meta-data and artifact repositories. Help_A_list_of_URLs_denoting_metadata_repositories=A list of URL's denoting meta-data repositories. Ambigous_Command=Cannot execute both {0} and {1} in one invocation. Application_NoManager=The repository manager is not available. Application_NoRepositories=Unable to load repositories. Help_Defines_flavor_to_use_for_created_profile=Defines what flavor to use for a newly created profile. Help_Defines_what_profile_to_use_for_the_actions=Defines what profile to use for the actions. -flavor_0_inconsistent_with_flavor_1=Install flavor {0} not consistent with profile flavor {1}. Help_Indicates_that_the_product_can_be_moved=Indicates that the product resulting from the installation can be moved. Effective only when a new profile is created. Installing=Installing {0} {1}. Help_Installs_the_listed_IUs=Installs the listed IU's. Each entry in the list is in the form [ '/' ]. @@ -56,9 +55,10 @@ Help_The_NL_when_profile_is_created=The language to use when the profile is crea Help_The_OS_when_profile_is_created=The OS to use when the profile is created. Help_The_WS_when_profile_is_created=The windowing system to use when the profile is created. unable_to_parse_0_to_uri_1=Unable to parse {0} into an URI: {1}. -unable_to_start_bundle_0=Unable to start bundle {0}. -unable_to_stop_bundle_0=Unable to stop bundle {0}. unknown_option_0=Unknown option {0}. Use -help for a list of known options. Help_Missing_argument=The argument specifying what to install or uninstall is missing. -Missing_profile = The profile to revert to is not being found. -Missing_registry=The profile registry could not be loaded +Missing_profile = The profile to revert to could not be found. +problem_CallingDirector=A problem occured while invoking the director. +problem_repoMustBeURI = The repository location ({0}) must be a URI. +unableToWriteLogFile=Unable to write to the log file {0}. + diff --git a/bundles/org.eclipse.equinox.p2.director.app/src_ant/org/eclipse/equinox/p2/director/app/ant/DirectorTask.java b/bundles/org.eclipse.equinox.p2.director.app/src_ant/org/eclipse/equinox/p2/director/app/ant/DirectorTask.java index 6dca03869..5ccf858ff 100644 --- a/bundles/org.eclipse.equinox.p2.director.app/src_ant/org/eclipse/equinox/p2/director/app/ant/DirectorTask.java +++ b/bundles/org.eclipse.equinox.p2.director.app/src_ant/org/eclipse/equinox/p2/director/app/ant/DirectorTask.java @@ -10,104 +10,163 @@ *******************************************************************************/ package org.eclipse.equinox.p2.director.app.ant; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; - -import java.io.File; +import java.io.*; import java.net.URI; import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.List; +import java.util.*; import org.apache.tools.ant.*; +import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.p2.director.app.Application; +import org.eclipse.equinox.app.IApplication; +import org.eclipse.equinox.internal.p2.director.app.*; +import org.eclipse.equinox.internal.p2.metadata.VersionedId; +import org.eclipse.osgi.util.NLS; /** * An Ant task to call the p2 Director application. * * @since 1.0 */ -public class DirectorTask extends Task { +public class DirectorTask extends Task implements ILog { + private static final String ANT_PREFIX = "${"; //$NON-NLS-1$ + private static final String ENTRY = "!ENTRY "; //$NON-NLS-1$ + private static final String SUBENTRY = "!SUBENTRY "; //$NON-NLS-1$ + private static final String logEntry = "{0} {1} {2}\n"; //$NON-NLS-1$ + private static final String MESSAGE = "!MESSAGE "; //$NON-NLS-1$ + + private boolean roaming; + private boolean list; + private String profile, flavor, os, ws, nl, arch, uninstallIU; + private String extraArguments; + private File destination, bundlePool, agentLocation; + private URI metadataRepository, artifactRepository; + private List ius = new ArrayList(); + private String outputProperty; + private StringBuffer outputBuffer = null; + private File logFile = null; + + public static class IUDescription { + private String id = null; + private String version = null; + + public VersionedId getVersionedId() { + return new VersionedId(id, version); + } + + public void setId(String id) { + this.id = id; + } - boolean roaming; - boolean list; - String profile, flavor, os, ws, nl, arch, installIU, uninstallIU; - File destination, bundlePool; - URI metadataRepository, artifactRepository; - Version version; + public void setVersion(String version) { + if (version.length() > 0 && !version.startsWith(ANT_PREFIX)) + this.version = version; + } + } /* * (non-Javadoc) * @see org.apache.tools.ant.Task#execute() */ public void execute() throws BuildException { + Object result = null; try { + if (outputProperty != null) + outputBuffer = new StringBuffer(); + // collect the arguments and call the application - new Application().run(getArguments()); + DirectorApplication application = new DirectorApplication(); + application.setLog(this); + result = application.run(getArguments()); } catch (Exception e) { - throw new BuildException("Exception while calling the director task.", e); + getProject().log(Messages.problem_CallingDirector, e, Project.MSG_ERR); + throw new BuildException(Messages.problem_CallingDirector, e); + } finally { + log(outputBuffer); + } + if (result != null && !result.equals(IApplication.EXIT_OK)) { + getProject().log(Messages.problem_CallingDirector, Project.MSG_ERR); + throw new BuildException(Messages.problem_CallingDirector); } } + public void addConfiguredIu(IUDescription iu) { + ius.add(iu); + } + private String[] getArguments() { - List result = new ArrayList(); + List result = new ArrayList(); if (roaming) - result.add("-roaming"); + result.add("-roaming"); //$NON-NLS-1$ if (profile != null) { - result.add("-profile"); + result.add("-profile"); //$NON-NLS-1$ result.add(profile); } + if (extraArguments != null) { + StringTokenizer tokenizer = new StringTokenizer(extraArguments); + while (tokenizer.hasMoreTokens()) { + result.add(tokenizer.nextToken()); + } + } if (destination != null) { - result.add("-destination"); + result.add("-destination"); //$NON-NLS-1$ result.add(destination.getAbsolutePath()); } if (bundlePool != null) { - result.add("-bundlePool"); + result.add("-bundlePool"); //$NON-NLS-1$ result.add(bundlePool.getAbsolutePath()); } + if (agentLocation != null) { + result.add("-shared"); //$NON-NLS-1$ + result.add(agentLocation.getAbsolutePath()); + } if (metadataRepository != null) { - result.add("-metadataRepository"); + result.add("-metadataRepository"); //$NON-NLS-1$ result.add(metadataRepository.toString()); } if (artifactRepository != null) { - result.add("-artifactRepository"); + result.add("-artifactRepository"); //$NON-NLS-1$ result.add(artifactRepository.toString()); } if (flavor != null) { - result.add("-flavor"); + result.add("-flavor"); //$NON-NLS-1$ result.add(flavor); } - if (version != null) { - result.add("-version"); - result.add(version.toString()); + if (ius.size() > 0) { + result.add("-installIUs"); //$NON-NLS-1$ + StringBuffer arg = new StringBuffer(); + for (Iterator iterator = ius.iterator(); iterator.hasNext();) { + IUDescription object = (IUDescription) iterator.next(); + arg.append(object.getVersionedId().toString()); + if (iterator.hasNext()) + arg.append(','); + } + result.add(arg.toString()); } if (os != null) { - result.add("-p2.os"); + result.add("-p2.os"); //$NON-NLS-1$ result.add(os); } if (ws != null) { - result.add("-p2.ws"); + result.add("-p2.ws"); //$NON-NLS-1$ result.add(ws); } if (arch != null) { - result.add("-p2.arch"); + result.add("-p2.arch"); //$NON-NLS-1$ result.add(arch); } if (nl != null) { - result.add("-p2.nl"); + result.add("-p2.nl"); //$NON-NLS-1$ result.add(nl); } if (list) { result.add(Application.COMMAND_NAMES[Application.COMMAND_LIST]); } - if (installIU != null) { - result.add(Application.COMMAND_NAMES[Application.COMMAND_INSTALL]); - result.add(installIU); - } + if (uninstallIU != null) { result.add(Application.COMMAND_NAMES[Application.COMMAND_UNINSTALL]); result.add(uninstallIU); } - return (String[]) result.toArray(new String[result.size()]); + return result.toArray(new String[result.size()]); } public void setArch(String value) { @@ -118,7 +177,7 @@ public class DirectorTask extends Task { try { artifactRepository = URIUtil.fromString(value); } catch (URISyntaxException e) { - log("Error setting the artifact repository.", e, Project.MSG_ERR); + log(NLS.bind(Messages.problem_repoMustBeURI, value), e, Project.MSG_ERR); } } @@ -131,50 +190,143 @@ public class DirectorTask extends Task { } public void setFlavor(String value) { - flavor = value; - } - - public void setInstallIU(String value) { - installIU = value; + if (value != null && value.length() > 0 && !value.startsWith(ANT_PREFIX)) + flavor = value; } public void setList(String value) { - list = Boolean.valueOf(value).booleanValue(); + if (value != null && value.length() > 0 && !value.startsWith(ANT_PREFIX)) + list = Boolean.valueOf(value).booleanValue(); } public void setMetadataRepository(String value) { try { metadataRepository = URIUtil.fromString(value); } catch (URISyntaxException e) { - log("Error setting the metadata repository.", e, Project.MSG_ERR); + log(NLS.bind(Messages.problem_repoMustBeURI, value), e, Project.MSG_ERR); } } public void setNl(String value) { - nl = value; + if (value != null && value.length() > 0 && !value.startsWith(ANT_PREFIX)) + nl = value; } public void setOs(String value) { - os = value; + if (value != null && value.length() > 0 && !value.startsWith(ANT_PREFIX)) + os = value; } public void setProfile(String value) { - profile = value; + if (value != null && value.length() > 0 && !value.startsWith(ANT_PREFIX)) + profile = value; + } + + public void setExtraArguments(String value) { + if (value != null && value.length() > 0 && !value.startsWith(ANT_PREFIX)) { + extraArguments = value; + } + } public void setRoaming(String value) { - roaming = Boolean.valueOf(value).booleanValue(); + if (value != null && value.length() > 0 && !value.startsWith(ANT_PREFIX)) + roaming = Boolean.valueOf(value).booleanValue(); } public void setUninstallIU(String value) { - uninstallIU = value; + if (value != null && value.length() > 0 && !value.startsWith(ANT_PREFIX)) + uninstallIU = value; + } + + public void setWs(String value) { + if (value != null && value.length() > 0 && !value.startsWith(ANT_PREFIX)) + ws = value; } - public void setVersion(String value) { - version = new Version(value); + public void setAgentLocation(String value) { + if (value != null && value.length() > 0 && !value.startsWith(ANT_PREFIX)) + agentLocation = new File(value); } - public void setWs(String value) { - ws = value; + public void log(String msg) { + if (outputBuffer != null) { + outputBuffer.append(msg); + if (!msg.endsWith("\n")) //$NON-NLS-1$ + outputBuffer.append('\n'); + } + super.log(msg, Project.MSG_INFO); + } + + public void log(IStatus status) { + log(0, status); + if (status.isMultiStatus()) { + IStatus[] children = status.getChildren(); + for (int i = 0; i < children.length; i++) { + log(1, children[i]); + } + } + } + + private void log(int depth, IStatus status) { + log(status.getMessage(), status.getException(), Project.MSG_ERR); + if (outputBuffer != null) { + if (depth == 0) + outputBuffer.append(ENTRY); + else + outputBuffer.append(SUBENTRY); + outputBuffer.append(NLS.bind(logEntry, new String[] {status.getPlugin(), Integer.toString(status.getSeverity()), Integer.toString(status.getCode())})); + outputBuffer.append(MESSAGE); + outputBuffer.append(status.getMessage()); + outputBuffer.append('\n'); + } + } + + private void log(StringBuffer buffer) { + if (outputBuffer == null) + return; + + String logString = outputBuffer.toString(); + getProject().setNewProperty(outputProperty, logString); + + if (logFile != null) { + File parentFile = logFile.getParentFile(); + if (parentFile != null && !parentFile.exists()) + parentFile.mkdirs(); + + FileWriter writer = null; + try { + writer = new FileWriter(logFile); + writer.write(logString); + + } catch (IOException e) { + getProject().log(NLS.bind(Messages.unableToWriteLogFile, logFile.getAbsolutePath()), e, Project.MSG_WARN); + } finally { + if (writer != null) { + try { + writer.close(); + } catch (IOException e) { + //ignore + } + } + } + } + } + + public void setOutputProperty(String property) { + this.outputProperty = property; + } + + public void setLogFile(String file) { + if (file != null && !file.startsWith(ANT_PREFIX)) { + this.logFile = new File(file); + if (!logFile.isAbsolute()) { + logFile = new File(getProject().getBaseDir(), file); + } + } + } + + public void close() { + // ILog#close(), nothing to do here } } diff --git a/bundles/org.eclipse.equinox.p2.director/.classpath b/bundles/org.eclipse.equinox.p2.director/.classpath index f4025822f..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.director/.classpath +++ b/bundles/org.eclipse.equinox.p2.director/.classpath @@ -1,7 +1,7 @@ + - diff --git a/bundles/org.eclipse.equinox.p2.director/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.director/.settings/org.eclipse.jdt.core.prefs index b486accf6..5e1105ff0 100644 --- a/bundles/org.eclipse.equinox.p2.director/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.director/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Sat Feb 28 12:14:19 CET 2009 +#Mon Dec 21 23:16:26 CET 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.builder.cleanOutputFolder=clean org.eclipse.jdt.core.builder.duplicateResourceTask=warning @@ -8,23 +8,23 @@ org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fieldHiding=warning org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning @@ -71,7 +71,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=en org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 diff --git a/bundles/org.eclipse.equinox.p2.director/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.director/META-INF/MANIFEST.MF index b78fefec8..2b7b838ec 100644 --- a/bundles/org.eclipse.equinox.p2.director/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.director/META-INF/MANIFEST.MF @@ -5,25 +5,29 @@ Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-Localization: plugin Bundle-Version: 1.0.100.qualifier -Import-Package: org.eclipse.equinox.internal.p2.core.helpers, +Import-Package: org.eclipse.core.expressions, + org.eclipse.equinox.internal.p2.core.helpers, + org.eclipse.equinox.internal.p2.engine, org.eclipse.equinox.internal.provisional.configurator, org.eclipse.equinox.internal.provisional.p2.core, - org.eclipse.equinox.internal.provisional.p2.engine, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.p2.repository, org.eclipse.equinox.p2.core, org.eclipse.equinox.p2.core.spi, + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.engine.query, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.metadata, org.eclipse.osgi.util;version="1.0.0", org.osgi.framework;version="1.3.0" -Export-Package: org.eclipse.equinox.internal.p2.director;x-friends:="org.eclipse.equinox.p2.exemplarysetup,org.eclipse.pde.core", +Export-Package: org.eclipse.equinox.internal.p2.director;x-friends:="org.eclipse.equinox.p2.exemplarysetup,org.eclipse.pde.core,org.eclipse.equinox.p2.repository.tools", org.eclipse.equinox.internal.p2.rollback;x-friends:="org.eclipse.equinox.p2.ui", org.eclipse.equinox.internal.provisional.p2.director; x-friends:="org.eclipse.equinox.p2.console, org.eclipse.equinox.p2.director.app, org.eclipse.equinox.p2.installer, org.eclipse.equinox.p2.reconciler.dropins, + org.eclipse.equinox.p2.operations, org.eclipse.equinox.p2.ui, org.eclipse.equinox.p2.ui.admin, org.eclipse.equinox.p2.ui.sdk, @@ -34,11 +38,12 @@ Export-Package: org.eclipse.equinox.internal.p2.director;x-friends:="org.eclipse org.eclipse.pde.core" Bundle-Activator: org.eclipse.equinox.internal.p2.director.DirectorActivator Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, - J2SE-1.4 -Require-Bundle: org.eclipse.equinox.common;bundle-version="[3.5.0,4.0.0)", +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 +Require-Bundle: org.eclipse.equinox.common;bundle-version="[3.3.0,4.0.0)", org.sat4j.core;bundle-version="2.1.0", org.sat4j.pb;bundle-version="2.1.0", - org.eclipse.core.jobs;bundle-version="3.4.100", + org.eclipse.core.jobs;bundle-version="3.3.0", org.eclipse.equinox.p2.metadata Service-Component: OSGI-INF/director.xml, OSGI-INF/planner.xml diff --git a/bundles/org.eclipse.equinox.p2.director/build.properties b/bundles/org.eclipse.equinox.p2.director/build.properties index 9334e284d..9ac550cbd 100644 --- a/bundles/org.eclipse.equinox.p2.director/build.properties +++ b/bundles/org.eclipse.equinox.p2.director/build.properties @@ -16,3 +16,5 @@ bin.includes = META-INF/,\ plugin.properties src.includes = about.html source.. = src/ +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/ApplicablePatchQuery.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/ApplicablePatchQuery.java index 9a7b55291..4e6f0ba6f 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/ApplicablePatchQuery.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/ApplicablePatchQuery.java @@ -10,25 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.director; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.MatchQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; +import org.eclipse.equinox.p2.metadata.IInstallableUnitPatch; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; +import org.eclipse.equinox.p2.query.MatchQuery; /** * A query that accepts any patch that applies to a given installable unit. */ -public class ApplicablePatchQuery extends MatchQuery { - - /** - * A query that matches any patch. - */ - public static final Query ANY = new MatchQuery() { - public boolean isMatch(Object candidate) { - return candidate instanceof IInstallableUnitPatch; - } - }; - +public class ApplicablePatchQuery extends MatchQuery { IInstallableUnit iu; /** @@ -40,11 +31,11 @@ public class ApplicablePatchQuery extends MatchQuery { this.iu = iu; } - public boolean isMatch(Object candidate) { + public boolean isMatch(IInstallableUnit candidate) { if (!(candidate instanceof IInstallableUnitPatch)) return false; IInstallableUnitPatch patchIU = (IInstallableUnitPatch) candidate; - IRequiredCapability[][] scopeDescription = patchIU.getApplicabilityScope(); + IRequirement[][] scopeDescription = patchIU.getApplicabilityScope(); if (scopeDescription.length == 0) return true; diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/AttachmentHelper.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/AttachmentHelper.java index 68d9d747a..547aca422 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/AttachmentHelper.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/AttachmentHelper.java @@ -10,47 +10,46 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.director; +import org.eclipse.equinox.p2.metadata.IInstallableUnitFragment; + import java.util.*; import java.util.Map.Entry; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; +import org.eclipse.equinox.p2.metadata.query.FragmentQuery; public class AttachmentHelper { private static final IInstallableUnitFragment[] NO_FRAGMENTS = new IInstallableUnitFragment[0]; - public static Collection attachFragments(Collection toAttach, Map fragmentsToIUs) { - Map fragmentBindings = new HashMap(); + public static Collection attachFragments(Iterator toAttach, Map> fragmentsToIUs) { + Map fragmentBindings = new HashMap(); //Build a map inverse of the one provided in input (host --> List of fragments) - Map iusToFragment = new HashMap(fragmentsToIUs.size()); - for (Iterator iterator = fragmentsToIUs.entrySet().iterator(); iterator.hasNext();) { - Entry mapping = (Entry) iterator.next(); - IInstallableUnitFragment fragment = (IInstallableUnitFragment) mapping.getKey(); - List existingMatches = (List) mapping.getValue(); + Map> iusToFragment = new HashMap>(fragmentsToIUs.size()); + for (Entry> mapping : fragmentsToIUs.entrySet()) { + IInstallableUnitFragment fragment = mapping.getKey(); + List existingMatches = mapping.getValue(); - for (Iterator iterator2 = existingMatches.iterator(); iterator2.hasNext();) { - Object host = iterator2.next(); - List potentialFragments = (List) iusToFragment.get(host); + for (IInstallableUnit host : existingMatches) { + List potentialFragments = iusToFragment.get(host); if (potentialFragments == null) { - potentialFragments = new ArrayList(); + potentialFragments = new ArrayList(); iusToFragment.put(host, potentialFragments); } potentialFragments.add(fragment); } } - for (Iterator iterator = iusToFragment.entrySet().iterator(); iterator.hasNext();) { - Entry entry = (Entry) iterator.next(); - IInstallableUnit hostIU = (IInstallableUnit) entry.getKey(); - List potentialIUFragments = (List) entry.getValue(); - ArrayList applicableFragments = new ArrayList(); - for (Iterator iterator2 = potentialIUFragments.iterator(); iterator2.hasNext();) { - IInstallableUnit dependentIU = (IInstallableUnitFragment) iterator2.next(); - if (hostIU.equals(dependentIU) || !dependentIU.isFragment()) + for (Entry> entry : iusToFragment.entrySet()) { + IInstallableUnit hostIU = entry.getKey(); + List potentialIUFragments = entry.getValue(); + ArrayList applicableFragments = new ArrayList(); + for (IInstallableUnitFragment potentialFragment : potentialIUFragments) { + if (hostIU.equals(potentialFragment)) continue; - IInstallableUnitFragment potentialFragment = (IInstallableUnitFragment) dependentIU; - // Check to make sure the host meets the requirements of the fragment - IRequiredCapability reqsFromFragment[] = potentialFragment.getHost(); + IRequirement reqsFromFragment[] = potentialFragment.getHost(); boolean match = true; boolean requirementMatched = false; for (int l = 0; l < reqsFromFragment.length && match == true; l++) { @@ -70,8 +69,7 @@ public class AttachmentHelper { IInstallableUnitFragment theFragment = null; int specificityLevel = 0; - for (Iterator iterator4 = applicableFragments.iterator(); iterator4.hasNext();) { - IInstallableUnitFragment fragment = (IInstallableUnitFragment) iterator4.next(); + for (IInstallableUnitFragment fragment : applicableFragments) { if (fragment.getHost().length > specificityLevel) { theFragment = fragment; specificityLevel = fragment.getHost().length; @@ -81,18 +79,18 @@ public class AttachmentHelper { fragmentBindings.put(hostIU, theFragment); } //build the collection of resolved IUs - Collection result = new HashSet(toAttach.size()); - for (Iterator iterator = toAttach.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); + Collection result = new HashSet(); + while (toAttach.hasNext()) { + IInstallableUnit iu = toAttach.next(); if (iu == null) continue; //just return fragments as they are - if (iu.isFragment()) { + if (FragmentQuery.isFragment(iu)) { result.add(iu); continue; } //return a new IU that combines the IU with its bound fragments - IInstallableUnitFragment fragment = (IInstallableUnitFragment) fragmentBindings.get(iu); + IInstallableUnitFragment fragment = fragmentBindings.get(iu); IInstallableUnitFragment[] fragments; if (fragment == null) fragments = NO_FRAGMENTS; diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/DirectorComponent.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/DirectorComponent.java index b4f2a3044..2ab6904af 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/DirectorComponent.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/DirectorComponent.java @@ -1,10 +1,3 @@ -package org.eclipse.equinox.internal.p2.director; - -import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.p2.core.IProvisioningAgent; -import org.eclipse.equinox.p2.core.spi.IAgentServiceFactory; - /******************************************************************************* * Copyright (c) 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials @@ -15,10 +8,13 @@ import org.eclipse.equinox.p2.core.spi.IAgentServiceFactory; * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ +package org.eclipse.equinox.internal.p2.director; + +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.core.spi.IAgentServiceFactory; +import org.eclipse.equinox.p2.engine.IEngine; -/** - * - */ public class DirectorComponent implements IAgentServiceFactory { public Object createService(IProvisioningAgent agent) { diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Explanation.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Explanation.java index 0a85e5748..6dea4fcf6 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Explanation.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Explanation.java @@ -10,17 +10,20 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.director; +import org.eclipse.equinox.p2.metadata.IInstallableUnitPatch; + import java.util.Arrays; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; import org.eclipse.osgi.util.NLS; -public abstract class Explanation implements Comparable { +public abstract class Explanation implements Comparable { public static class PatchedHardRequirement extends Explanation { public final IInstallableUnit iu; public final IInstallableUnitPatch patch; - public final IRequiredCapability req; + public final IRequirement req; public PatchedHardRequirement(IInstallableUnit iu, IInstallableUnitPatch patch) { this.iu = iu; @@ -28,7 +31,7 @@ public abstract class Explanation implements Comparable { this.patch = patch; } - public PatchedHardRequirement(IInstallableUnit iu, IRequiredCapability req, IInstallableUnitPatch patch) { + public PatchedHardRequirement(IInstallableUnit iu, IRequirement req, IInstallableUnitPatch patch) { this.iu = iu; this.req = req; this.patch = patch; @@ -53,9 +56,9 @@ public abstract class Explanation implements Comparable { public static class HardRequirement extends Explanation { public final IInstallableUnit iu; - public final IRequiredCapability req; + public final IRequirement req; - public HardRequirement(IInstallableUnit iu, IRequiredCapability req) { + public HardRequirement(IInstallableUnit iu, IRequirement req) { this.iu = iu; this.req = req; } @@ -118,9 +121,9 @@ public abstract class Explanation implements Comparable { public static class MissingIU extends Explanation { public final IInstallableUnit iu; - public final IRequiredCapability req; + public final IRequirement req; - public MissingIU(IInstallableUnit iu, IRequiredCapability req) { + public MissingIU(IInstallableUnit iu, IRequirement req) { this.iu = iu; this.req = req; } @@ -134,19 +137,17 @@ public abstract class Explanation implements Comparable { } public String toString() { - String filter = req.getFilter(); - if (filter == null) { + if (req.getFilter() == null) { return NLS.bind(Messages.Explanation_missingRequired, iu, req); } - return NLS.bind(Messages.Explanation_missingRequiredFilter, new Object[] {filter, iu, req}); + return NLS.bind(Messages.Explanation_missingRequiredFilter, new Object[] {req.getFilter(), iu, req}); } public IStatus toStatus() { - String filter = req.getFilter(); - if (filter == null) { + if (req.getFilter() == null) { return new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, NLS.bind(Messages.Explanation_missingRequired, getUserReadableName(iu), req)); } - return new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, NLS.bind(Messages.Explanation_missingRequiredFilter, new Object[] {filter, getUserReadableName(iu), req})); + return new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, NLS.bind(Messages.Explanation_missingRequiredFilter, new Object[] {req.getFilter(), getUserReadableName(iu), req})); } } @@ -197,8 +198,7 @@ public abstract class Explanation implements Comparable { super(); } - public int compareTo(Object arg0) { - Explanation exp = (Explanation) arg0; + public int compareTo(Explanation exp) { if (this.orderValue() == exp.orderValue()) { return this.toString().compareTo(exp.toString()); } diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/HasMatchCollector.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/HasMatchCollector.java deleted file mode 100644 index 058e3b3a7..000000000 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/HasMatchCollector.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.director; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; - -/** - * A collector that short-circuits on the first match. - */ -public class HasMatchCollector extends Collector { - private boolean hasMatch = false; - - public boolean accept(Object object) { - hasMatch = true; - return false; - } - - public boolean isEmpty() { - return !hasMatch; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Messages.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Messages.java index 831cf7e0a..cccc419a6 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Messages.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Messages.java @@ -56,5 +56,6 @@ public class Messages extends NLS { public static String Planner_can_not_install_preq; public static String Planner_no_profile_registry; public static String Planner_profile_out_of_sync; + public static String RequestStatus_message; } diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/OperationGenerator.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/OperationGenerator.java index 444e514f8..87484914e 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/OperationGenerator.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/OperationGenerator.java @@ -10,94 +10,72 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.director; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; +import org.eclipse.equinox.p2.metadata.IInstallableUnitFragment; import java.util.*; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; public class OperationGenerator { private static final IInstallableUnit NULL_IU = MetadataFactory.createResolvedInstallableUnit(MetadataFactory.createInstallableUnit(new InstallableUnitDescription()), new IInstallableUnitFragment[0]); - public InstallableUnitOperand[] generateOperation(Collection from_, Collection to_) { - Collection intersection = new HashSet(from_); + public List generateOperation(Collection from_, Collection to_) { + Collection intersection = new HashSet(from_); intersection.retainAll(to_); - HashSet tmpFrom = new HashSet(from_); - HashSet tmpTo = new HashSet(to_); + HashSet tmpFrom = new HashSet(from_); + HashSet tmpTo = new HashSet(to_); tmpFrom.removeAll(intersection); tmpTo.removeAll(intersection); - List from = new ArrayList(tmpFrom); + List from = new ArrayList(tmpFrom); Collections.sort(from); - List to = new ArrayList(tmpTo); + List to = new ArrayList(tmpTo); Collections.sort(to); - ArrayList operations = new ArrayList(); + ArrayList operations = new ArrayList(); generateUpdates(from, to, operations); generateInstallUninstall(from, to, operations); generateConfigurationChanges(to_, intersection, operations); - InstallableUnitOperand[] ops = (InstallableUnitOperand[]) operations.toArray(new InstallableUnitOperand[operations.size()]); - return ops; + return operations; } //This generates operations that are causing the IUs to be reconfigured. - private void generateConfigurationChanges(Collection to_, Collection intersection, ArrayList operations) { + private void generateConfigurationChanges(Collection to_, Collection intersection, ArrayList operations) { if (intersection.size() == 0) return; //We retain from each set the things that are the same. //Note that despite the fact that they are the same, a different CU can be attached. //The objects contained in the intersection are the one that were originally in the from collection. - TreeSet to = new TreeSet(to_); - for (Iterator iterator = intersection.iterator(); iterator.hasNext();) { - IInstallableUnit fromIU = (IInstallableUnit) iterator.next(); - IInstallableUnit toIU = (IInstallableUnit) to.tailSet(fromIU).first(); + TreeSet to = new TreeSet(to_); + for (IInstallableUnit fromIU : intersection) { + IInstallableUnit toIU = to.tailSet(fromIU).first(); generateConfigurationOperation(fromIU, toIU, operations); } } - private void generateConfigurationOperation(IInstallableUnit fromIU, IInstallableUnit toIU, ArrayList operations) { - IInstallableUnitFragment[] fromFragments = fromIU.getFragments(); - IInstallableUnitFragment[] toFragments = toIU.getFragments(); + private void generateConfigurationOperation(IInstallableUnit fromIU, IInstallableUnit toIU, ArrayList operations) { + List fromFragments = fromIU.getFragments(); + List toFragments = toIU.getFragments(); if (fromFragments == toFragments) return; //Check to see if the two arrays are equals independently of the order of the fragments - boolean different = false; - if (fromFragments != null && toFragments != null) { - if (fromFragments.length != toFragments.length) - different = true; - else { - for (int i = 0; i < fromFragments.length; i++) { - boolean found = false; - for (int j = 0; j < toFragments.length; j++) { - if (fromFragments[i].equals(toFragments[j])) - found = true; - } - if (!found) { - different = true; - break; - } - } - } - } else { - //One of the two array is null - different = true; - } - if (!different) + if (fromFragments.size() == toFragments.size() && fromFragments.containsAll(toFragments)) return; operations.add(new InstallableUnitOperand(fromIU, toIU)); } - private void generateInstallUninstall(List from, List to, ArrayList operations) { + private void generateInstallUninstall(List from, List to, ArrayList operations) { int toIdx = 0; int fromIdx = 0; while (fromIdx != from.size() && toIdx != to.size()) { - IInstallableUnit fromIU = (IInstallableUnit) from.get(fromIdx); - IInstallableUnit toIU = (IInstallableUnit) to.get(toIdx); + IInstallableUnit fromIU = from.get(fromIdx); + IInstallableUnit toIU = to.get(toIdx); int comparison = toIU.compareTo(fromIU); if (comparison < 0) { operations.add(createInstallOperation(toIU)); @@ -113,36 +91,35 @@ public class OperationGenerator { } if (fromIdx != from.size()) { for (int i = fromIdx; i < from.size(); i++) { - operations.add(createUninstallOperation((IInstallableUnit) from.get(i))); + operations.add(createUninstallOperation(from.get(i))); } } if (toIdx != to.size()) { for (int i = toIdx; i < to.size(); i++) { - operations.add(createInstallOperation((IInstallableUnit) to.get(i))); + operations.add(createInstallOperation(to.get(i))); } } } - private void generateUpdates(List from, List to, ArrayList operations) { - Set processed = new HashSet(); - Set removedFromTo = new HashSet(); - + private void generateUpdates(List from, List to, ArrayList operations) { if (to.isEmpty() || from.isEmpty()) return; - Map fromById = new HashMap(); - for (Iterator iterator = from.iterator(); iterator.hasNext();) { - IInstallableUnit iuFrom = (IInstallableUnit) iterator.next(); - List ius = (List) fromById.get(iuFrom.getId()); + Set processed = new HashSet(); + Set removedFromTo = new HashSet(); + + Map> fromById = new HashMap>(); + for (IInstallableUnit iuFrom : from) { + List ius = fromById.get(iuFrom.getId()); if (ius == null) { - ius = new ArrayList(); + ius = new ArrayList(); fromById.put(iuFrom.getId(), ius); } ius.add(iuFrom); } for (int toIdx = 0; toIdx < to.size(); toIdx++) { - IInstallableUnit iuTo = (IInstallableUnit) to.get(toIdx); + IInstallableUnit iuTo = to.get(toIdx); if (iuTo.getId().equals(next(to, toIdx).getId())) { //This handle the case where there are multiple versions of the same IU in the target. Eg we are trying to update from A 1.0.0 to A 1.1.1 and A 1.2.2 toIdx = skip(to, iuTo, toIdx) - 1; //System.out.println("Can't update " + iuTo + " because another iu with same id is in the target state"); @@ -151,18 +128,18 @@ public class OperationGenerator { if (iuTo.getUpdateDescriptor() == null) continue; - List fromIdIndexList = (List) fromById.get(iuTo.getUpdateDescriptor().getId()); + List fromIdIndexList = fromById.get(iuTo.getUpdateDescriptor().getId()); if (fromIdIndexList == null) continue; //when the ui we update from is in the new state, skip (for example FROM is A, C, B & TO is C (update of InstallableUnitQuery updateQuery = new InstallableUnitQuery(iuTo.getUpdateDescriptor().getId(), iuTo.getUpdateDescriptor().getRange()); - Iterator updates = updateQuery.perform(fromIdIndexList.iterator(), new Collector()).iterator(); + Iterator updates = updateQuery.perform(fromIdIndexList.iterator()).iterator(); if (!updates.hasNext()) { //Nothing to update from. continue; } - IInstallableUnit iuFrom = (IInstallableUnit) updates.next(); + IInstallableUnit iuFrom = updates.next(); if (updates.hasNext()) { //There are multiple IUs to update from //System.out.println("Can't update " + iuTo + " because there are multiple IUs to update from (" + toString(iusFrom) + ')'); continue; @@ -194,17 +171,17 @@ public class OperationGenerator { return new InstallableUnitOperand(from, to); } - private IInstallableUnit next(List l, int i) { + private IInstallableUnit next(List l, int i) { i++; if (i >= l.size()) return NULL_IU; - return (IInstallableUnit) l.get(i); + return l.get(i); } - private int skip(List c, IInstallableUnit id, int idx) { + private int skip(List c, IInstallableUnit id, int idx) { int i = idx; for (; i < c.size(); i++) { - if (!id.getId().equals(((IInstallableUnit) c.get(i)).getId())) + if (!id.getId().equals(c.get(i).getId())) return i; } return i; diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/PermissiveSlicer.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/PermissiveSlicer.java index aff9e89ec..25604cbb4 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/PermissiveSlicer.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/PermissiveSlicer.java @@ -8,11 +8,11 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.director; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; - import java.util.Dictionary; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.p2.metadata.RequiredCapability; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; +import org.eclipse.equinox.p2.query.IQueryable; public class PermissiveSlicer extends Slicer { private boolean includeOptionalDependencies; //Cause optional dependencies not be followed as part of the @@ -22,7 +22,7 @@ public class PermissiveSlicer extends Slicer { private boolean evalFilterTo; private boolean onlyFilteredRequirements; - public PermissiveSlicer(IQueryable input, Dictionary context, boolean includeOptionalDependencies, boolean everythingGreedy, boolean evalFilterTo, boolean considerOnlyStrictDependency, boolean onlyFilteredRequirements) { + public PermissiveSlicer(IQueryable input, Dictionary context, boolean includeOptionalDependencies, boolean everythingGreedy, boolean evalFilterTo, boolean considerOnlyStrictDependency, boolean onlyFilteredRequirements) { super(input, context, true); this.considerFilter = (context != null && context.size() > 1) ? true : false; this.includeOptionalDependencies = includeOptionalDependencies; @@ -40,14 +40,14 @@ public class PermissiveSlicer extends Slicer { return evalFilterTo; } - protected boolean isApplicable(IRequiredCapability req) { + protected boolean isApplicable(IRequirement req) { //Every filter in this method needs to continue except when the filter does not pass if (!includeOptionalDependencies) - if (req.isOptional()) + if (req.getMin() == 0) return false; if (considerOnlyStrictDependency) { - if (!req.getRange().getMinimum().equals(req.getRange().getMaximum())) + if (!RequiredCapability.isVersionStrict(req.getMatches())) return false; } @@ -66,7 +66,7 @@ public class PermissiveSlicer extends Slicer { return evalFilterTo; } - protected boolean isGreedy(IRequiredCapability req) { + protected boolean isGreedy(IRequirement req) { if (everythingGreedy) { return true; } diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/PlannerComponent.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/PlannerComponent.java index e363ea236..771c70f01 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/PlannerComponent.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/PlannerComponent.java @@ -10,10 +10,10 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.director; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; import org.eclipse.equinox.p2.core.IProvisioningAgent; import org.eclipse.equinox.p2.core.spi.IAgentServiceFactory; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; /** * A service factory that provides planner implementations diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Projector.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Projector.java index 20575be58..0388be5e3 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Projector.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Projector.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. All rights reserved. This + * Copyright (c) 2007, 2010 IBM Corporation and others. All rights reserved. This * program and the accompanying materials are made available under the terms of * the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html @@ -16,12 +16,15 @@ import java.util.*; import java.util.Map.Entry; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; import org.eclipse.equinox.internal.p2.core.helpers.Tracing; -import org.eclipse.equinox.internal.p2.metadata.NotRequirement; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.*; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.query.IQueryable; import org.eclipse.osgi.util.NLS; -import org.osgi.framework.InvalidSyntaxException; +import org.osgi.framework.Filter; import org.sat4j.pb.IPBSolver; import org.sat4j.pb.SolverFactory; import org.sat4j.pb.tools.DependencyHelper; @@ -36,26 +39,28 @@ import org.sat4j.specs.*; public class Projector { static boolean DEBUG = Tracing.DEBUG_PLANNER_PROJECTOR; private static boolean DEBUG_ENCODING = false; - private IQueryable picker; + private IQueryable picker; private QueryableArray patches; - private Map noopVariables; //key IU, value AbstractVariable - private List abstractVariables; + private Map noopVariables; //key IU, value AbstractVariable + private List abstractVariables; - private TwoTierMap slice; //The IUs that have been considered to be part of the problem + private Map> slice; //The IUs that have been considered to be part of the problem - private Dictionary selectionContext; + private Dictionary selectionContext; - DependencyHelper dependencyHelper; - private Collection solution; - private Collection assumptions; + DependencyHelper dependencyHelper; + private Collection solution; + private Collection assumptions; private MultiStatus result; - private Collection alreadyInstalledIUs; + private Collection alreadyInstalledIUs; + private IQueryable lastState; + private boolean considerMetaRequirements; private IInstallableUnit entryPoint; - private Map fragments = new HashMap(); + private Map> fragments = new HashMap>(); static class AbstractVariable { public String toString() { @@ -67,7 +72,7 @@ public class Projector { * Job for computing SAT failure explanation in the background. */ class ExplanationJob extends Job { - private Set explanation; + private Set explanation; public ExplanationJob() { super(Messages.Planner_NoSolution); @@ -84,7 +89,7 @@ public class Projector { dependencyHelper.stopExplanation(); } - public Set getExplanationResult() { + public Set getExplanationResult() { return explanation; } @@ -100,8 +105,8 @@ public class Projector { long stop = System.currentTimeMillis(); Tracing.debug("Explanation found: " + (stop - start)); //$NON-NLS-1$ Tracing.debug("Explanation:"); //$NON-NLS-1$ - for (Iterator i = explanation.iterator(); i.hasNext();) { - Tracing.debug(i.next().toString()); + for (Explanation ex : explanation) { + Tracing.debug(ex.toString()); } } } catch (TimeoutException e) { @@ -110,7 +115,7 @@ public class Projector { } finally { //must never have a null result, because caller is waiting on result to be non-null if (explanation == null) - explanation = Collections.EMPTY_SET; + explanation = CollectionUtils.emptySet(); } synchronized (this) { ExplanationJob.this.notify(); @@ -120,19 +125,24 @@ public class Projector { } - public Projector(IQueryable q, Dictionary context, boolean considerMetaRequirements) { + public Projector(IQueryable q, Dictionary context, boolean considerMetaRequirements) { picker = q; - noopVariables = new HashMap(); - slice = new TwoTierMap(); + noopVariables = new HashMap(); + slice = new HashMap>(); selectionContext = context; - abstractVariables = new ArrayList(); + abstractVariables = new ArrayList(); result = new MultiStatus(DirectorActivator.PI_DIRECTOR, IStatus.OK, Messages.Planner_Problems_resolving_plan, null); - assumptions = new ArrayList(); + assumptions = new ArrayList(); this.considerMetaRequirements = considerMetaRequirements; } - public void encode(IInstallableUnit entryPointIU, IInstallableUnit[] alreadyExistingRoots, IInstallableUnit[] newRoots, IProgressMonitor monitor) { + protected boolean isInstalled(IInstallableUnit iu) { + return !lastState.query(new InstallableUnitQuery(iu), null).isEmpty(); + } + + public void encode(IInstallableUnit entryPointIU, IInstallableUnit[] alreadyExistingRoots, IQueryable installedIUs, IInstallableUnit[] newRoots, IProgressMonitor monitor) { alreadyInstalledIUs = Arrays.asList(alreadyExistingRoots); + lastState = installedIUs; this.entryPoint = entryPointIU; try { long start = 0; @@ -147,12 +157,12 @@ public class Projector { solver = SolverFactory.newEclipseP2(); } solver.setTimeoutOnConflicts(1000); - Collector collector = picker.query(InstallableUnitQuery.ANY, new Collector(), null); - dependencyHelper = new DependencyHelper(solver); + IQueryResult queryResult = picker.query(InstallableUnitQuery.ANY, null); + dependencyHelper = new DependencyHelper(solver); - Iterator iusToEncode = collector.iterator(); + Iterator iusToEncode = queryResult.iterator(); if (DEBUG) { - List iusToOrder = new ArrayList(); + List iusToOrder = new ArrayList(); while (iusToEncode.hasNext()) { iusToOrder.add(iusToEncode.next()); } @@ -164,7 +174,7 @@ public class Projector { result.merge(Status.CANCEL_STATUS); throw new OperationCanceledException(); } - IInstallableUnit iuToEncode = (IInstallableUnit) iusToEncode.next(); + IInstallableUnit iuToEncode = iusToEncode.next(); if (iuToEncode != entryPointIU) { processIU(iuToEncode, false); } @@ -191,24 +201,24 @@ public class Projector { //Create an optimization function favoring the highest version of each IU private void createOptimizationFunction(IInstallableUnit metaIu) { - List weightedObjects = new ArrayList(); + List> weightedObjects = new ArrayList>(); - Set s = slice.entrySet(); + Set>> s = slice.entrySet(); final BigInteger POWER = BigInteger.valueOf(2); BigInteger maxWeight = POWER; - for (Iterator iterator = s.iterator(); iterator.hasNext();) { - Map.Entry entry = (Map.Entry) iterator.next(); - HashMap conflictingEntries = (HashMap) entry.getValue(); + for (Entry> entry : s) { + Map conflictingEntries = entry.getValue(); if (conflictingEntries.size() == 1) { continue; } - List toSort = new ArrayList(conflictingEntries.values()); + List toSort = new ArrayList(conflictingEntries.values()); Collections.sort(toSort, Collections.reverseOrder()); - BigInteger weight = BigInteger.ONE; + BigInteger weight = POWER; int count = toSort.size(); for (int i = 0; i < count; i++) { - weightedObjects.add(WeightedObject.newWO(toSort.get(i), weight)); + IInstallableUnit iu = toSort.get(i); + weightedObjects.add(WeightedObject.newWO(iu, isInstalled(iu) ? BigInteger.ONE : weight)); weight = weight.multiply(POWER); } if (weight.compareTo(maxWeight) > 0) @@ -218,40 +228,40 @@ public class Projector { maxWeight = maxWeight.multiply(POWER); // Weight the no-op variables beneath the abstract variables - for (Iterator iterator = noopVariables.values().iterator(); iterator.hasNext();) { - weightedObjects.add(WeightedObject.newWO(iterator.next(), maxWeight)); - } + for (AbstractVariable var : noopVariables.values()) + weightedObjects.add(WeightedObject.newWO(var, maxWeight)); maxWeight = maxWeight.multiply(POWER); // Add the abstract variables BigInteger abstractWeight = maxWeight.negate(); - for (Iterator iterator = abstractVariables.iterator(); iterator.hasNext();) { - weightedObjects.add(WeightedObject.newWO(iterator.next(), abstractWeight)); + for (AbstractVariable var : abstractVariables) { + weightedObjects.add(WeightedObject.newWO(var, abstractWeight)); } maxWeight = maxWeight.multiply(POWER); BigInteger optionalWeight = maxWeight.negate(); long countOptional = 1; - List requestedPatches = new ArrayList(); - IRequiredCapability[] reqs = metaIu.getRequiredCapabilities(); - for (int j = 0; j < reqs.length; j++) { - if (!reqs[j].isOptional()) + List requestedPatches = new ArrayList(); + Collection reqs = metaIu.getRequiredCapabilities(); + for (IRequirement req : reqs) { + if (req.getMin() > 0) continue; - Collector matches = picker.query(new CapabilityQuery(reqs[j]), new Collector(), null); - for (Iterator iterator = matches.iterator(); iterator.hasNext();) { - IInstallableUnit match = (IInstallableUnit) iterator.next(); + IQueryResult matches = picker.query(new ExpressionQuery(IInstallableUnit.class, req.getMatches()), null); + for (Iterator iterator = matches.iterator(); iterator.hasNext();) { + IInstallableUnit match = iterator.next(); if (match instanceof IInstallableUnitPatch) { requestedPatches.add(match); countOptional = countOptional + 1; - } else - weightedObjects.add(WeightedObject.newWO(match, optionalWeight)); + } else { + weightedObjects.add(WeightedObject.newWO(match, isInstalled(match) ? BigInteger.ONE : optionalWeight)); + } } } BigInteger patchWeight = maxWeight.multiply(POWER).multiply(BigInteger.valueOf(countOptional)).negate(); - for (Iterator iterator = requestedPatches.iterator(); iterator.hasNext();) { + for (Iterator iterator = requestedPatches.iterator(); iterator.hasNext();) { weightedObjects.add(WeightedObject.newWO(iterator.next(), patchWeight)); } if (!weightedObjects.isEmpty()) { @@ -259,11 +269,10 @@ public class Projector { } } - private void createObjectiveFunction(List weightedObjects) { + private void createObjectiveFunction(List> weightedObjects) { if (DEBUG) { StringBuffer b = new StringBuffer(); - for (Iterator i = weightedObjects.iterator(); i.hasNext();) { - WeightedObject object = (WeightedObject) i.next(); + for (WeightedObject object : weightedObjects) { if (b.length() > 0) b.append(", "); //$NON-NLS-1$ b.append(object.getWeight()); @@ -272,7 +281,9 @@ public class Projector { } Tracing.debug("objective function: " + b); //$NON-NLS-1$ } - dependencyHelper.setObjectiveFunction((WeightedObject[]) weightedObjects.toArray(new WeightedObject[weightedObjects.size()])); + @SuppressWarnings("unchecked") + WeightedObject[] array = (WeightedObject[]) weightedObjects.toArray(new WeightedObject[weightedObjects.size()]); + dependencyHelper.setObjectiveFunction(array); } private void createMustHave(IInstallableUnit iu, IInstallableUnit[] alreadyExistingRoots, IInstallableUnit[] newRoots) throws ContradictionException { @@ -284,7 +295,7 @@ public class Projector { assumptions.add(iu); } - private void createNegation(IInstallableUnit iu, IRequiredCapability req) throws ContradictionException { + private void createNegation(IInstallableUnit iu, IRequirement req) throws ContradictionException { if (DEBUG) { Tracing.debug(iu + "=0"); //$NON-NLS-1$ } @@ -292,39 +303,26 @@ public class Projector { } // Check whether the requirement is applicable - private boolean isApplicable(IRequiredCapability req) { - String filter = req.getFilter(); - if (filter == null) - return true; - try { - return DirectorActivator.context.createFilter(filter).match(selectionContext); - } catch (InvalidSyntaxException e) { - return false; - } + private boolean isApplicable(IRequirement req) { + Filter filter = req.getFilter(); + return filter == null || filter.match(selectionContext); } private boolean isApplicable(IInstallableUnit iu) { - String enablementFilter = iu.getFilter(); - if (enablementFilter == null) - return true; - try { - return DirectorActivator.context.createFilter(enablementFilter).match(selectionContext); - } catch (InvalidSyntaxException e) { - return false; - } + Filter filter = iu.getFilter(); + return filter == null || filter.match(selectionContext); } - private void expandNegatedRequirement(IRequiredCapability req, IInstallableUnit iu, List optionalAbstractRequirements, boolean isRootIu) throws ContradictionException { - IRequiredCapability negatedReq = ((NotRequirement) req).getRequirement(); - if (!isApplicable(negatedReq)) + private void expandNegatedRequirement(IRequirement req, IInstallableUnit iu, List optionalAbstractRequirements, boolean isRootIu) throws ContradictionException { + if (!isApplicable(req)) return; - List matches = getApplicableMatches(negatedReq); + List matches = getApplicableMatches(req); if (matches.isEmpty()) { return; } Explanation explanation; if (isRootIu) { - IInstallableUnit reqIu = (IInstallableUnit) matches.iterator().next(); + IInstallableUnit reqIu = matches.get(0); if (alreadyInstalledIUs.contains(reqIu)) { explanation = new Explanation.IUInstalled(reqIu); } else { @@ -336,22 +334,22 @@ public class Projector { createNegationImplication(iu, matches, explanation); } - private void expandRequirement(IRequiredCapability req, IInstallableUnit iu, List optionalAbstractRequirements, boolean isRootIu) throws ContradictionException { - if (req.isNegation()) { + private void expandRequirement(IRequirement req, IInstallableUnit iu, List optionalAbstractRequirements, boolean isRootIu) throws ContradictionException { + if (req.getMax() == 0) { expandNegatedRequirement(req, iu, optionalAbstractRequirements, isRootIu); return; } if (!isApplicable(req)) return; - List matches = getApplicableMatches(req); + List matches = getApplicableMatches(req); if (isHostRequirement(iu, req)) { - rememberHostMatches(iu, matches); + rememberHostMatches((IInstallableUnitFragment) iu, matches); } - if (!req.isOptional()) { + if (req.getMin() > 0) { if (matches.isEmpty()) { missingRequirement(iu, req); } else { - IInstallableUnit reqIu = (IInstallableUnit) picker.query(new CapabilityQuery(req), new Collector(), null).iterator().next(); + IInstallableUnit reqIu = matches.get(0); Explanation explanation; if (isRootIu) { if (alreadyInstalledIUs.contains(reqIu)) { @@ -373,13 +371,12 @@ public class Projector { } } - private void expandRequirements(IRequiredCapability[] reqs, IInstallableUnit iu, boolean isRootIu) throws ContradictionException { - if (reqs.length == 0) { + private void expandRequirements(Collection reqs, IInstallableUnit iu, boolean isRootIu) throws ContradictionException { + if (reqs.isEmpty()) return; - } - List optionalAbstractRequirements = new ArrayList(); - for (int i = 0; i < reqs.length; i++) { - expandRequirement(reqs[i], iu, optionalAbstractRequirements, isRootIu); + List optionalAbstractRequirements = new ArrayList(); + for (IRequirement req : reqs) { + expandRequirement(req, iu, optionalAbstractRequirements, isRootIu); } createOptionalityExpression(iu, optionalAbstractRequirements); } @@ -387,16 +384,21 @@ public class Projector { public void processIU(IInstallableUnit iu, boolean isRootIU) throws ContradictionException { iu = iu.unresolved(); - slice.put(iu.getId(), iu.getVersion(), iu); + Map iuSlice = slice.get(iu.getId()); + if (iuSlice == null) { + iuSlice = new HashMap(); + slice.put(iu.getId(), iuSlice); + } + iuSlice.put(iu.getVersion(), iu); if (!isApplicable(iu)) { createNegation(iu, null); return; } - Collector applicablePatches = getApplicablePatches(iu); + IQueryResult applicablePatches = getApplicablePatches(iu); expandLifeCycle(iu, isRootIU); //No patches apply, normal code path - if (applicablePatches.size() == 0) { + if (applicablePatches.isEmpty()) { expandRequirements(getRequiredCapabilities(iu), iu, isRootIU); } else { //Patches are applicable to the IU @@ -404,21 +406,35 @@ public class Projector { } } - private IRequiredCapability[] getRequiredCapabilities(IInstallableUnit iu) { - if (considerMetaRequirements == false || iu.getMetaRequiredCapabilities().length == 0) - return iu.getRequiredCapabilities(); - IRequiredCapability[] aggregatedCapabilities = new IRequiredCapability[iu.getRequiredCapabilities().length + iu.getMetaRequiredCapabilities().length]; - System.arraycopy(iu.getRequiredCapabilities(), 0, aggregatedCapabilities, 0, iu.getRequiredCapabilities().length); - System.arraycopy(iu.getMetaRequiredCapabilities(), 0, aggregatedCapabilities, iu.getRequiredCapabilities().length, iu.getMetaRequiredCapabilities().length); - return aggregatedCapabilities; + private Collection getRequiredCapabilities(IInstallableUnit iu) { + Collection rqs = iu.getRequiredCapabilities(); + if (!considerMetaRequirements) + return rqs; + + Collection metaRqs = iu.getMetaRequiredCapabilities(); + if (metaRqs.isEmpty()) + return rqs; + + ArrayList aggregatedRqs = new ArrayList(rqs.size() + metaRqs.size()); + aggregatedRqs.addAll(rqs); + aggregatedRqs.addAll(metaRqs); + return aggregatedRqs; + } + + static final class Pending { + List matches; + Explanation explanation; + Object left; } - private void expandRequirementsWithPatches(IInstallableUnit iu, Collector applicablePatches, boolean isRootIu) throws ContradictionException { + private void expandRequirementsWithPatches(IInstallableUnit iu, IQueryResult applicablePatches, boolean isRootIu) throws ContradictionException { //Unmodified dependencies - Map unchangedRequirements = new HashMap(getRequiredCapabilities(iu).length); - for (Iterator iterator = applicablePatches.iterator(); iterator.hasNext();) { + Collection iuRequirements = getRequiredCapabilities(iu); + Map> unchangedRequirements = new HashMap>(iuRequirements.size()); + Map nonPatchedRequirements = new HashMap(iuRequirements.size()); + for (Iterator iterator = applicablePatches.iterator(); iterator.hasNext();) { IInstallableUnitPatch patch = (IInstallableUnitPatch) iterator.next(); - IRequiredCapability[][] reqs = mergeRequirements(iu, patch); + IRequirement[][] reqs = mergeRequirements(iu, patch); if (reqs.length == 0) return; @@ -427,16 +443,16 @@ public class Projector { // noop(IU)-> ~ABS // IU -> (noop(IU) or ABS) // Therefore we only need one optional requirement statement per IU - List optionalAbstractRequirements = new ArrayList(); + List optionalAbstractRequirements = new ArrayList(); for (int i = 0; i < reqs.length; i++) { //The requirement is unchanged if (reqs[i][0] == reqs[i][1]) { if (!isApplicable(reqs[i][0])) continue; - List patchesAppliedElseWhere = (List) unchangedRequirements.get(reqs[i][0]); + List patchesAppliedElseWhere = unchangedRequirements.get(reqs[i][0]); if (patchesAppliedElseWhere == null) { - patchesAppliedElseWhere = new ArrayList(); + patchesAppliedElseWhere = new ArrayList(); unchangedRequirements.put(reqs[i][0], patchesAppliedElseWhere); } patchesAppliedElseWhere.add(patch); @@ -446,16 +462,16 @@ public class Projector { //Generate dependency when the patch is applied //P1 -> (A -> D) equiv. (P1 & A) -> D if (isApplicable(reqs[i][1])) { - IRequiredCapability req = reqs[i][1]; - List matches = getApplicableMatches(req); + IRequirement req = reqs[i][1]; + List matches = getApplicableMatches(req); if (isHostRequirement(iu, req)) { - rememberHostMatches(iu, matches); + rememberHostMatches((IInstallableUnitFragment) iu, matches); } - if (!req.isOptional()) { + if (req.getMin() > 0) { if (matches.isEmpty()) { missingRequirement(patch, req); } else { - IInstallableUnit reqIu = (IInstallableUnit) picker.query(new CapabilityQuery(req), new Collector(), null).iterator().next(); + IInstallableUnit reqIu = matches.get(0); Explanation explanation; if (isRootIu) { if (alreadyInstalledIUs.contains(reqIu)) { @@ -479,17 +495,26 @@ public class Projector { //Generate dependency when the patch is not applied //-P1 -> (A -> B) ( equiv. A -> (P1 or B) ) if (isApplicable(reqs[i][0])) { - IRequiredCapability req = reqs[i][0]; - List matches = getApplicableMatches(req); + IRequirement req = reqs[i][0]; + + // Fix: if multiple patches apply to the same IU-req, we need to make sure we list each + // patch as an optional match + Pending pending = nonPatchedRequirements.get(req); + if (pending != null) { + pending.matches.add(patch); + continue; + } + + List matches = getApplicableMatches(req); if (isHostRequirement(iu, req)) { - rememberHostMatches(iu, matches); + rememberHostMatches((IInstallableUnitFragment) iu, matches); } - if (!req.isOptional()) { + if (req.getMin() > 0) { if (matches.isEmpty()) { dependencyHelper.implication(new Object[] {iu}).implies(patch).named(new Explanation.HardRequirement(iu, null)); } else { matches.add(patch); - IInstallableUnit reqIu = (IInstallableUnit) picker.query(new CapabilityQuery(req), new Collector(), null).iterator().next(); + IInstallableUnit reqIu = matches.get(0);///(IInstallableUnit) picker.query(new CapabilityQuery(req), new Collector(), null).iterator().next(); Explanation explanation; if (isRootIu) { @@ -501,13 +526,26 @@ public class Projector { } else { explanation = new Explanation.HardRequirement(iu, req); } - createImplication(iu, matches, explanation); + + // Fix: make sure we collect all patches that will impact this IU-req, not just one + pending = new Pending(); + pending.left = iu; + pending.explanation = explanation; + pending.matches = matches; + nonPatchedRequirements.put(req, pending); } } else { if (!matches.isEmpty()) { AbstractVariable abs = getAbstractVariable(); matches.add(patch); - createImplication(new Object[] {abs, iu}, matches, Explanation.OPTIONAL_REQUIREMENT); + + // Fix: make sure we collect all patches that will impact this IU-req, not just one + pending = new Pending(); + pending.left = new Object[] {abs, iu}; + pending.explanation = Explanation.OPTIONAL_REQUIREMENT; + pending.matches = matches; + nonPatchedRequirements.put(req, pending); + optionalAbstractRequirements.add(abs); } } @@ -515,23 +553,28 @@ public class Projector { } createOptionalityExpression(iu, optionalAbstractRequirements); } - List optionalAbstractRequirements = new ArrayList(); - for (Iterator iterator = unchangedRequirements.entrySet().iterator(); iterator.hasNext();) { - Entry entry = (Entry) iterator.next(); - List patchesApplied = (List) entry.getValue(); - List allPatches = new ArrayList(applicablePatches.toCollection()); - allPatches.removeAll(patchesApplied); - List requiredPatches = new ArrayList(); - for (Iterator iterator2 = allPatches.iterator(); iterator2.hasNext();) { - IInstallableUnitPatch patch = (IInstallableUnitPatch) iterator2.next(); - requiredPatches.add(patch); + + // Fix: now create the pending non-patch requirements based on the full set of patches + for (Pending pending : nonPatchedRequirements.values()) { + createImplication(pending.left, pending.matches, pending.explanation); + } + + List optionalAbstractRequirements = new ArrayList(); + for (Entry> entry : unchangedRequirements.entrySet()) { + List patchesApplied = entry.getValue(); + Iterator allPatches = applicablePatches.iterator(); + List requiredPatches = new ArrayList(); + while (allPatches.hasNext()) { + IInstallableUnitPatch patch = (IInstallableUnitPatch) allPatches.next(); + if (!patchesApplied.contains(patch)) + requiredPatches.add(patch); } - IRequiredCapability req = (IRequiredCapability) entry.getKey(); - List matches = getApplicableMatches(req); + IRequirement req = entry.getKey(); + List matches = getApplicableMatches(req); if (isHostRequirement(iu, req)) { - rememberHostMatches(iu, matches); + rememberHostMatches((IInstallableUnitFragment) iu, matches); } - if (!req.isOptional()) { + if (req.getMin() > 0) { if (matches.isEmpty()) { if (requiredPatches.isEmpty()) { missingRequirement(iu, req); @@ -541,7 +584,7 @@ public class Projector { } else { if (!requiredPatches.isEmpty()) matches.addAll(requiredPatches); - IInstallableUnit reqIu = (IInstallableUnit) picker.query(new CapabilityQuery(req), new Collector(), null).iterator().next(); + IInstallableUnit reqIu = matches.get(0);//(IInstallableUnit) picker.query(new CapabilityQuery(req), new Collector(), null).iterator().next(); Explanation explanation; if (isRootIu) { if (alreadyInstalledIUs.contains(reqIu)) { @@ -571,13 +614,13 @@ public class Projector { if (!(iu instanceof IInstallableUnitPatch)) return; IInstallableUnitPatch patch = (IInstallableUnitPatch) iu; - IRequiredCapability req = patch.getLifeCycle(); + IRequirement req = patch.getLifeCycle(); if (req == null) return; - expandRequirement(req, iu, Collections.EMPTY_LIST, isRootIu); + expandRequirement(req, iu, CollectionUtils. emptyList(), isRootIu); } - private void missingRequirement(IInstallableUnit iu, IRequiredCapability req) throws ContradictionException { + private void missingRequirement(IInstallableUnit iu, IRequirement req) throws ContradictionException { result.add(new Status(IStatus.WARNING, DirectorActivator.PI_DIRECTOR, NLS.bind(Messages.Planner_Unsatisfied_dependency, iu, req))); createNegation(iu, req); } @@ -586,11 +629,11 @@ public class Projector { * @param req * @return a list of mandatory requirements if any, an empty list if req.isOptional(). */ - private List getApplicableMatches(IRequiredCapability req) { - List target = new ArrayList(); - Collector matches = picker.query(new CapabilityQuery(req), new Collector(), null); - for (Iterator iterator = matches.iterator(); iterator.hasNext();) { - IInstallableUnit match = (IInstallableUnit) iterator.next(); + private List getApplicableMatches(IRequirement req) { + List target = new ArrayList(); + IQueryResult matches = picker.query(new ExpressionQuery(IInstallableUnit.class, req.getMatches()), null); + for (Iterator iterator = matches.iterator(); iterator.hasNext();) { + IInstallableUnit match = iterator.next(); if (isApplicable(match)) { target.add(match); } @@ -599,36 +642,37 @@ public class Projector { } //Return a new array of requirements representing the application of the patch - private IRequiredCapability[][] mergeRequirements(IInstallableUnit iu, IInstallableUnitPatch patch) { + private IRequirement[][] mergeRequirements(IInstallableUnit iu, IInstallableUnitPatch patch) { if (patch == null) return null; - IRequirementChange[] changes = patch.getRequirementsChange(); - IRequiredCapability[] originalRequirements = new IRequiredCapability[iu.getRequiredCapabilities().length]; - System.arraycopy(iu.getRequiredCapabilities(), 0, originalRequirements, 0, originalRequirements.length); - List rrr = new ArrayList(); + List changes = patch.getRequirementsChange(); + Collection iuRequirements = iu.getRequiredCapabilities(); + IRequirement[] originalRequirements = iuRequirements.toArray(new IRequirement[iuRequirements.size()]); + List rrr = new ArrayList(); boolean found = false; - for (int i = 0; i < changes.length; i++) { + for (int i = 0; i < changes.size(); i++) { + IRequirementChange change = changes.get(i); for (int j = 0; j < originalRequirements.length; j++) { - if (originalRequirements[j] != null && changes[i].matches(originalRequirements[j])) { + if (originalRequirements[j] != null && change.matches((IRequiredCapability) originalRequirements[j])) { found = true; - if (changes[i].newValue() != null) - rrr.add(new IRequiredCapability[] {originalRequirements[j], changes[i].newValue()}); + if (change.newValue() != null) + rrr.add(new IRequirement[] {originalRequirements[j], change.newValue()}); else // case where a requirement is removed - rrr.add(new IRequiredCapability[] {originalRequirements[j], null}); + rrr.add(new IRequirement[] {originalRequirements[j], null}); originalRequirements[j] = null; } // break; } - if (!found && changes[i].applyOn() == null && changes[i].newValue() != null) //Case where a new requirement is added - rrr.add(new IRequiredCapability[] {null, changes[i].newValue()}); + if (!found && change.applyOn() == null && change.newValue() != null) //Case where a new requirement is added + rrr.add(new IRequirement[] {null, change.newValue()}); } //Add all the unmodified requirements to the result for (int i = 0; i < originalRequirements.length; i++) { if (originalRequirements[i] != null) - rrr.add(new IRequiredCapability[] {originalRequirements[i], originalRequirements[i]}); + rrr.add(new IRequirement[] {originalRequirements[i], originalRequirements[i]}); } - return (IRequiredCapability[][]) rrr.toArray(new IRequiredCapability[rrr.size()][]); + return rrr.toArray(new IRequirement[rrr.size()][]); } /** @@ -640,12 +684,11 @@ public class Projector { * @param optionalRequirements * @throws ContradictionException */ - private void createOptionalityExpression(IInstallableUnit iu, List optionalRequirements) throws ContradictionException { + private void createOptionalityExpression(IInstallableUnit iu, List optionalRequirements) throws ContradictionException { if (optionalRequirements.isEmpty()) return; AbstractVariable noop = getNoOperationVariable(iu); - for (Iterator i = optionalRequirements.iterator(); i.hasNext();) { - AbstractVariable abs = (AbstractVariable) i.next(); + for (AbstractVariable abs : optionalRequirements) { createIncompatibleValues(abs, noop); } optionalRequirements.add(noop); @@ -653,24 +696,22 @@ public class Projector { } //This will create as many implication as there is element in the right argument - private void createNegationImplication(Object left, List right, Explanation name) throws ContradictionException { + private void createNegationImplication(Object left, List right, Explanation name) throws ContradictionException { if (DEBUG) { Tracing.debug(name + ": " + left + "->" + right); //$NON-NLS-1$ //$NON-NLS-2$ } - for (Iterator iterator = right.iterator(); iterator.hasNext();) { - dependencyHelper.implication(new Object[] {left}).impliesNot(iterator.next()).named(name); - } - + for (Object r : right) + dependencyHelper.implication(new Object[] {left}).impliesNot(r).named(name); } - private void createImplication(Object left, List right, Explanation name) throws ContradictionException { + private void createImplication(Object left, List right, Explanation name) throws ContradictionException { if (DEBUG) { Tracing.debug(name + ": " + left + "->" + right); //$NON-NLS-1$ //$NON-NLS-2$ } dependencyHelper.implication(new Object[] {left}).implies(right.toArray()).named(name); } - private void createImplication(Object[] left, List right, Explanation name) throws ContradictionException { + private void createImplication(Object[] left, List right, Explanation name) throws ContradictionException { if (DEBUG) { Tracing.debug(name + ": " + Arrays.asList(left) + "->" + right); //$NON-NLS-1$ //$NON-NLS-2$ } @@ -678,28 +719,26 @@ public class Projector { } //Return IUPatches that are applicable for the given iu - private Collector getApplicablePatches(IInstallableUnit iu) { + private IQueryResult getApplicablePatches(IInstallableUnit iu) { if (patches == null) - patches = new QueryableArray((IInstallableUnit[]) picker.query(ApplicablePatchQuery.ANY, new Collector(), null).toArray(IInstallableUnit.class)); + patches = new QueryableArray(picker.query(new PatchQuery(), null).toArray(IInstallableUnit.class)); - return patches.query(new ApplicablePatchQuery(iu), new Collector(), null); + return patches.query(new ApplicablePatchQuery(iu), null); } //Create constraints to deal with singleton //When there is a mix of singleton and non singleton, several constraints are generated private void createConstraintsForSingleton() throws ContradictionException { - Set s = slice.entrySet(); - for (Iterator iterator = s.iterator(); iterator.hasNext();) { - Map.Entry entry = (Map.Entry) iterator.next(); - HashMap conflictingEntries = (HashMap) entry.getValue(); + Set>> s = slice.entrySet(); + for (Entry> entry : s) { + Map conflictingEntries = entry.getValue(); if (conflictingEntries.size() < 2) continue; - Collection conflictingVersions = conflictingEntries.values(); - List singletons = new ArrayList(); - List nonSingletons = new ArrayList(); - for (Iterator conflictIterator = conflictingVersions.iterator(); conflictIterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) conflictIterator.next(); + Collection conflictingVersions = conflictingEntries.values(); + List singletons = new ArrayList(); + List nonSingletons = new ArrayList(); + for (IInstallableUnit iu : conflictingVersions) { if (iu.isSingleton()) { singletons.add(iu); } else { @@ -711,12 +750,12 @@ public class Projector { IInstallableUnit[] singletonArray; if (nonSingletons.isEmpty()) { - singletonArray = (IInstallableUnit[]) singletons.toArray(new IInstallableUnit[singletons.size()]); + singletonArray = singletons.toArray(new IInstallableUnit[singletons.size()]); createAtMostOne(singletonArray); } else { - singletonArray = (IInstallableUnit[]) singletons.toArray(new IInstallableUnit[singletons.size() + 1]); - for (Iterator iterator2 = nonSingletons.iterator(); iterator2.hasNext();) { - singletonArray[singletonArray.length - 1] = (IInstallableUnit) iterator2.next(); + singletonArray = singletons.toArray(new IInstallableUnit[singletons.size() + 1]); + for (IInstallableUnit nonSingleton : nonSingletons) { + singletonArray[singletonArray.length - 1] = nonSingleton; createAtMostOne(singletonArray); } } @@ -731,7 +770,7 @@ public class Projector { } Tracing.debug("At most 1 of " + b); //$NON-NLS-1$ } - dependencyHelper.atMost(1, ius).named(new Explanation.Singleton(ius)); + dependencyHelper.atMost(1, (Object[]) ius).named(new Explanation.Singleton(ius)); } private void createIncompatibleValues(AbstractVariable v1, AbstractVariable v2) throws ContradictionException { @@ -743,7 +782,7 @@ public class Projector { } Tracing.debug("At most 1 of " + b); //$NON-NLS-1$ } - dependencyHelper.atMost(1, vars).named(Explanation.OPTIONAL_REQUIREMENT); + dependencyHelper.atMost(1, (Object[]) vars).named(Explanation.OPTIONAL_REQUIREMENT); } private AbstractVariable getAbstractVariable() { @@ -753,7 +792,7 @@ public class Projector { } private AbstractVariable getNoOperationVariable(IInstallableUnit iu) { - AbstractVariable v = (AbstractVariable) noopVariables.get(iu); + AbstractVariable v = noopVariables.get(iu); if (v == null) { v = new AbstractVariable(); noopVariables.put(iu, v); @@ -798,10 +837,10 @@ public class Projector { } private void backToIU() { - solution = new ArrayList(); - IVec sat4jSolution = dependencyHelper.getSolution(); - for (Iterator i = sat4jSolution.iterator(); i.hasNext();) { - Object var = i.next(); + solution = new ArrayList(); + IVec sat4jSolution = dependencyHelper.getSolution(); + for (Iterator iter = sat4jSolution.iterator(); iter.hasNext();) { + Object var = iter.next(); if (var instanceof IInstallableUnit) { IInstallableUnit iu = (IInstallableUnit) var; if (iu == entryPoint) @@ -811,23 +850,23 @@ public class Projector { } } - private void printSolution(Collection state) { - ArrayList l = new ArrayList(state); + private void printSolution(Collection state) { + ArrayList l = new ArrayList(state); Collections.sort(l); Tracing.debug("Solution:"); //$NON-NLS-1$ Tracing.debug("Numbers of IUs selected: " + l.size()); //$NON-NLS-1$ - for (Iterator iterator = l.iterator(); iterator.hasNext();) { - Tracing.debug(iterator.next().toString()); + for (IInstallableUnit s : l) { + Tracing.debug(s.toString()); } } - public Collection extractSolution() { + public Collection extractSolution() { if (DEBUG) printSolution(solution); return solution; } - public Set getExplanation(IProgressMonitor monitor) { + public Set getExplanation(IProgressMonitor monitor) { ExplanationJob job = new ExplanationJob(); job.schedule(); monitor.setTaskName(Messages.Planner_NoSolution); @@ -855,16 +894,14 @@ public class Projector { return job.getExplanationResult(); } - public Map getFragmentAssociation() { - Map resolvedFragments = new HashMap(fragments.size()); - for (Iterator iterator = fragments.entrySet().iterator(); iterator.hasNext();) { - Entry fragment = (Entry) iterator.next(); + public Map> getFragmentAssociation() { + Map> resolvedFragments = new HashMap>(fragments.size()); + for (Entry> fragment : fragments.entrySet()) { if (!dependencyHelper.getBooleanValueFor(fragment.getKey())) continue; - Set potentialHosts = (Set) fragment.getValue(); - List resolvedHost = new ArrayList(potentialHosts.size()); - for (Iterator iterator2 = potentialHosts.iterator(); iterator2.hasNext();) { - Object host = iterator2.next(); + Set potentialHosts = fragment.getValue(); + List resolvedHost = new ArrayList(potentialHosts.size()); + for (IInstallableUnit host : potentialHosts) { if (dependencyHelper.getBooleanValueFor(host)) resolvedHost.add(host); } @@ -874,26 +911,26 @@ public class Projector { return resolvedFragments; } - private void rememberHostMatches(IInstallableUnit fragment, List matches) { - Set existingMatches = (Set) fragments.get(fragment); + private void rememberHostMatches(IInstallableUnitFragment fragment, List matches) { + Set existingMatches = fragments.get(fragment); if (existingMatches == null) { - existingMatches = new HashSet(); + existingMatches = new HashSet(); fragments.put(fragment, existingMatches); existingMatches.addAll(matches); } existingMatches.retainAll(matches); } - private boolean isHostRequirement(IInstallableUnit iu, IRequiredCapability req) { + private boolean isHostRequirement(IInstallableUnit iu, IRequirement req) { if (!(iu instanceof IInstallableUnitFragment)) return false; IInstallableUnitFragment fragment = (IInstallableUnitFragment) iu; - IRequiredCapability[] reqs = fragment.getHost(); + IRequirement[] reqs = fragment.getHost(); for (int i = 0; i < reqs.length; i++) { - if (req == reqs[i]) + if (req.equals(reqs[i])) return true; } - return true; + return false; } } \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/QueryableArray.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/QueryableArray.java index 80f500296..1a250b301 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/QueryableArray.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/QueryableArray.java @@ -12,70 +12,56 @@ package org.eclipse.equinox.internal.p2.director; import java.util.*; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.p2.metadata.ORRequirement; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.internal.p2.metadata.RequiredCapability; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IProvidedCapability; +import org.eclipse.equinox.p2.metadata.expression.IMatchExpression; +import org.eclipse.equinox.p2.metadata.query.ExpressionQuery; +import org.eclipse.equinox.p2.query.*; -public class QueryableArray implements IQueryable { - static class IUCapability { - final IInstallableUnit iu; - final IProvidedCapability capability; - - public IUCapability(IInstallableUnit iu, IProvidedCapability capability) { - this.iu = iu; - this.capability = capability; - } - } - - private final List dataSet; - private Map namedCapabilityIndex; +public class QueryableArray implements IQueryable { + private final List dataSet; + private Map> namedCapabilityIndex; public QueryableArray(IInstallableUnit[] ius) { dataSet = Arrays.asList(ius); } - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - if (query instanceof CapabilityQuery) - return queryCapability((CapabilityQuery) query, collector, monitor); - return query.perform(dataSet.iterator(), collector); + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + if (query instanceof ExpressionQuery) + return queryCapability((ExpressionQuery) query, new Collector(), monitor); + return query.perform(dataSet.iterator()); } - private Collector queryCapability(CapabilityQuery query, Collector collector, IProgressMonitor monitor) { + private Collector queryCapability(ExpressionQuery query, Collector collector, IProgressMonitor monitor) { generateNamedCapabilityIndex(); - IRequiredCapability[] requiredCapabilities = query.getRequiredCapabilities(); - Collection resultIUs = null; - for (int i = 0; i < requiredCapabilities.length; i++) { - if (requiredCapabilities[i] instanceof ORRequirement) { - query.perform(dataSet.iterator(), collector); - continue; - } - Collection matchingIUs = findMatchingIUs(requiredCapabilities[i]); - if (matchingIUs == null) - return collector; - if (resultIUs == null) - resultIUs = matchingIUs; - else - resultIUs.retainAll(matchingIUs); - } + Collection resultIUs = null; + Collection matchingIUs = findMatchingIUs(query.getExpression()); + if (matchingIUs == null) + return collector; + if (resultIUs == null) + resultIUs = matchingIUs; + else + resultIUs.retainAll(matchingIUs); if (resultIUs != null) - for (Iterator iterator = resultIUs.iterator(); iterator.hasNext();) + for (Iterator iterator = resultIUs.iterator(); iterator.hasNext();) collector.accept(iterator.next()); return collector; } - private Collection findMatchingIUs(IRequiredCapability requiredCapability) { - List iuCapabilities = (List) namedCapabilityIndex.get(requiredCapability.getName()); - if (iuCapabilities == null) + private Collection findMatchingIUs(IMatchExpression requirementMatch) { + // TODO: This is a hack. Should be replaced by use of proper indexes + List ius = namedCapabilityIndex.get(RequiredCapability.extractName(requirementMatch)); + if (ius == null) return null; - Set matchingIUs = new HashSet(); - for (Iterator iterator = iuCapabilities.iterator(); iterator.hasNext();) { - IUCapability iuCapability = (IUCapability) iterator.next(); - if (iuCapability.capability.satisfies(requiredCapability)) - matchingIUs.add(iuCapability.iu); + Set matchingIUs = new HashSet(); + for (IInstallableUnit iu : ius) { + if (requirementMatch.isMatch(iu)) + matchingIUs.add(iu); } return matchingIUs; } @@ -84,19 +70,18 @@ public class QueryableArray implements IQueryable { if (namedCapabilityIndex != null) return; - namedCapabilityIndex = new HashMap(); - for (Iterator iterator = dataSet.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); + namedCapabilityIndex = new HashMap>(); + for (IInstallableUnit iu : dataSet) { - IProvidedCapability[] providedCapabilities = iu.getProvidedCapabilities(); - for (int i = 0; i < providedCapabilities.length; i++) { - String name = providedCapabilities[i].getName(); - List iuCapabilities = (List) namedCapabilityIndex.get(name); - if (iuCapabilities == null) { - iuCapabilities = new ArrayList(5); - namedCapabilityIndex.put(name, iuCapabilities); + Collection providedCapabilities = iu.getProvidedCapabilities(); + for (IProvidedCapability pc : providedCapabilities) { + String name = pc.getName(); + List ius = namedCapabilityIndex.get(name); + if (ius == null) { + ius = new ArrayList(5); + namedCapabilityIndex.put(name, ius); } - iuCapabilities.add(new IUCapability(iu, providedCapabilities[i])); + ius.add(iu); } } } diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/SimpleDirector.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/SimpleDirector.java index 884c422f7..58bce1e85 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/SimpleDirector.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/SimpleDirector.java @@ -10,8 +10,8 @@ package org.eclipse.equinox.internal.p2.director; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.osgi.util.NLS; public class SimpleDirector implements IDirector { @@ -32,7 +32,7 @@ public class SimpleDirector implements IDirector { public IStatus revert(IProfile currentProfile, IProfile revertProfile, ProvisioningContext context, IProgressMonitor monitor) { SubMonitor sub = SubMonitor.convert(monitor, Messages.Director_Task_Updating, PlanWork + EngineWork); try { - ProvisioningPlan plan = planner.getDiffPlan(currentProfile, revertProfile, sub.newChild(PlanWork)); + IProvisioningPlan plan = planner.getDiffPlan(currentProfile, revertProfile, sub.newChild(PlanWork)); return PlanExecutionHelper.executePlan(plan, engine, context, sub.newChild(EngineWork)); } finally { sub.done(); @@ -46,9 +46,9 @@ public class SimpleDirector implements IDirector { IInstallableUnit[] installRoots = request.getAddedInstallableUnits(); // mark the roots as such for (int i = 0; i < installRoots.length; i++) { - request.setInstallableUnitProfileProperty(installRoots[i], IInstallableUnit.PROP_PROFILE_ROOT_IU, Boolean.toString(true)); + request.setInstallableUnitProfileProperty(installRoots[i], IProfile.PROP_PROFILE_ROOT_IU, Boolean.toString(true)); } - ProvisioningPlan plan = planner.getProvisioningPlan(request, context, sub.newChild(PlanWork)); + IProvisioningPlan plan = planner.getProvisioningPlan(request, context, sub.newChild(PlanWork)); return PlanExecutionHelper.executePlan(plan, engine, context, sub.newChild(EngineWork)); } finally { sub.done(); diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/SimplePlanner.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/SimplePlanner.java index 719a69293..71304c460 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/SimplePlanner.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/SimplePlanner.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. All rights reserved. This + * Copyright (c) 2007, 2010 IBM Corporation and others. All rights reserved. This * program and the accompanying materials are made available under the terms of * the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html @@ -16,16 +16,21 @@ import java.util.Map.Entry; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.core.helpers.Tracing; +import org.eclipse.equinox.internal.p2.metadata.query.UpdateQuery; import org.eclipse.equinox.internal.p2.rollback.FormerState; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.query.IUProfilePropertyQuery; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.ExpressionQuery; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.util.NLS; public class SimplePlanner implements IPlanner { @@ -41,39 +46,43 @@ public class SimplePlanner implements IPlanner { private final IMetadataRepositoryManager repoManager; private final IProfileRegistry profileRegistry; - private ProvisioningPlan generateProvisioningPlan(Collection fromState, Collection toState, ProfileChangeRequest changeRequest, ProvisioningPlan installerPlan) { - InstallableUnitOperand[] iuOperands = generateOperations(fromState, toState); + private ProvisioningPlan generateProvisioningPlan(Collection fromState, Collection toState, ProfileChangeRequest changeRequest, IProvisioningPlan installerPlan, ProvisioningContext context) { + List iuOperands = generateOperations(fromState, toState); PropertyOperand[] propertyOperands = generatePropertyOperations(changeRequest); - Operand[] operands = new Operand[iuOperands.length + propertyOperands.length]; - System.arraycopy(iuOperands, 0, operands, 0, iuOperands.length); - System.arraycopy(propertyOperands, 0, operands, iuOperands.length, propertyOperands.length); + int iuOpsSize = iuOperands.size(); + Operand[] operands = new Operand[iuOpsSize + propertyOperands.length]; + for (int i = 0; i < iuOpsSize; ++i) + operands[i] = iuOperands.get(i); + System.arraycopy(propertyOperands, 0, operands, iuOpsSize, propertyOperands.length); if (DEBUG) { for (int i = 0; i < operands.length; i++) { Tracing.debug(operands[i].toString()); } } - return new ProvisioningPlan(Status.OK_STATUS, operands, computeActualChangeRequest(toState, changeRequest), null, installerPlan, changeRequest, new QueryableArray((IInstallableUnit[]) toState.toArray(new IInstallableUnit[toState.size()]))); + return new ProvisioningPlan(Status.OK_STATUS, operands, computeActualChangeRequest(toState, changeRequest), null, installerPlan, changeRequest.getProfile(), new QueryableArray(toState.toArray(new IInstallableUnit[toState.size()])), context); } - private Map[] buildDetailedErrors(ProfileChangeRequest changeRequest) { + private Map[] buildDetailedErrors(ProfileChangeRequest changeRequest) { IInstallableUnit[] added = changeRequest.getAddedInstallableUnits(); IInstallableUnit[] removed = changeRequest.getRemovedInstallableUnits(); - Map requestStatus = new HashMap(added.length + removed.length); + Map requestStatus = new HashMap(added.length + removed.length); for (int i = 0; i < added.length; i++) { requestStatus.put(added[i], new RequestStatus(added[i], RequestStatus.ADDED, IStatus.ERROR, null)); } for (int i = 0; i < removed.length; i++) { requestStatus.put(removed[i], new RequestStatus(removed[i], RequestStatus.REMOVED, IStatus.ERROR, null)); } - return new Map[] {requestStatus, null}; + @SuppressWarnings("unchecked") + Map[] maps = new Map[] {requestStatus, null}; + return maps; } - private Map[] computeActualChangeRequest(Collection toState, ProfileChangeRequest changeRequest) { + private Map[] computeActualChangeRequest(Collection toState, ProfileChangeRequest changeRequest) { IInstallableUnit[] added = changeRequest.getAddedInstallableUnits(); IInstallableUnit[] removed = changeRequest.getRemovedInstallableUnits(); - Map requestStatus = new HashMap(added.length + removed.length); + Map requestStatus = new HashMap(added.length + removed.length); for (int i = 0; i < added.length; i++) { if (toState.contains(added[i])) requestStatus.put(added[i], new RequestStatus(added[i], RequestStatus.ADDED, IStatus.OK, null)); @@ -89,37 +98,34 @@ public class SimplePlanner implements IPlanner { } //Compute the side effect changes (e.g. things installed optionally going away) - Collection includedIUs = new HashSet(changeRequest.getProfile().query(new IUProfilePropertyQuery(INCLUSION_RULES, null), new Collector(), null).toCollection()); - Map sideEffectStatus = new HashMap(includedIUs.size()); - includedIUs.removeAll(toState); - for (Iterator iterator = includedIUs.iterator(); iterator.hasNext();) { - IInstallableUnit removal = (IInstallableUnit) iterator.next(); - if (!requestStatus.containsKey(removal)) + Iterator includedIUs = changeRequest.getProfile().query(new IUProfilePropertyQuery(INCLUSION_RULES, null), null).iterator(); + Map sideEffectStatus = new HashMap(); + while (includedIUs.hasNext()) { + IInstallableUnit removal = includedIUs.next(); + if (!toState.contains(removal) && !requestStatus.containsKey(removal)) { sideEffectStatus.put(removal, new RequestStatus(removal, RequestStatus.REMOVED, IStatus.INFO, null)); + } } - return new Map[] {requestStatus, sideEffectStatus}; + @SuppressWarnings("unchecked") + Map[] maps = new Map[] {requestStatus, sideEffectStatus}; + return maps; } /** * Converts a set containing a list of resolver explanations into a human-readable status object. */ - private IStatus convertExplanationToStatus(Set explanations) { + private IStatus convertExplanationToStatus(Set explanations) { if (explanations == null) return new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, Messages.Director_Unsatisfied_Dependencies); MultiStatus root = new MultiStatus(DirectorActivator.PI_DIRECTOR, 1, Messages.Director_Unsatisfied_Dependencies, null); //try to find a more specific root message if possible String specificMessage = null; - for (Iterator it = explanations.iterator(); it.hasNext();) { - final Object next = it.next(); - if (next instanceof Explanation) { - root.add(((Explanation) next).toStatus()); - if (specificMessage == null && next instanceof Explanation.MissingIU) - specificMessage = Messages.Explanation_rootMissing; - else if (specificMessage == null && next instanceof Explanation.Singleton) { - specificMessage = Messages.Explanation_rootSingleton; - } - } else - root.add(new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, next.toString())); + for (Explanation next : explanations) { + root.add(next.toStatus()); + if (specificMessage == null && next instanceof Explanation.MissingIU) + specificMessage = Messages.Explanation_rootMissing; + else if (specificMessage == null && next instanceof Explanation.Singleton) + specificMessage = Messages.Explanation_rootSingleton; } //use a more specific root message if available if (specificMessage != null) { @@ -132,60 +138,50 @@ public class SimplePlanner implements IPlanner { private PropertyOperand[] generatePropertyOperations(ProfileChangeRequest profileChangeRequest) { IProfile profile = profileChangeRequest.getProfile(); - List operands = new ArrayList(); + List operands = new ArrayList(); // First deal with profile properties to remove. Only generate an operand if the property was there in the first place String[] toRemove = profileChangeRequest.getPropertiesToRemove(); - Map existingProperties = profile.getProperties(); + Map existingProperties = profile.getProperties(); for (int i = 0; i < toRemove.length; i++) { if (existingProperties.containsKey(toRemove[i])) operands.add(new PropertyOperand(toRemove[i], existingProperties.get(toRemove[i]), null)); } // Now deal with profile property changes/additions - Map propertyChanges = profileChangeRequest.getPropertiesToAdd(); - Iterator iter = propertyChanges.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = (Map.Entry) iter.next(); - operands.add(new PropertyOperand((String) entry.getKey(), existingProperties.get(entry.getKey()), entry.getValue())); + Map propertyChanges = profileChangeRequest.getPropertiesToAdd(); + for (Entry entry : propertyChanges.entrySet()) { + operands.add(new PropertyOperand(entry.getKey(), existingProperties.get(entry.getKey()), entry.getValue())); } // Now deal with iu property changes/additions. // TODO we aren't yet checking that the IU will exist in the final profile, will the engine do this? - Map allIUPropertyChanges = profileChangeRequest.getInstallableUnitProfilePropertiesToAdd(); - iter = allIUPropertyChanges.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = (Map.Entry) iter.next(); - IInstallableUnit iu = (IInstallableUnit) entry.getKey(); - Map iuPropertyChanges = (Map) entry.getValue(); - Iterator iuPropIter = iuPropertyChanges.entrySet().iterator(); - while (iuPropIter.hasNext()) { - Map.Entry entry2 = (Map.Entry) iuPropIter.next(); - Object oldValue = profile.getInstallableUnitProperty(iu, (String) entry2.getKey()); - operands.add(new InstallableUnitPropertyOperand(iu, (String) entry2.getKey(), oldValue, entry2.getValue())); + Map> allIUPropertyChanges = profileChangeRequest.getInstallableUnitProfilePropertiesToAdd(); + for (Entry> entry : allIUPropertyChanges.entrySet()) { + IInstallableUnit iu = entry.getKey(); + for (Entry entry2 : entry.getValue().entrySet()) { + Object oldValue = profile.getInstallableUnitProperty(iu, entry2.getKey()); + operands.add(new InstallableUnitPropertyOperand(iu, entry2.getKey(), oldValue, entry2.getValue())); } } // Now deal with iu property removals. // TODO we could optimize by not generating property removals for IU's that aren't there or won't be there. - Map allIUPropertyDeletions = profileChangeRequest.getInstallableUnitProfilePropertiesToRemove(); - iter = allIUPropertyDeletions.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = (Map.Entry) iter.next(); - IInstallableUnit iu = (IInstallableUnit) entry.getKey(); - Map existingIUProperties = profile.getInstallableUnitProperties(iu); - List iuPropertyRemovals = (List) entry.getValue(); - for (Iterator it = iuPropertyRemovals.iterator(); it.hasNext();) { - String key = (String) it.next(); + Map> allIUPropertyDeletions = profileChangeRequest.getInstallableUnitProfilePropertiesToRemove(); + for (Entry> entry : allIUPropertyDeletions.entrySet()) { + IInstallableUnit iu = entry.getKey(); + Map existingIUProperties = profile.getInstallableUnitProperties(iu); + List iuPropertyRemovals = entry.getValue(); + for (String key : iuPropertyRemovals) { if (existingIUProperties.containsKey(key)) operands.add(new InstallableUnitPropertyOperand(iu, key, existingIUProperties.get(key), null)); } } - return (PropertyOperand[]) operands.toArray(new PropertyOperand[operands.size()]); + return operands.toArray(new PropertyOperand[operands.size()]); } - private InstallableUnitOperand[] generateOperations(Collection fromState, Collection toState) { + private List generateOperations(Collection fromState, Collection toState) { return new OperationGenerator().generateOperation(fromState, toState); } - public ProvisioningPlan getDiffPlan(IProfile currentProfile, IProfile targetProfile, IProgressMonitor monitor) { + public IProvisioningPlan getDiffPlan(IProfile currentProfile, IProfile targetProfile, IProgressMonitor monitor) { SubMonitor sub = SubMonitor.convert(monitor, ExpandWork); sub.setTaskName(Messages.Director_Task_Resolving_Dependencies); try { @@ -193,7 +189,7 @@ public class SimplePlanner implements IPlanner { ProvisioningContext context = new ProvisioningContext(new URI[0]); if (context.getProperty(INCLUDE_PROFILE_IUS) == null) context.setProperty(INCLUDE_PROFILE_IUS, Boolean.FALSE.toString()); - context.setExtraIUs(new ArrayList(targetProfile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection())); + context.setExtraIUs(Arrays.asList(targetProfile.available(InstallableUnitQuery.ANY, null).toArray(IInstallableUnit.class))); return getProvisioningPlan(profileChangeRequest, context, sub.newChild(ExpandWork / 2)); } finally { sub.done(); @@ -201,23 +197,13 @@ public class SimplePlanner implements IPlanner { } public static IInstallableUnit[] findPlannerMarkedIUs(final IProfile profile) { - Query markerQuery = new MatchQuery() { - public boolean isMatch(Object candidate) { - if (!(candidate instanceof IInstallableUnit)) - return false; - - IInstallableUnit iu = (IInstallableUnit) candidate; - - String inclusion = profile.getInstallableUnitProperty(iu, INCLUSION_RULES); - return (inclusion != null); - } - }; - return (IInstallableUnit[]) profile.query(markerQuery, new Collector(), null).toArray(IInstallableUnit.class); + IQuery markerQuery = new IUProfilePropertyQuery(INCLUSION_RULES, null); + return profile.query(markerQuery, null).toArray(IInstallableUnit.class); } - public static Dictionary createSelectionContext(Map properties) { - Hashtable result = new Hashtable(properties); - String environments = (String) properties.get(IProfile.PROP_ENVIRONMENTS); + public static Dictionary createSelectionContext(Map properties) { + Hashtable result = new Hashtable(properties); + String environments = properties.get(IProfile.PROP_ENVIRONMENTS); if (environments == null) return result; for (StringTokenizer tokenizer = new StringTokenizer(environments, ","); tokenizer.hasMoreElements();) { //$NON-NLS-1$ @@ -231,7 +217,7 @@ public class SimplePlanner implements IPlanner { } private IInstallableUnit[] gatherAvailableInstallableUnits(IInstallableUnit[] additionalSource, URI[] repositories, ProvisioningContext context, IProgressMonitor monitor) { - Map resultsMap = new HashMap(); + Map resultsMap = new HashMap(); if (additionalSource != null) { for (int i = 0; i < additionalSource.length; i++) { String key = additionalSource[i].getId() + "_" + additionalSource[i].getVersion().toString(); //$NON-NLS-1$ @@ -239,8 +225,7 @@ public class SimplePlanner implements IPlanner { } } if (context != null) { - for (Iterator iter = context.getExtraIUs().iterator(); iter.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iter.next(); + for (IInstallableUnit iu : context.getExtraIUs()) { String key = iu.getId() + '_' + iu.getVersion().toString(); resultsMap.put(key, iu); } @@ -256,11 +241,11 @@ public class SimplePlanner implements IPlanner { throw new OperationCanceledException(); IMetadataRepository repository = repoManager.loadRepository(repositories[i], sub.newChild(100)); - Collector matches = repository.query(new InstallableUnitQuery(null, VersionRange.emptyRange), new Collector(), sub.newChild(100)); - for (Iterator it = matches.iterator(); it.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) it.next(); + IQueryResult matches = repository.query(new InstallableUnitQuery(null, VersionRange.emptyRange), sub.newChild(100)); + for (Iterator it = matches.iterator(); it.hasNext();) { + IInstallableUnit iu = it.next(); String key = iu.getId() + "_" + iu.getVersion().toString(); //$NON-NLS-1$ - IInstallableUnit currentIU = (IInstallableUnit) resultsMap.get(key); + IInstallableUnit currentIU = resultsMap.get(key); if (currentIU == null || hasHigherFidelity(iu, currentIU)) resultsMap.put(key, iu); } @@ -269,8 +254,8 @@ public class SimplePlanner implements IPlanner { } } sub.done(); - Collection results = resultsMap.values(); - return (IInstallableUnit[]) results.toArray(new IInstallableUnit[results.size()]); + Collection results = resultsMap.values(); + return results.toArray(new IInstallableUnit[results.size()]); } private static boolean hasHigherFidelity(IInstallableUnit iu, IInstallableUnit currentIU) { @@ -286,10 +271,10 @@ public class SimplePlanner implements IPlanner { this.repoManager = repoManager; } - private boolean satisfyMetaRequirements(Map props) { + private boolean satisfyMetaRequirements(Map props) { if (props == null) return true; - if (props.get(CONSIDER_METAREQUIREMENTS) == null || "true".equalsIgnoreCase((String) props.get(CONSIDER_METAREQUIREMENTS))) //$NON-NLS-1$ + if (props.get(CONSIDER_METAREQUIREMENTS) == null || "true".equalsIgnoreCase(props.get(CONSIDER_METAREQUIREMENTS))) //$NON-NLS-1$ return true; return false; } @@ -308,33 +293,36 @@ public class SimplePlanner implements IPlanner { Object[] updatedPlan = updatePlannerInfo(profileChangeRequest, context); URI[] metadataRepositories = (context != null) ? context.getMetadataRepositories() : null; - Dictionary newSelectionContext = createSelectionContext(profileChangeRequest.getProfileProperties()); + Dictionary newSelectionContext = createSelectionContext(profileChangeRequest.getProfileProperties()); - List extraIUs = new ArrayList(Arrays.asList(profileChangeRequest.getAddedInstallableUnits())); + List extraIUs = new ArrayList(Arrays.asList(profileChangeRequest.getAddedInstallableUnits())); extraIUs.addAll(Arrays.asList(profileChangeRequest.getRemovedInstallableUnits())); - if (context == null || context.getProperty(INCLUDE_PROFILE_IUS) == null || context.getProperty(INCLUDE_PROFILE_IUS).equalsIgnoreCase(Boolean.TRUE.toString())) - extraIUs.addAll(profile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection()); + if (context == null || context.getProperty(INCLUDE_PROFILE_IUS) == null || context.getProperty(INCLUDE_PROFILE_IUS).equalsIgnoreCase(Boolean.TRUE.toString())) { + Iterator itor = profile.available(InstallableUnitQuery.ANY, null).iterator(); + while (itor.hasNext()) + extraIUs.add(itor.next()); + } - IInstallableUnit[] availableIUs = gatherAvailableInstallableUnits((IInstallableUnit[]) extraIUs.toArray(new IInstallableUnit[extraIUs.size()]), metadataRepositories, context, sub.newChild(ExpandWork / 4)); + IInstallableUnit[] availableIUs = gatherAvailableInstallableUnits(extraIUs.toArray(new IInstallableUnit[extraIUs.size()]), metadataRepositories, context, sub.newChild(ExpandWork / 4)); Slicer slicer = new Slicer(new QueryableArray(availableIUs), newSelectionContext, satisfyMetaRequirements(profileChangeRequest.getProfileProperties())); - IQueryable slice = slicer.slice(new IInstallableUnit[] {(IInstallableUnit) updatedPlan[0]}, sub.newChild(ExpandWork / 4)); + IQueryable slice = slicer.slice(new IInstallableUnit[] {(IInstallableUnit) updatedPlan[0]}, sub.newChild(ExpandWork / 4)); if (slice == null) - return new ProvisioningPlan(slicer.getStatus(), profileChangeRequest, null); + return new ProvisioningPlan(slicer.getStatus(), profile, null, context); Projector projector = new Projector(slice, newSelectionContext, satisfyMetaRequirements(profileChangeRequest.getProfileProperties())); - projector.encode((IInstallableUnit) updatedPlan[0], (IInstallableUnit[]) updatedPlan[1], profileChangeRequest.getAddedInstallableUnits(), sub.newChild(ExpandWork / 4)); + projector.encode((IInstallableUnit) updatedPlan[0], (IInstallableUnit[]) updatedPlan[1], profile, profileChangeRequest.getAddedInstallableUnits(), sub.newChild(ExpandWork / 4)); IStatus s = projector.invokeSolver(sub.newChild(ExpandWork / 4)); if (s.getSeverity() == IStatus.CANCEL) - return new ProvisioningPlan(s, profileChangeRequest, null); + return new ProvisioningPlan(s, profile, null, context); if (s.getSeverity() == IStatus.ERROR) { sub.setTaskName(Messages.Planner_NoSolution); if (context != null && !(context.getProperty(EXPLANATION) == null || Boolean.TRUE.toString().equalsIgnoreCase(context.getProperty(EXPLANATION)))) - return new ProvisioningPlan(s, profileChangeRequest, null); + return new ProvisioningPlan(s, profile, null, context); //Extract the explanation - Set explanation = projector.getExplanation(sub.newChild(ExpandWork / 4)); + Set explanation = projector.getExplanation(sub.newChild(ExpandWork / 4)); IStatus explanationStatus = convertExplanationToStatus(explanation); - return new ProvisioningPlan(explanationStatus, new Operand[0], buildDetailedErrors(profileChangeRequest), new RequestStatus(null, RequestStatus.REMOVED, IStatus.ERROR, explanation), null, profileChangeRequest, null); + return new ProvisioningPlan(explanationStatus, new Operand[0], buildDetailedErrors(profileChangeRequest), new RequestStatus(null, RequestStatus.REMOVED, IStatus.ERROR, explanation), null, profile, null, context); } //The resolution succeeded. We can forget about the warnings since there is a solution. if (Tracing.DEBUG && s.getSeverity() != IStatus.OK) @@ -347,70 +335,88 @@ public class SimplePlanner implements IPlanner { } } - public ProvisioningPlan getProvisioningPlan(ProfileChangeRequest profileChangeRequest, ProvisioningContext context, IProgressMonitor monitor) { + public IProvisioningPlan getProvisioningPlan(ProfileChangeRequest profileChangeRequest, ProvisioningContext context, IProgressMonitor monitor) { + if (profileChangeRequest.getAbsolute()) + return generateAbsoluteProvisioningPlan(profileChangeRequest, context, monitor); SubMonitor sub = SubMonitor.convert(monitor, ExpandWork); sub.setTaskName(Messages.Director_Task_Resolving_Dependencies); try { //Get the solution for the initial request Object resolutionResult = getSolutionFor(profileChangeRequest, context, sub.newChild(ExpandWork / 2)); - if (resolutionResult instanceof ProvisioningPlan) + if (resolutionResult instanceof IProvisioningPlan) return (ProvisioningPlan) resolutionResult; - Collection newState = ((Projector) resolutionResult).extractSolution(); - Collection fullState = new ArrayList(); + Collection newState = ((Projector) resolutionResult).extractSolution(); + Collection fullState = new ArrayList(); fullState.addAll(newState); - newState = AttachmentHelper.attachFragments(newState, ((Projector) resolutionResult).getFragmentAssociation()); + newState = AttachmentHelper.attachFragments(newState.iterator(), ((Projector) resolutionResult).getFragmentAssociation()); - ProvisioningPlan temporaryPlan = generatePlan((Projector) resolutionResult, newState, profileChangeRequest); + ProvisioningPlan temporaryPlan = generatePlan((Projector) resolutionResult, newState, profileChangeRequest, context); //Create a plan for installing necessary pieces to complete the installation (e.g touchpoint actions) return createInstallerPlan(profileChangeRequest.getProfile(), profileChangeRequest, fullState, newState, temporaryPlan, context, sub.newChild(ExpandWork / 2)); } catch (OperationCanceledException e) { - return new ProvisioningPlan(Status.CANCEL_STATUS, profileChangeRequest, null); + return new ProvisioningPlan(Status.CANCEL_STATUS, profileChangeRequest.getProfile(), null, context); } finally { sub.done(); } } + private IProvisioningPlan generateAbsoluteProvisioningPlan(ProfileChangeRequest profileChangeRequest, ProvisioningContext context, IProgressMonitor monitor) { + Set toState = profileChangeRequest.getProfile().query(InstallableUnitQuery.ANY, null).toSet(); + HashSet fromState = new HashSet(toState); + toState.removeAll(Arrays.asList(profileChangeRequest.getRemovedInstallableUnits())); + toState.addAll(Arrays.asList(profileChangeRequest.getAddedInstallableUnits())); + + List iuOperands = generateOperations(fromState, toState); + PropertyOperand[] propertyOperands = generatePropertyOperations(profileChangeRequest); + + int iuOpsSize = iuOperands.size(); + Operand[] operands = new Operand[iuOpsSize + propertyOperands.length]; + for (int i = 0; i < iuOpsSize; ++i) + operands[i] = iuOperands.get(i); + System.arraycopy(propertyOperands, 0, operands, iuOpsSize, propertyOperands.length); + + if (DEBUG) { + for (int i = 0; i < operands.length; i++) { + Tracing.debug(operands[i].toString()); + } + } + return new ProvisioningPlan(Status.OK_STATUS, operands, computeActualChangeRequest(toState, profileChangeRequest), null, null, profileChangeRequest.getProfile(), new QueryableArray(toState.toArray(new IInstallableUnit[toState.size()])), context); + + } + //Verify that all the meta requirements necessary to perform the uninstallation (if necessary) and all t - private Collection areMetaRequirementsSatisfied(IProfile oldProfile, Collection newProfile, ProvisioningPlan initialPlan) { - Collection allMetaRequirements = extractMetaRequirements(newProfile, initialPlan); - for (Iterator iterator = allMetaRequirements.iterator(); iterator.hasNext();) { - IRequiredCapability requirement = (IRequiredCapability) iterator.next(); - if (oldProfile.query(new CapabilityQuery(requirement), new HasMatchCollector(), null).isEmpty()) + private Collection areMetaRequirementsSatisfied(IProfile oldProfile, Collection newProfile, IProvisioningPlan initialPlan) { + Collection allMetaRequirements = extractMetaRequirements(newProfile, initialPlan); + for (IRequirement requirement : allMetaRequirements) { + if (oldProfile.query(new LimitQuery(new ExpressionQuery(IInstallableUnit.class, requirement.getMatches()), 1), null).isEmpty()) return allMetaRequirements; } return null; } //Return all the meta requirements for the list of IU specified and all the meta requirements listed necessary to satisfy the uninstallation - private Collection extractMetaRequirements(Collection ius, ProvisioningPlan plan) { - Set allMetaRequirements = new HashSet(); - for (Iterator iterator = ius.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); - IRequiredCapability[] reqs = iu.getMetaRequiredCapabilities(); - for (int i = 0; i < reqs.length; i++) { - allMetaRequirements.add(reqs[i]); - } + private Collection extractMetaRequirements(Collection ius, IProvisioningPlan plan) { + Set allMetaRequirements = new HashSet(); + for (IInstallableUnit iu : ius) { + allMetaRequirements.addAll(iu.getMetaRequiredCapabilities()); } - Collector c2 = plan.getRemovals().query(InstallableUnitQuery.ANY, new Collector(), null); - for (Iterator iterator = c2.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); - IRequiredCapability[] reqs = iu.getMetaRequiredCapabilities(); - for (int i = 0; i < reqs.length; i++) { - allMetaRequirements.add(reqs[i]); - } + IQueryResult queryResult = plan.getRemovals().query(InstallableUnitQuery.ANY, null); + for (Iterator iterator = queryResult.iterator(); iterator.hasNext();) { + IInstallableUnit iu = iterator.next(); + allMetaRequirements.addAll(iu.getMetaRequiredCapabilities()); } return allMetaRequirements; } - private ProvisioningPlan createInstallerPlan(IProfile profile, ProfileChangeRequest initialRequest, Collection unattachedState, Collection expectedState, ProvisioningPlan initialPlan, ProvisioningContext initialContext, IProgressMonitor monitor) { + private ProvisioningPlan createInstallerPlan(IProfile profile, ProfileChangeRequest initialRequest, Collection unattachedState, Collection expectedState, ProvisioningPlan initialPlan, ProvisioningContext initialContext, IProgressMonitor monitor) { SubMonitor sub = SubMonitor.convert(monitor, ExpandWork); try { sub.setTaskName(Messages.Director_Task_installer_plan); if (profileRegistry == null) - return new ProvisioningPlan(new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, Messages.Planner_no_profile_registry), initialRequest, null); + return new ProvisioningPlan(new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, Messages.Planner_no_profile_registry), profile, null, initialContext); IProfile agentProfile = profileRegistry.getProfile(IProfileRegistry.SELF); if (agentProfile == null) @@ -418,7 +424,7 @@ public class SimplePlanner implements IPlanner { if (profile.getProfileId().equals(agentProfile.getProfileId())) { if (profile.getTimestamp() != agentProfile.getTimestamp()) - return new ProvisioningPlan(new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, NLS.bind(Messages.Planner_profile_out_of_sync, profile.getProfileId())), initialRequest, null); + return new ProvisioningPlan(new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, NLS.bind(Messages.Planner_profile_out_of_sync, profile.getProfileId())), profile, null, initialContext); return createInstallerPlanForCohostedCase(profile, initialRequest, initialPlan, unattachedState, expectedState, initialContext, sub); } @@ -431,14 +437,14 @@ public class SimplePlanner implements IPlanner { } } - private ProvisioningPlan createInstallerPlanForCohostedCaseFromExternalInstaller(IProfile profile, ProfileChangeRequest initialRequest, ProvisioningPlan initialPlan, Collection newState, ProvisioningContext initialContext, IProfile agentProfile, SubMonitor sub) { - ProvisioningPlan planForProfile = generatePlan(null, newState, initialRequest); + private ProvisioningPlan createInstallerPlanForCohostedCaseFromExternalInstaller(IProfile profile, ProfileChangeRequest initialRequest, IProvisioningPlan initialPlan, Collection newState, ProvisioningContext initialContext, IProfile agentProfile, SubMonitor sub) { + ProvisioningPlan planForProfile = generatePlan(null, newState, initialRequest, initialContext); return createInstallerPlanForExternalInstaller(profile, initialRequest, planForProfile, newState, initialContext, agentProfile, sub); } //Deal with the case where the agent profile is different than the one being provisioned - private ProvisioningPlan createInstallerPlanForExternalInstaller(IProfile targetedProfile, ProfileChangeRequest initialRequest, ProvisioningPlan initialPlan, Collection expectedState, ProvisioningContext initialContext, IProfile agentProfile, SubMonitor sub) { - Collection metaRequirements = areMetaRequirementsSatisfied(agentProfile, expectedState, initialPlan); + private ProvisioningPlan createInstallerPlanForExternalInstaller(IProfile targetedProfile, ProfileChangeRequest initialRequest, ProvisioningPlan initialPlan, Collection expectedState, ProvisioningContext initialContext, IProfile agentProfile, SubMonitor sub) { + Collection metaRequirements = areMetaRequirementsSatisfied(agentProfile, expectedState, initialPlan); if (metaRequirements == null) return initialPlan; @@ -446,24 +452,24 @@ public class SimplePlanner implements IPlanner { IInstallableUnit previousActionsIU = getPreviousIUForMetaRequirements(agentProfile, getActionGatheringIUId(targetedProfile), sub); ProfileChangeRequest agentRequest = new ProfileChangeRequest(agentProfile); - agentRequest.addInstallableUnits(new IInstallableUnit[] {actionsIU}); + agentRequest.addInstallableUnits(actionsIU); if (previousActionsIU != null) - agentRequest.removeInstallableUnits(new IInstallableUnit[] {previousActionsIU}); + agentRequest.removeInstallableUnit(previousActionsIU); Object externalInstallerPlan = getSolutionFor(agentRequest, initialContext, sub.newChild(10)); - if (externalInstallerPlan instanceof ProvisioningPlan && ((ProvisioningPlan) externalInstallerPlan).getStatus().getSeverity() == IStatus.ERROR) { + if (externalInstallerPlan instanceof IProvisioningPlan && ((IProvisioningPlan) externalInstallerPlan).getStatus().getSeverity() == IStatus.ERROR) { MultiStatus externalInstallerStatus = new MultiStatus(DirectorActivator.PI_DIRECTOR, 0, Messages.Planner_can_not_install_preq, null); - externalInstallerStatus.add(((ProvisioningPlan) externalInstallerPlan).getStatus()); - return new ProvisioningPlan(externalInstallerStatus, initialRequest, new ProvisioningPlan(externalInstallerStatus, agentRequest, null)); + externalInstallerStatus.add(((IProvisioningPlan) externalInstallerPlan).getStatus()); + return new ProvisioningPlan(externalInstallerStatus, initialRequest.getProfile(), new ProvisioningPlan(externalInstallerStatus, agentProfile, null, initialContext), initialContext); } - initialPlan.setInstallerPlan(generatePlan((Projector) externalInstallerPlan, null, agentRequest)); + initialPlan.setInstallerPlan(generatePlan((Projector) externalInstallerPlan, null, agentRequest, initialContext)); return initialPlan; } //Deal with the case where the actions needs to be installed in the same profile than the one we are performing the initial request //The expectedState represents the result of the initialRequest where the metaRequirements have been satisfied. - private ProvisioningPlan createInstallerPlanForCohostedCase(IProfile profile, ProfileChangeRequest initialRequest, ProvisioningPlan initialPlan, Collection unattachedState, Collection expectedState, ProvisioningContext initialContext, SubMonitor monitor) { - Collection metaRequirements = initialRequest.getRemovedInstallableUnits().length == 0 ? areMetaRequirementsSatisfied(profile, expectedState, initialPlan) : extractMetaRequirements(expectedState, initialPlan); + private ProvisioningPlan createInstallerPlanForCohostedCase(IProfile profile, ProfileChangeRequest initialRequest, ProvisioningPlan initialPlan, Collection unattachedState, Collection expectedState, ProvisioningContext initialContext, SubMonitor monitor) { + Collection metaRequirements = initialRequest.getRemovedInstallableUnits().length == 0 ? areMetaRequirementsSatisfied(profile, expectedState, initialPlan) : extractMetaRequirements(expectedState, initialPlan); if (metaRequirements == null || metaRequirements.isEmpty()) return initialPlan; @@ -473,102 +479,97 @@ public class SimplePlanner implements IPlanner { //Create an agent request from the initial request ProfileChangeRequest agentRequest = new ProfileChangeRequest(profile); - for (Iterator it = initialRequest.getPropertiesToAdd().entrySet().iterator(); it.hasNext();) { - Entry entry = (Entry) it.next(); - agentRequest.setProfileProperty((String) entry.getKey(), entry.getValue()); + for (Entry entry : initialRequest.getPropertiesToAdd().entrySet()) { + agentRequest.setProfileProperty(entry.getKey(), entry.getValue()); } String[] removedProperties = initialRequest.getPropertiesToRemove(); for (int i = 0; i < removedProperties.length; i++) { agentRequest.removeProfileProperty(removedProperties[i]); } - Map removedIUProperties = initialRequest.getInstallableUnitProfilePropertiesToRemove(); - for (Iterator iterator = removedIUProperties.entrySet().iterator(); iterator.hasNext();) { - Entry entry = (Entry) iterator.next(); - ArrayList value = (ArrayList) entry.getValue(); - for (Iterator iterator2 = value.iterator(); iterator2.hasNext();) { - agentRequest.removeInstallableUnitProfileProperty((IInstallableUnit) entry.getKey(), (String) iterator2.next()); + Map> removedIUProperties = initialRequest.getInstallableUnitProfilePropertiesToRemove(); + for (Entry> entry : removedIUProperties.entrySet()) { + for (String propKey : entry.getValue()) { + agentRequest.removeInstallableUnitProfileProperty(entry.getKey(), propKey); } } if (previousMetaRequirementIU != null) - agentRequest.removeInstallableUnits(new IInstallableUnit[] {previousMetaRequirementIU}); - agentRequest.addInstallableUnits(new IInstallableUnit[] {metaRequirementIU}); + agentRequest.removeInstallableUnit(previousMetaRequirementIU); + agentRequest.addInstallableUnits(metaRequirementIU); ProvisioningContext agentCtx = new ProvisioningContext(new URI[0]); - ArrayList extraIUs = new ArrayList(unattachedState); + ArrayList extraIUs = new ArrayList(unattachedState); agentCtx.setExtraIUs(extraIUs); Object agentSolution = getSolutionFor(agentRequest, agentCtx, monitor.newChild(3)); - if (agentSolution instanceof ProvisioningPlan && ((ProvisioningPlan) agentSolution).getStatus().getSeverity() == IStatus.ERROR) { + if (agentSolution instanceof IProvisioningPlan && ((IProvisioningPlan) agentSolution).getStatus().getSeverity() == IStatus.ERROR) { MultiStatus agentStatus = new MultiStatus(DirectorActivator.PI_DIRECTOR, 0, Messages.Planner_actions_and_software_incompatible, null); - agentStatus.add(((ProvisioningPlan) agentSolution).getStatus()); - return new ProvisioningPlan(agentStatus, initialRequest, new ProvisioningPlan(agentStatus, agentRequest, null)); + agentStatus.add(((IProvisioningPlan) agentSolution).getStatus()); + return new ProvisioningPlan(agentStatus, initialRequest.getProfile(), new ProvisioningPlan(agentStatus, agentRequest.getProfile(), null, initialContext), initialContext); } //Compute the installer plan. It is the difference between what is currently in the profile and the solution we just computed - Collection agentState = ((Projector) agentSolution).extractSolution(); + Collection agentState = ((Projector) agentSolution).extractSolution(); agentState.remove(metaRequirementIU); //Remove the fake IU - agentState = AttachmentHelper.attachFragments(agentState, ((Projector) agentSolution).getFragmentAssociation()); + agentState = AttachmentHelper.attachFragments(agentState.iterator(), ((Projector) agentSolution).getFragmentAssociation()); ProvisioningContext noRepoContext = createNoRepoContext(initialRequest); //...This computes the attachment of what is currently in the profile Object initialSolution = getSolutionFor(new ProfileChangeRequest(new EverythingOptionalProfile(initialRequest.getProfile())), noRepoContext, new NullProgressMonitor()); - if (initialSolution instanceof ProvisioningPlan) { + if (initialSolution instanceof IProvisioningPlan) { LogHelper.log(new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, "The resolution of the previous state contained in profile " + initialRequest.getProfile().getProfileId() + " version " + initialRequest.getProfile().getTimestamp() + " failed.")); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ return (ProvisioningPlan) initialSolution; } - Collection initialState = initialRequest.getProfile().query(InstallableUnitQuery.ANY, new Collector(), null).toCollection(); - initialState = AttachmentHelper.attachFragments(initialState, ((Projector) initialSolution).getFragmentAssociation()); + Iterator profileState = initialRequest.getProfile().query(InstallableUnitQuery.ANY, null).iterator(); + Collection initialState = AttachmentHelper.attachFragments(profileState, ((Projector) initialSolution).getFragmentAssociation()); - ProvisioningPlan agentPlan = generateProvisioningPlan(initialState, agentState, initialRequest, null); + IProvisioningPlan agentPlan = generateProvisioningPlan(initialState, agentState, initialRequest, null, initialContext); //Compute the installation plan. It is the difference between the state after the installer plan has run and the expectedState. - return generateProvisioningPlan(agentState, expectedState, initialRequest, agentPlan); + return generateProvisioningPlan(agentState, expectedState, initialRequest, agentPlan, initialContext); } //Compute the set of operands based on the solution obtained previously - private ProvisioningPlan generatePlan(Projector newSolution, Collection newState, ProfileChangeRequest request) { + private ProvisioningPlan generatePlan(Projector newSolution, Collection newState, ProfileChangeRequest request, ProvisioningContext context) { //Compute the attachment of the new state if not provided if (newState == null) { newState = newSolution.extractSolution(); - newState = AttachmentHelper.attachFragments(newState, newSolution.getFragmentAssociation()); + newState = AttachmentHelper.attachFragments(newState.iterator(), newSolution.getFragmentAssociation()); } ProvisioningContext noRepoContext = createNoRepoContext(request); //Compute the attachment of the previous state Object initialSolution = getSolutionFor(new ProfileChangeRequest(new EverythingOptionalProfile(request.getProfile())), noRepoContext, new NullProgressMonitor()); - if (initialSolution instanceof ProvisioningPlan) { + if (initialSolution instanceof IProvisioningPlan) { LogHelper.log(new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, "The resolution of the previous state contained in profile " + request.getProfile().getProfileId() + " version " + request.getProfile().getTimestamp() + " failed.")); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ return (ProvisioningPlan) initialSolution; } - Collection initialState = request.getProfile().query(InstallableUnitQuery.ANY, new Collector(), null).toCollection(); - initialState = AttachmentHelper.attachFragments(initialState, ((Projector) initialSolution).getFragmentAssociation()); + Iterator profileState = request.getProfile().query(InstallableUnitQuery.ANY, null).iterator(); + Collection initialState = AttachmentHelper.attachFragments(profileState, ((Projector) initialSolution).getFragmentAssociation()); //Generate the plan - return generateProvisioningPlan(initialState, newState, request, null); + return generateProvisioningPlan(initialState, newState, request, null, context); } private ProvisioningContext createNoRepoContext(ProfileChangeRequest request) { ProvisioningContext noRepoContext = new ProvisioningContext(new URI[0]); noRepoContext.setArtifactRepositories(new URI[0]); noRepoContext.setProperty(INCLUDE_PROFILE_IUS, Boolean.FALSE.toString()); - ArrayList extraIUs = new ArrayList(); - extraIUs.addAll(request.getProfile().query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).toCollection()); - noRepoContext.setExtraIUs(extraIUs); + noRepoContext.setExtraIUs(new ArrayList(request.getProfile().query(InstallableUnitQuery.ANY, new NullProgressMonitor()).unmodifiableSet())); return noRepoContext; } private IInstallableUnit getPreviousIUForMetaRequirements(IProfile profile, String iuId, IProgressMonitor monitor) { - Collector c = profile.query(new InstallableUnitQuery(iuId), new Collector(), monitor); - if (c.size() == 0) + IQueryResult c = profile.query(new InstallableUnitQuery(iuId), monitor); + if (c.isEmpty()) return null; - return (IInstallableUnit) c.toArray(IInstallableUnit.class)[0]; + return c.iterator().next(); } private String getActionGatheringIUId(IProfile profile) { return ID_IU_FOR_ACTIONS + '.' + profile.getProfileId(); } - private IInstallableUnit createIUForMetaRequirements(IProfile profile, Collection metaRequirements) { + private IInstallableUnit createIUForMetaRequirements(IProfile profile, Collection metaRequirements) { InstallableUnitDescription description = new InstallableUnitDescription(); String id = getActionGatheringIUId(profile); description.setId(id); @@ -576,7 +577,7 @@ public class SimplePlanner implements IPlanner { description.setVersion(version); description.addRequiredCapabilities(metaRequirements); - ArrayList providedCapabilities = new ArrayList(); + ArrayList providedCapabilities = new ArrayList(); IProvidedCapability providedCapability = MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, id, version); providedCapabilities.add(providedCapability); description.addProvidedCapabilities(providedCapabilities); @@ -585,12 +586,12 @@ public class SimplePlanner implements IPlanner { return actionsIU; } - private IInstallableUnit createIURepresentingTheProfile(ArrayList allRequirements) { + private IInstallableUnit createIURepresentingTheProfile(ArrayList allRequirements) { InstallableUnitDescription iud = new MetadataFactory.InstallableUnitDescription(); String time = Long.toString(System.currentTimeMillis()); iud.setId(time); iud.setVersion(Version.createOSGi(0, 0, 0, time)); - iud.setRequiredCapabilities((IRequiredCapability[]) allRequirements.toArray(new IRequiredCapability[allRequirements.size()])); + iud.setRequiredCapabilities(allRequirements.toArray(new IRequirement[allRequirements.size()])); return MetadataFactory.createInstallableUnit(iud); } @@ -598,21 +599,19 @@ public class SimplePlanner implements IPlanner { //It returns at index 0 a meta IU representing everything that needs to be installed //It returns at index 1 all the IUs that are in the profile after the removal have been done, but before the addition have been done private Object[] updatePlannerInfo(ProfileChangeRequest profileChangeRequest, ProvisioningContext context) { - Collection includedIUs = profileChangeRequest.getProfile().query(new IUProfilePropertyQuery(INCLUSION_RULES, null), new Collector(), null).toCollection(); - Collection alreadyInstalled = new HashSet(includedIUs); + IQueryResult alreadyInstalled = profileChangeRequest.getProfile().query(new IUProfilePropertyQuery(INCLUSION_RULES, null), null); IInstallableUnit[] added = profileChangeRequest.getAddedInstallableUnits(); IInstallableUnit[] removed = profileChangeRequest.getRemovedInstallableUnits(); - for (Iterator iterator = profileChangeRequest.getInstallableUnitProfilePropertiesToRemove().entrySet().iterator(); iterator.hasNext();) { - Map.Entry object = (Map.Entry) iterator.next(); - if (((List) object.getValue()).contains(INCLUSION_RULES)) - profileChangeRequest.setInstallableUnitProfileProperty((IInstallableUnit) object.getKey(), INCLUSION_RULES, PlannerHelper.createStrictInclusionRule((IInstallableUnit) object.getKey())); + for (Entry> object : profileChangeRequest.getInstallableUnitProfilePropertiesToRemove().entrySet()) { + if (object.getValue().contains(INCLUSION_RULES)) + profileChangeRequest.setInstallableUnitProfileProperty(object.getKey(), INCLUSION_RULES, PlannerHelper.createStrictInclusionRule(object.getKey())); } //Remove the iu properties associated to the ius removed and the iu properties being removed as well if (removed.length != 0) { - for (Iterator iterator = alreadyInstalled.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); + for (Iterator iterator = alreadyInstalled.iterator(); iterator.hasNext();) { + IInstallableUnit iu = iterator.next(); for (int i = 0; i < removed.length; i++) { if (iu.equals(removed[i])) { profileChangeRequest.removeInstallableUnitProfileProperty(removed[i], INCLUSION_RULES); @@ -622,15 +621,15 @@ public class SimplePlanner implements IPlanner { } } } - ArrayList gatheredRequirements = new ArrayList(); + ArrayList gatheredRequirements = new ArrayList(); //Process all the IUs being added - Map iuPropertiesToAdd = profileChangeRequest.getInstallableUnitProfilePropertiesToAdd(); + Map> iuPropertiesToAdd = profileChangeRequest.getInstallableUnitProfilePropertiesToAdd(); for (int i = 0; i < added.length; i++) { - Map propertiesForIU = (Map) iuPropertiesToAdd.get(added[i]); - IRequiredCapability profileRequirement = null; + Map propertiesForIU = iuPropertiesToAdd.get(added[i]); + IRequirement profileRequirement = null; if (propertiesForIU != null) { - profileRequirement = createRequirement(added[i], (String) propertiesForIU.get(INCLUSION_RULES)); + profileRequirement = createRequirement(added[i], propertiesForIU.get(INCLUSION_RULES)); } if (profileRequirement == null) { profileChangeRequest.setInstallableUnitProfileProperty(added[i], INCLUSION_RULES, PlannerHelper.createStrictInclusionRule(added[i])); @@ -640,13 +639,13 @@ public class SimplePlanner implements IPlanner { } //Process the IUs that were already there - for (Iterator iterator = alreadyInstalled.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); - Map propertiesForIU = (Map) iuPropertiesToAdd.get(iu); - IRequiredCapability profileRequirement = null; + for (Iterator iterator = alreadyInstalled.iterator(); iterator.hasNext();) { + IInstallableUnit iu = iterator.next(); + Map propertiesForIU = iuPropertiesToAdd.get(iu); + IRequirement profileRequirement = null; //Test if the value has changed if (propertiesForIU != null) { - profileRequirement = createRequirement(iu, (String) propertiesForIU.get(INCLUSION_RULES)); + profileRequirement = createRequirement(iu, propertiesForIU.get(INCLUSION_RULES)); } if (profileRequirement == null) { profileRequirement = createRequirement(iu, profileChangeRequest.getProfile().getInstallableUnitProperty(iu, INCLUSION_RULES)); @@ -657,10 +656,10 @@ public class SimplePlanner implements IPlanner { //Now add any other requirement that we need to see satisfied if (context != null && context.getAdditionalRequirements() != null) gatheredRequirements.addAll(context.getAdditionalRequirements()); - return new Object[] {createIURepresentingTheProfile(gatheredRequirements), (IInstallableUnit[]) alreadyInstalled.toArray(new IInstallableUnit[alreadyInstalled.size()])}; + return new Object[] {createIURepresentingTheProfile(gatheredRequirements), alreadyInstalled.toArray(IInstallableUnit.class)}; } - private IRequiredCapability createRequirement(IInstallableUnit iu, String rule) { + private IRequirement createRequirement(IInstallableUnit iu, String rule) { if (rule == null) return null; if (rule.equals(PlannerHelper.createStrictInclusionRule(iu))) { @@ -672,16 +671,16 @@ public class SimplePlanner implements IPlanner { return null; } - private IRequiredCapability createOptionalRequirement(IInstallableUnit iu) { + private IRequirement createOptionalRequirement(IInstallableUnit iu) { return MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, iu.getId(), new VersionRange(iu.getVersion(), true, iu.getVersion(), true), null, true, false, true); } - private IRequiredCapability createStrictRequirement(IInstallableUnit iu) { + private IRequirement createStrictRequirement(IInstallableUnit iu) { return MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, iu.getId(), new VersionRange(iu.getVersion(), true, iu.getVersion(), true), null, false, false, true); } public IInstallableUnit[] updatesFor(IInstallableUnit toUpdate, ProvisioningContext context, IProgressMonitor monitor) { - Map resultsMap = new HashMap(); + Map resultsMap = new HashMap(); URI[] repositories = context.getMetadataRepositories(); if (repositories == null) @@ -693,11 +692,11 @@ public class SimplePlanner implements IPlanner { if (sub.isCanceled()) throw new OperationCanceledException(); IMetadataRepository repository = repoManager.loadRepository(repositories[i], sub.newChild(100)); - Collector matches = repository.query(new UpdateQuery(toUpdate), new Collector(), sub.newChild(100)); - for (Iterator it = matches.iterator(); it.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) it.next(); + IQueryResult matches = repository.query(new UpdateQuery(toUpdate), sub.newChild(100)); + for (Iterator it = matches.iterator(); it.hasNext();) { + IInstallableUnit iu = it.next(); String key = iu.getId() + "_" + iu.getVersion().toString(); //$NON-NLS-1$ - IInstallableUnit currentIU = (IInstallableUnit) resultsMap.get(key); + IInstallableUnit currentIU = resultsMap.get(key); if (currentIU == null || hasHigherFidelity(iu, currentIU)) resultsMap.put(key, iu); } @@ -706,8 +705,8 @@ public class SimplePlanner implements IPlanner { } } sub.done(); - Collection results = resultsMap.values(); - return (IInstallableUnit[]) results.toArray(new IInstallableUnit[results.size()]); + Collection results = resultsMap.values(); + return results.toArray(new IInstallableUnit[results.size()]); } //helper class to trick the resolver to believe that everything is optional @@ -718,11 +717,11 @@ public class SimplePlanner implements IPlanner { profile = p; } - public Collector available(Query query, Collector collector, IProgressMonitor monitor) { - return profile.available(query, collector, monitor); + public IQueryResult available(IQuery query, IProgressMonitor monitor) { + return profile.available(query, monitor); } - public Map getInstallableUnitProperties(IInstallableUnit iu) { + public Map getInstallableUnitProperties(IInstallableUnit iu) { return profile.getInstallableUnitProperties(iu); } @@ -732,23 +731,11 @@ public class SimplePlanner implements IPlanner { return profile.getInstallableUnitProperty(iu, key); } - public Map getLocalProperties() { - return profile.getLocalProperties(); - } - - public String getLocalProperty(String key) { - return profile.getLocalProperty(key); - } - - public IProfile getParentProfile() { - return profile.getParentProfile(); - } - public String getProfileId() { return profile.getProfileId(); } - public Map getProperties() { + public Map getProperties() { return profile.getProperties(); } @@ -756,24 +743,12 @@ public class SimplePlanner implements IPlanner { return profile.getProperty(key); } - public String[] getSubProfileIds() { - return profile.getSubProfileIds(); - } - public long getTimestamp() { return profile.getTimestamp(); } - public boolean hasSubProfiles() { - return profile.hasSubProfiles(); - } - - public boolean isRootProfile() { - return profile.isRootProfile(); - } - - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - return profile.query(query, collector, monitor); + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return profile.query(query, monitor); } } } diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Slicer.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Slicer.java index ab629af91..0f84ef178 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Slicer.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/Slicer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. + * Copyright (c) 2007, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -14,33 +14,35 @@ import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.core.helpers.Tracing; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.ExpressionQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.query.IQueryable; import org.eclipse.osgi.util.NLS; -import org.osgi.framework.InvalidSyntaxException; +import org.osgi.framework.Filter; public class Slicer { private static boolean DEBUG = false; - private IQueryable possibilites; + private IQueryable possibilites; - private LinkedList toProcess; - private Set considered; //IUs to add to the slice - private TwoTierMap slice; //The IUs that have been considered to be part of the problem + private LinkedList toProcess; + private Set considered; //IUs to add to the slice + private Map> slice; //The IUs that have been considered to be part of the problem - protected Dictionary selectionContext; + protected Dictionary selectionContext; private MultiStatus result; private boolean considerMetaRequirements = false; - public Slicer(IQueryable input, Dictionary context, boolean considerMetaRequirements) { + public Slicer(IQueryable input, Dictionary context, boolean considerMetaRequirements) { possibilites = input; - slice = new TwoTierMap(); + slice = new HashMap>(); selectionContext = context; result = new MultiStatus(DirectorActivator.PI_DIRECTOR, IStatus.OK, Messages.Planner_Problems_resolving_plan, null); this.considerMetaRequirements = considerMetaRequirements; } - public IQueryable slice(IInstallableUnit[] ius, IProgressMonitor monitor) { + public IQueryable slice(IInstallableUnit[] ius, IProgressMonitor monitor) { try { long start = 0; if (DEBUG) { @@ -49,14 +51,14 @@ public class Slicer { } validateInput(ius); - considered = new HashSet(Arrays.asList(ius)); - toProcess = new LinkedList(considered); + considered = new HashSet(Arrays.asList(ius)); + toProcess = new LinkedList(considered); while (!toProcess.isEmpty()) { if (monitor.isCanceled()) { result.merge(Status.CANCEL_STATUS); throw new OperationCanceledException(); } - processIU((IInstallableUnit) toProcess.removeFirst()); + processIU(toProcess.removeFirst()); } if (DEBUG) { long stop = System.currentTimeMillis(); @@ -69,7 +71,7 @@ public class Slicer { LogHelper.log(result); if (result.getSeverity() == IStatus.ERROR) return null; - return new QueryableArray((IInstallableUnit[]) considered.toArray(new IInstallableUnit[considered.size()])); + return new QueryableArray(considered.toArray(new IInstallableUnit[considered.size()])); } public MultiStatus getStatus() { @@ -85,93 +87,92 @@ public class Slicer { } // Check whether the requirement is applicable - protected boolean isApplicable(IRequiredCapability req) { - String filter = req.getFilter(); - if (filter == null) - return true; - try { - return DirectorActivator.context.createFilter(filter).match(selectionContext); - } catch (InvalidSyntaxException e) { - return false; - } + protected boolean isApplicable(IRequirement req) { + Filter filter = req.getFilter(); + return filter == null || filter.match(selectionContext); } protected boolean isApplicable(IInstallableUnit iu) { - String enablementFilter = iu.getFilter(); - if (enablementFilter == null) - return true; - try { - return DirectorActivator.context.createFilter(enablementFilter).match(selectionContext); - } catch (InvalidSyntaxException e) { - return false; - } + Filter filter = iu.getFilter(); + return filter == null || filter.match(selectionContext); } protected void processIU(IInstallableUnit iu) { iu = iu.unresolved(); - slice.put(iu.getId(), iu.getVersion(), iu); + Map iuSlice = slice.get(iu.getId()); + if (iuSlice == null) { + iuSlice = new HashMap(); + slice.put(iu.getId(), iuSlice); + } + iuSlice.put(iu.getVersion(), iu); if (!isApplicable(iu)) { return; } - IRequiredCapability[] reqs = getRequiredCapabilities(iu); - if (reqs.length == 0) { + Collection reqs = getRequiredCapabilities(iu); + if (reqs.isEmpty()) return; - } - for (int i = 0; i < reqs.length; i++) { - if (!isApplicable(reqs[i])) + for (IRequirement req : reqs) { + if (!isApplicable(req)) continue; - if (!isGreedy(reqs[i])) { + if (!isGreedy(req)) { continue; } - expandRequirement(iu, reqs[i]); + expandRequirement(iu, req); } } - protected boolean isGreedy(IRequiredCapability req) { + protected boolean isGreedy(IRequirement req) { return req.isGreedy(); } - private IRequiredCapability[] getRequiredCapabilities(IInstallableUnit iu) { + private Collection getRequiredCapabilities(IInstallableUnit iu) { + Collection iuRequirements = iu.getRequiredCapabilities(); + int initialRequirementCount = iuRequirements.size(); if (!(iu instanceof IInstallableUnitPatch)) { - if (iu.getMetaRequiredCapabilities().length == 0 || considerMetaRequirements == false) - return iu.getRequiredCapabilities(); - IRequiredCapability[] aggregatedCapabilities = new IRequiredCapability[iu.getRequiredCapabilities().length + iu.getMetaRequiredCapabilities().length]; - System.arraycopy(iu.getRequiredCapabilities(), 0, aggregatedCapabilities, 0, iu.getRequiredCapabilities().length); - System.arraycopy(iu.getMetaRequiredCapabilities(), 0, aggregatedCapabilities, iu.getRequiredCapabilities().length, iu.getMetaRequiredCapabilities().length); + if (!considerMetaRequirements) + return iuRequirements; + + Collection iuMetaRequirements = iu.getMetaRequiredCapabilities(); + int metaSize = iuMetaRequirements.size(); + if (metaSize == 0) + return iuRequirements; + + ArrayList aggregatedCapabilities = new ArrayList(initialRequirementCount + metaSize); + aggregatedCapabilities.addAll(iuRequirements); + aggregatedCapabilities.addAll(iuMetaRequirements); return aggregatedCapabilities; } - IRequiredCapability[] aggregatedCapabilities; + IInstallableUnitPatch patchIU = (IInstallableUnitPatch) iu; - IRequirementChange[] changes = patchIU.getRequirementsChange(); - int initialRequirementCount = iu.getRequiredCapabilities().length; - aggregatedCapabilities = new IRequiredCapability[initialRequirementCount + changes.length]; - System.arraycopy(iu.getRequiredCapabilities(), 0, aggregatedCapabilities, 0, initialRequirementCount); - for (int i = 0; i < changes.length; i++) { - aggregatedCapabilities[initialRequirementCount++] = changes[i].newValue(); - } + List changes = patchIU.getRequirementsChange(); + ArrayList aggregatedCapabilities = new ArrayList(initialRequirementCount + changes.size()); + aggregatedCapabilities.addAll(iuRequirements); + for (int i = 0; i < changes.size(); i++) + aggregatedCapabilities.add(changes.get(i).newValue()); return aggregatedCapabilities; } - private void expandRequirement(IInstallableUnit iu, IRequiredCapability req) { - if (req.isNegation()) + private void expandRequirement(IInstallableUnit iu, IRequirement req) { + if (req.getMax() == 0) return; - Collector matches = possibilites.query(new CapabilityQuery(req), new Collector(), null); + IQueryResult matches = possibilites.query(new ExpressionQuery(IInstallableUnit.class, req.getMatches()), null); int validMatches = 0; - for (Iterator iterator = matches.iterator(); iterator.hasNext();) { - IInstallableUnit match = (IInstallableUnit) iterator.next(); + for (Iterator iterator = matches.iterator(); iterator.hasNext();) { + IInstallableUnit match = iterator.next(); if (!isApplicable(match)) continue; validMatches++; - if (!slice.containsKey(match.getId(), match.getVersion())) + Map iuSlice = slice.get(match.getId()); + if (iuSlice == null || !iuSlice.containsKey(match.getVersion())) consider(match); } if (validMatches == 0) { - if (req.isOptional()) { + if (req.getMin() == 0) { if (DEBUG) System.out.println("No IU found to satisfy optional dependency of " + iu + " on req " + req); //$NON-NLS-1$//$NON-NLS-2$ } else { diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/TwoTierMap.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/TwoTierMap.java deleted file mode 100644 index 84ba95c06..000000000 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/TwoTierMap.java +++ /dev/null @@ -1,354 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.director; - -import java.io.PrintStream; -import java.io.Serializable; -import java.util.*; - -/** - * The purpose of this class is to provide a two-tier map. - * MapOf(key1 => MapOf(key2 => value)). - * Even though this class implements Map the behavior of - * the methods aren't exactly the same as that of a real - * Map - especially, entrySet(), keySet() etc. works off - * the outer map while values() returns all the values of - * all the inner maps. - */ -public class TwoTierMap implements Map, Serializable { - - private static final long serialVersionUID = 362497720873186265L; - - private Map outerMap; - private int policy; - - public static final int POLICY_NONE = 0, POLICY_BOTH_MAPS_PRESERVE_ORDERING = 1 << 0, POLICY_INNER_MAP_PRESERVE_EXISTING = 1 << 1, POLICY_INNER_MAP_SORTED_ASCENDING = 1 << 2, POLICY_INNER_MAP_SORTED_DESCENDING = 1 << 3, POLICY_INNER_MAP_ENSURE_SINGLETON = 1 << 4; - - private static final int POLICY_INNER_MAP_SORTED_MASK = POLICY_INNER_MAP_SORTED_ASCENDING | POLICY_INNER_MAP_SORTED_DESCENDING; - - public TwoTierMap() { - this(8, POLICY_NONE); - } - - public TwoTierMap(int initialCapacity) { - this(initialCapacity, POLICY_NONE); - } - - /** - * Creates a two-tier map with the specified - * initialCapacity and policy. The policy determines - * whether the outer map is ordered, inner map is - * sorted, clobber values of inner map etc. - */ - public TwoTierMap(int initialCapacity, int policy) { - this.policy = policy; - this.outerMap = shouldUseOrderedMap() ? new LinkedHashMap(initialCapacity) : new HashMap(initialCapacity); - } - - /** - * Insert the value with key key1 into the inner map - * that is obtained from the outer map with key key2. - * If you have set POLICY_INNER_MAP_PRESERVE_EXISTING - * at the time of creating this, it will not overwrite - * if there is already a non-null value at key2. - * The other POLICY_INNER_MAP_* policies determine - * what kind of inner map is created. - * @param key1 The key for outer map. - * @param key2 The key for inner map. - * @param value The value. - * @return Existing value if any, otherwise null. - */ - public Object put(Object key1, Object key2, Object value) { - Map innerMap = (Map) this.outerMap.get(key1); - if (innerMap == null) { - if (shouldUseSingletonInnerMap()) { - this.outerMap.put(key1, Collections.singletonMap(key2, value)); - return null; - } - innerMap = createInnerMap(); - this.outerMap.put(key1, innerMap); - } - // It is faster to check for already existing entry - // this way instead of containsKey() check. Of course, - // this will prevent us from recognizing a null entry, - // which I think shouldn't be a problem. - Object existing = innerMap.put(key2, value); - if (existing != null && shouldPreserveExisting()) { - innerMap.put(key2, existing); - } - return existing; - } - - /** - * Get the object stored in the inner map using key2 - * as key where the inner map is obtained from the - * outer map using key1. - * @param key1 The key for outer map. - * @param key2 The key for inner map. - * @return The object for key2 in inner map for key1 - * in the outer map. - */ - public Object get(Object key1, Object key2) { - if (key1 == null || key2 == null) - return getAll(key1); - Map innerMap = (Map) this.outerMap.get(key1); - Object value = innerMap == null ? null : innerMap.get(key2); - return value; - } - - /** - * Get all the values in the inner map for key1 in - * the outer map. - * @param key1 The key for outer map. - * @return Collection of values in the inner map. - */ - public Collection getAll(Object key1) { - if (key1 == null) - // return all - return values(); - Map innerMap = (Map) this.outerMap.get(key1); - return innerMap == null ? Collections.EMPTY_LIST : Collections.unmodifiableCollection(innerMap.values()); - - } - - public Object remove(Object key1, Object key2) { - if (key1 == null || key2 == null) - return removeAll(key1); - Map innerMap = (Map) this.outerMap.get(key1); - if (innerMap == null) - return null; - if (shouldUseSingletonInnerMap()) { - Object result = innerMap.get(key2); - if (result != null) { - this.outerMap.remove(key1); - } - return result; - } - Object result = innerMap.remove(key2); - if (result != null && innerMap.isEmpty()) { - this.outerMap.remove(key1); - } - return result; - } - - public Collection removeAll(Object key1) { - if (key1 == null) - return Collections.EMPTY_LIST; - Map innerMap = (Map) this.outerMap.remove(key1); - return innerMap == null ? Collections.EMPTY_LIST : innerMap.values(); - } - - /** - * Determine whether there exists a valid object for - * key2 in the inner map for key1 in the outer map. - * @param key1 The key for outer map. - * @param key2 The key for inner map. - * @return true if a non-null object exists; otherwise - * false. - */ - public boolean containsKey(Object key1, Object key2) { - if (key1 == null) - return false; - if (key2 == null) - return containsKey(key1); - return get(key1, key2) != null; - } - - /* (non-Javadoc) - * @see java.util.Map#clear() - */ - public void clear() { - this.outerMap.clear(); - } - - /* (non-Javadoc) - * @see java.util.Map#containsKey(java.lang.Object) - */ - public boolean containsKey(Object key) { - return this.outerMap.containsKey(key); - } - - /* (non-Javadoc) - * @see java.util.Map#containsValue(java.lang.Object) - */ - public boolean containsValue(Object value) { - for (Iterator it = entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - Map innerMap = (Map) entry.getValue(); - if (innerMap.containsValue(value)) - return true; - } - return false; - } - - /* (non-Javadoc) - * @see java.util.Map#size() - */ - public int size() { - return this.outerMap.size(); - } - - /* (non-Javadoc) - * @see java.util.Map#isEmpty() - */ - public boolean isEmpty() { - return this.size() == 0; - } - - /* (non-Javadoc) - * @see java.util.Map#entrySet() - */ - public Set entrySet() { - return Collections.unmodifiableSet(this.outerMap.entrySet()); - } - - /* (non-Javadoc) - * @see java.util.Map#values() - */ - public Collection values() { - ArrayList result = new ArrayList(size()); - for (Iterator it = this.outerMap.keySet().iterator(); it.hasNext();) { - Object key = it.next(); - // A null key will cause infinite recursion! - if (key != null) { - result.addAll(getAll(key)); - } - } - return result; - } - - /* (non-Javadoc) - * @see java.util.Map#get(java.lang.Object) - */ - public Object get(Object key) { - if (key instanceof Object[]) { - Object[] keys = (Object[]) key; - return get(keys[0], keys[1]); - } else - return getAll(key); - } - - /* (non-Javadoc) - * @see java.util.Map#keySet() - */ - public Set keySet() { - return Collections.unmodifiableSet(this.outerMap.keySet()); - } - - /* (non-Javadoc) - * @see java.util.Map#put(java.lang.Object, java.lang.Object) - */ - public Object put(Object key, Object value) { - if (key instanceof Object[]) { - Object[] keys = (Object[]) key; - return put(keys[0], keys[1], value); - } - throw new IllegalArgumentException("First arg should be an array!"); //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see java.util.Map#putAll(java.util.Map) - */ - public void putAll(Map t) { - throw new UnsupportedOperationException(); - } - - /* (non-Javadoc) - * @see java.util.Map#remove(java.lang.Object) - */ - public Object remove(Object key) { - if (key instanceof Object[]) { - Object[] keys = (Object[]) key; - return remove(keys[0], keys[1]); - } else - return removeAll(key); - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - if (this.outerMap.isEmpty()) { - sb.append(" (Empty)"); //$NON-NLS-1$ - } else { - for (Iterator it = this.outerMap.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - sb.append(" ").append(entry.getKey()) //$NON-NLS-1$ - .append(" = ") //$NON-NLS-1$ - .append(entry.getValue()).append('\n'); - } - sb.setLength(sb.length() - 1); - } - return sb.toString(); - } - - public void dump(PrintStream ps) { - if (ps == null) { - ps = System.out; - } - ps.println(this.toString()); - } - - private Map createInnerMap() { - Map innerMap; - if (shouldUseSortedInnerMap()) { - innerMap = new TreeMap(new ValueComparator(shouldSortInAscendingOrder())); - } else if (shouldUseOrderedMap()) { - innerMap = new LinkedHashMap(2); - } else { - innerMap = new HashMap(2); - } - return innerMap; - } - - private boolean shouldPreserveExisting() { - return (this.policy & POLICY_INNER_MAP_PRESERVE_EXISTING) == POLICY_INNER_MAP_PRESERVE_EXISTING; - } - - private boolean shouldUseOrderedMap() { - return (this.policy & POLICY_BOTH_MAPS_PRESERVE_ORDERING) == POLICY_BOTH_MAPS_PRESERVE_ORDERING; - } - - private boolean shouldUseSortedInnerMap() { - return (this.policy & POLICY_INNER_MAP_SORTED_MASK) != 0; - } - - private boolean shouldSortInAscendingOrder() { - return (this.policy & POLICY_INNER_MAP_SORTED_MASK) == POLICY_INNER_MAP_SORTED_ASCENDING; - } - - private boolean shouldUseSingletonInnerMap() { - return (this.policy & POLICY_INNER_MAP_ENSURE_SINGLETON) == POLICY_INNER_MAP_ENSURE_SINGLETON; - } - - private static class ValueComparator implements Comparator, Serializable { - private static final long serialVersionUID = 362497720873186266L; - private boolean ascending; - - public ValueComparator(boolean ascending) { - this.ascending = ascending; - } - - /* (non-Javadoc) - * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) - */ - public int compare(Object o1, Object o2) { - try { - if (o1 instanceof Comparable) { - int cmp = ((Comparable) o1).compareTo(o2); - return this.ascending ? cmp : (0 - cmp); - } - } catch (Exception e) { - // Ignore - } - return 1; - } - } - -} diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/messages.properties b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/messages.properties index 5ca20c9e1..d6b5b7ed0 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/messages.properties +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/messages.properties @@ -41,4 +41,5 @@ Planner_Unexpected_problem=An unexpected error occurred while resolving. Planner_actions_and_software_incompatible=The actions required to successfully install the requested software are incompatible with the software to install. Planner_can_not_install_preq=The actions required to successfully install the requested software can not be installed. Planner_no_profile_registry=Profile Registry is not registered. -Planner_profile_out_of_sync=The copies of profile {0} are not in sync. \ No newline at end of file +Planner_profile_out_of_sync=The copies of profile {0} are not in sync. +RequestStatus_message=Plan status for {0} diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/rollback/FormerState.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/rollback/FormerState.java index 94a3bfbeb..c0d30f031 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/rollback/FormerState.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/rollback/FormerState.java @@ -10,15 +10,13 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.rollback; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; - import java.util.*; import java.util.Map.Entry; import org.eclipse.equinox.internal.p2.director.SimplePlanner; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; public class FormerState { @@ -33,43 +31,39 @@ public class FormerState { } private static void synchronizeAllIUProperties(ProfileChangeRequest request, IProfile current, IProfile target) { - Collection currentIUs = current.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection(); - Collection targetIUs = target.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection(); - List iusToAdd = new ArrayList(targetIUs); - iusToAdd.remove(currentIUs); + Set currentIUset = current.query(InstallableUnitQuery.ANY, null).unmodifiableSet(); + Iterator targetIUs = target.query(InstallableUnitQuery.ANY, null).iterator(); + List iusToAdd = new ArrayList(); + List iusToUpdate = new ArrayList(); + while (targetIUs.hasNext()) { + IInstallableUnit nxt = targetIUs.next(); + if (currentIUset.contains(nxt)) + iusToUpdate.add(nxt); + else + iusToAdd.add(nxt); + } //additions - for (Iterator iterator = iusToAdd.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); - for (Iterator it = target.getInstallableUnitProperties(iu).entrySet().iterator(); it.hasNext();) { - Entry entry = (Entry) it.next(); - String key = (String) entry.getKey(); - String value = (String) entry.getValue(); - request.setInstallableUnitProfileProperty(iu, key, value); + for (IInstallableUnit iu : iusToAdd) { + for (Entry entry : target.getInstallableUnitProperties(iu).entrySet()) { + request.setInstallableUnitProfileProperty(iu, entry.getKey(), entry.getValue()); } } // updates - List iusToUpdate = new ArrayList(targetIUs); - iusToUpdate.remove(iusToAdd); - for (Iterator iterator = iusToUpdate.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); - Map propertiesToSet = new HashMap(target.getInstallableUnitProperties(iu)); - for (Iterator it = current.getInstallableUnitProperties(iu).entrySet().iterator(); it.hasNext();) { - Entry entry = (Entry) it.next(); - String key = (String) entry.getKey(); - String newValue = (String) propertiesToSet.get(key); + for (IInstallableUnit iu : iusToUpdate) { + Map propertiesToSet = new HashMap(target.getInstallableUnitProperties(iu)); + for (Entry entry : current.getInstallableUnitProperties(iu).entrySet()) { + String key = entry.getKey(); + String newValue = propertiesToSet.get(key); if (newValue == null) { request.removeInstallableUnitProfileProperty(iu, key); } else if (newValue.equals(entry.getValue())) propertiesToSet.remove(key); } - for (Iterator it = propertiesToSet.entrySet().iterator(); it.hasNext();) { - Entry entry = (Entry) it.next(); - String key = (String) entry.getKey(); - String value = (String) entry.getValue(); - request.setInstallableUnitProfileProperty(iu, key, value); + for (Entry entry : propertiesToSet.entrySet()) { + request.setInstallableUnitProfileProperty(iu, entry.getKey(), entry.getValue()); } } } @@ -79,34 +73,30 @@ public class FormerState { IInstallableUnit[] targetPlannerMarkedIUs = SimplePlanner.findPlannerMarkedIUs(target); //additions - List markedIUsToAdd = new ArrayList(Arrays.asList(targetPlannerMarkedIUs)); + List markedIUsToAdd = new ArrayList(Arrays.asList(targetPlannerMarkedIUs)); markedIUsToAdd.removeAll(Arrays.asList(currentPlannerMarkedIUs)); - request.addInstallableUnits((IInstallableUnit[]) markedIUsToAdd.toArray(new IInstallableUnit[markedIUsToAdd.size()])); + request.addInstallableUnits(markedIUsToAdd); // removes - List markedIUsToRemove = new ArrayList(Arrays.asList(currentPlannerMarkedIUs)); + List markedIUsToRemove = new ArrayList(Arrays.asList(currentPlannerMarkedIUs)); markedIUsToRemove.removeAll(Arrays.asList(targetPlannerMarkedIUs)); - request.removeInstallableUnits((IInstallableUnit[]) markedIUsToRemove.toArray(new IInstallableUnit[markedIUsToRemove.size()])); + request.removeInstallableUnits(markedIUsToRemove); } private static void synchronizeProfileProperties(ProfileChangeRequest request, IProfile current, IProfile target) { - Map profilePropertiesToSet = new HashMap(target.getProperties()); - for (Iterator it = current.getProperties().entrySet().iterator(); it.hasNext();) { - Entry entry = (Entry) it.next(); - String key = (String) entry.getKey(); + Map profilePropertiesToSet = new HashMap(target.getProperties()); + for (Entry entry : current.getProperties().entrySet()) { + String key = entry.getKey(); - String newValue = (String) profilePropertiesToSet.get(key); + String newValue = profilePropertiesToSet.get(key); if (newValue == null) { request.removeProfileProperty(key); } else if (newValue.equals(entry.getValue())) profilePropertiesToSet.remove(key); } - for (Iterator it = profilePropertiesToSet.entrySet().iterator(); it.hasNext();) { - Entry entry = (Entry) it.next(); - String key = (String) entry.getKey(); - String value = (String) entry.getValue(); - request.setProfileProperty(key, value); + for (Entry entry : profilePropertiesToSet.entrySet()) { + request.setProfileProperty(entry.getKey(), entry.getValue()); } } } diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/IDirector.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/IDirector.java index caea4fa8c..585c89c72 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/IDirector.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/IDirector.java @@ -12,8 +12,8 @@ package org.eclipse.equinox.internal.provisional.p2.director; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.ProvisioningContext; /** * Directors are responsible for determining what should be done to a given diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/IPlanner.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/IPlanner.java index 801be18ea..62102574d 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/IPlanner.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/IPlanner.java @@ -11,9 +11,8 @@ package org.eclipse.equinox.internal.provisional.p2.director; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; /** * Planners are responsible for determining what should be done to a given @@ -28,10 +27,10 @@ public interface IPlanner { */ public static final String SERVICE_NAME = IPlanner.class.getName(); - public ProvisioningPlan getProvisioningPlan(ProfileChangeRequest profileChangeRequest, ProvisioningContext context, IProgressMonitor monitor); + public IProvisioningPlan getProvisioningPlan(ProfileChangeRequest profileChangeRequest, ProvisioningContext context, IProgressMonitor monitor); public IInstallableUnit[] updatesFor(IInstallableUnit toUpdate, ProvisioningContext context, IProgressMonitor monitor); - public ProvisioningPlan getDiffPlan(IProfile currentProfile, IProfile targetProfile, IProgressMonitor monitor); + public IProvisioningPlan getDiffPlan(IProfile currentProfile, IProfile targetProfile, IProgressMonitor monitor); } diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/PlanExecutionHelper.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/PlanExecutionHelper.java index 0f9ab3733..0ebf674d8 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/PlanExecutionHelper.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/PlanExecutionHelper.java @@ -15,20 +15,21 @@ import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.director.DirectorActivator; import org.eclipse.equinox.internal.p2.director.Messages; +import org.eclipse.equinox.internal.p2.engine.PhaseSet; import org.eclipse.equinox.internal.provisional.configurator.Configurator; -import org.eclipse.equinox.internal.provisional.p2.engine.*; +import org.eclipse.equinox.p2.engine.*; public class PlanExecutionHelper { - public static IStatus executePlan(ProvisioningPlan result, IEngine engine, ProvisioningContext context, IProgressMonitor progress) { + public static IStatus executePlan(IProvisioningPlan result, IEngine engine, ProvisioningContext context, IProgressMonitor progress) { return executePlan(result, engine, new DefaultPhaseSet(), context, progress); } - public static IStatus executePlan(ProvisioningPlan result, IEngine engine, PhaseSet phaseSet, ProvisioningContext context, IProgressMonitor progress) { + public static IStatus executePlan(IProvisioningPlan result, IEngine engine, PhaseSet phaseSet, ProvisioningContext context, IProgressMonitor progress) { if (!result.getStatus().isOK()) return result.getStatus(); if (result.getInstallerPlan() != null) { - IStatus installerPlanStatus = engine.perform(result.getInstallerPlan().getProfileChangeRequest().getProfile(), phaseSet, result.getInstallerPlan().getOperands(), context, progress); + IStatus installerPlanStatus = engine.perform(result.getInstallerPlan(), phaseSet, progress); if (!installerPlanStatus.isOK()) return installerPlanStatus; Configurator configChanger = (Configurator) ServiceHelper.getService(DirectorActivator.context, Configurator.class.getName()); @@ -38,6 +39,6 @@ public class PlanExecutionHelper { return new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, Messages.Director_error_applying_configuration, e); } } - return engine.perform(result.getProfileChangeRequest().getProfile(), phaseSet, result.getOperands(), context, progress); + return engine.perform(result, phaseSet, progress); } } diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/PlannerHelper.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/PlannerHelper.java index 6cac100c1..96fb859b7 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/PlannerHelper.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/PlannerHelper.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.equinox.internal.provisional.p2.director; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; public class PlannerHelper { public static String createOptionalInclusionRule(IInstallableUnit iu) { diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/ProfileChangeRequest.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/ProfileChangeRequest.java index 99f267279..69572a6d6 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/ProfileChangeRequest.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/ProfileChangeRequest.java @@ -11,24 +11,27 @@ package org.eclipse.equinox.internal.provisional.p2.director; import java.util.*; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQueryResult; public class ProfileChangeRequest implements Cloneable { private final IProfile profile; - private ArrayList iusToRemove = null; // list of ius to remove - private ArrayList iusToAdd = null; // list of ius to add - private ArrayList propertiesToRemove = null; // list of keys for properties to be removed - private HashMap propertiesToAdd = null; // map of key->value for properties to be added - private HashMap iuPropertiesToAdd = null; // map iu->map of key->value pairs for properties to be added for an iu - private HashMap iuPropertiesToRemove = null; // map of iu->list of property keys to be removed for an iu + private ArrayList iusToRemove = null; // list of ius to remove + private ArrayList iusToAdd = null; // list of ius to add + private ArrayList propertiesToRemove = null; // list of keys for properties to be removed + private HashMap propertiesToAdd = null; // map of key->value for properties to be added + private HashMap> iuPropertiesToAdd = null; // map iu->map of key->value pairs for properties to be added for an iu + private HashMap> iuPropertiesToRemove = null; // map of iu->list of property keys to be removed for an iu + private boolean isAbsolute = false; //Indicate whether or not the request is an absolute one public static ProfileChangeRequest createByProfileId(String profileId) { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(DirectorActivator.context, IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(DirectorActivator.context, IProfileRegistry.SERVICE_NAME); if (profileRegistry == null) throw new IllegalStateException(Messages.Planner_no_profile_registry); IProfile profile = profileRegistry.getProfile(profileId); @@ -47,11 +50,11 @@ public class ProfileChangeRequest implements Cloneable { return profile; } - public Map getProfileProperties() { - Map result = new HashMap(profile.getProperties()); + public Map getProfileProperties() { + Map result = new HashMap(profile.getProperties()); if (propertiesToRemove != null) { - for (Iterator it = propertiesToRemove.iterator(); it.hasNext();) { - result.remove(it.next()); + for (String key : propertiesToRemove) { + result.remove(key); } } if (propertiesToAdd != null) @@ -60,38 +63,66 @@ public class ProfileChangeRequest implements Cloneable { return result; } - public void addInstallableUnits(IInstallableUnit[] toInstall) { + private void addInstallableUnit(IInstallableUnit toInstall) { if (iusToAdd == null) - iusToAdd = new ArrayList(toInstall.length); + iusToAdd = new ArrayList(); + iusToAdd.add(toInstall); + } + + public void addInstallableUnits(Collection toInstall) { + for (IInstallableUnit iu : toInstall) + addInstallableUnit(iu); + } + + public void addInstallableUnits(IQueryResult toInstall) { + for (Iterator itor = toInstall.iterator(); itor.hasNext();) + addInstallableUnit(itor.next()); + } + + public void addInstallableUnits(IInstallableUnit... toInstall) { for (int i = 0; i < toInstall.length; i++) - iusToAdd.add(toInstall[i]); + addInstallableUnit(toInstall[i]); } - public void removeInstallableUnits(IInstallableUnit[] toUninstall) { + public void removeInstallableUnit(IInstallableUnit toUninstall) { if (iusToRemove == null) - iusToRemove = new ArrayList(toUninstall.length); + iusToRemove = new ArrayList(); + iusToRemove.add(toUninstall); + } + + public void removeInstallableUnits(IInstallableUnit[] toUninstall) { for (int i = 0; i < toUninstall.length; i++) - iusToRemove.add(toUninstall[i]); + removeInstallableUnit(toUninstall[i]); + } + + public void removeInstallableUnits(Collection toUninstall) { + for (IInstallableUnit iu : toUninstall) + removeInstallableUnit(iu); } - public void setProfileProperty(String key, Object value) { + public void removeInstallableUnits(IQueryResult toUninstall) { + for (Iterator itor = toUninstall.iterator(); itor.hasNext();) + removeInstallableUnit(itor.next()); + } + + public void setProfileProperty(String key, String value) { if (propertiesToAdd == null) - propertiesToAdd = new HashMap(); + propertiesToAdd = new HashMap(); propertiesToAdd.put(key, value); } public void removeProfileProperty(String key) { if (propertiesToRemove == null) - propertiesToRemove = new ArrayList(1); + propertiesToRemove = new ArrayList(1); propertiesToRemove.add(key); } - public void setInstallableUnitProfileProperty(IInstallableUnit iu, String key, Object value) { + public void setInstallableUnitProfileProperty(IInstallableUnit iu, String key, String value) { if (iuPropertiesToAdd == null) - iuPropertiesToAdd = new HashMap(); - Map properties = (Map) iuPropertiesToAdd.get(iu); + iuPropertiesToAdd = new HashMap>(); + Map properties = iuPropertiesToAdd.get(iu); if (properties == null) { - properties = new HashMap(); + properties = new HashMap(); iuPropertiesToAdd.put(iu, properties); } properties.put(key, value); @@ -99,10 +130,10 @@ public class ProfileChangeRequest implements Cloneable { public void removeInstallableUnitProfileProperty(IInstallableUnit iu, String key) { if (iuPropertiesToRemove == null) - iuPropertiesToRemove = new HashMap(); - List keys = (List) iuPropertiesToRemove.get(iu); + iuPropertiesToRemove = new HashMap>(); + List keys = iuPropertiesToRemove.get(iu); if (keys == null) { - keys = new ArrayList(); + keys = new ArrayList(); iuPropertiesToRemove.put(iu, keys); } keys.add(key); @@ -111,74 +142,91 @@ public class ProfileChangeRequest implements Cloneable { public IInstallableUnit[] getRemovedInstallableUnits() { if (iusToRemove == null) return new IInstallableUnit[0]; - return (IInstallableUnit[]) iusToRemove.toArray(new IInstallableUnit[iusToRemove.size()]); + return iusToRemove.toArray(new IInstallableUnit[iusToRemove.size()]); } public IInstallableUnit[] getAddedInstallableUnits() { if (iusToAdd == null) return new IInstallableUnit[0]; - return (IInstallableUnit[]) iusToAdd.toArray(new IInstallableUnit[iusToAdd.size()]); + return iusToAdd.toArray(new IInstallableUnit[iusToAdd.size()]); } // String [key, key, key] names of properties to remove public String[] getPropertiesToRemove() { if (propertiesToRemove == null) return new String[0]; - return (String[]) propertiesToRemove.toArray(new String[propertiesToRemove.size()]); + return propertiesToRemove.toArray(new String[propertiesToRemove.size()]); } // map of key value pairs - public Map getPropertiesToAdd() { + public Map getPropertiesToAdd() { if (propertiesToAdd == null) - return Collections.EMPTY_MAP; + return CollectionUtils.emptyMap(); return propertiesToAdd; } // map of iu->list of property keys to be removed for an iu - public Map getInstallableUnitProfilePropertiesToRemove() { + public Map> getInstallableUnitProfilePropertiesToRemove() { if (iuPropertiesToRemove == null) - return Collections.EMPTY_MAP; + return CollectionUtils.emptyMap(); return iuPropertiesToRemove; } // TODO This can be represented and returned in whatever way makes most sense for planner/engine // map iu->map of key->value pairs for properties to be added for an iu - public Map getInstallableUnitProfilePropertiesToAdd() { + public Map> getInstallableUnitProfilePropertiesToAdd() { if (iuPropertiesToAdd == null) - return Collections.EMPTY_MAP; + return CollectionUtils.emptyMap(); return iuPropertiesToAdd; } public void setInstallableUnitInclusionRules(IInstallableUnit iu, String value) { - if (iuPropertiesToAdd == null) - iuPropertiesToAdd = new HashMap(); - Map properties = (Map) iuPropertiesToAdd.get(iu); - if (properties == null) { - properties = new HashMap(); - iuPropertiesToAdd.put(iu, properties); - } - properties.put(SimplePlanner.INCLUSION_RULES, value); + setInstallableUnitProfileProperty(iu, SimplePlanner.INCLUSION_RULES, value); } public void removeInstallableUnitInclusionRules(IInstallableUnit iu) { - if (iuPropertiesToRemove == null) - iuPropertiesToRemove = new HashMap(); - List keys = (List) iuPropertiesToRemove.get(iu); - if (keys == null) { - keys = new ArrayList(); - iuPropertiesToRemove.put(iu, keys); - } - keys.add(SimplePlanner.INCLUSION_RULES); + removeInstallableUnitProfileProperty(iu, SimplePlanner.INCLUSION_RULES); } + public void setAbsoluteMode(boolean absolute) { + isAbsolute = absolute; + } + + public boolean getAbsolute() { + return isAbsolute; + } + + @SuppressWarnings("unchecked") public Object clone() { ProfileChangeRequest result = new ProfileChangeRequest(profile); - result.iusToRemove = iusToRemove == null ? null : (ArrayList) iusToRemove.clone(); - result.iusToAdd = iusToAdd == null ? null : (ArrayList) iusToAdd.clone(); - result.propertiesToRemove = propertiesToRemove == null ? null : (ArrayList) propertiesToRemove.clone(); - result.propertiesToAdd = propertiesToAdd == null ? null : (HashMap) propertiesToAdd.clone(); - result.iuPropertiesToAdd = iuPropertiesToAdd == null ? null : (HashMap) iuPropertiesToAdd.clone(); - result.iuPropertiesToRemove = iuPropertiesToRemove == null ? null : (HashMap) iuPropertiesToRemove.clone(); + result.iusToRemove = iusToRemove == null ? null : (ArrayList) iusToRemove.clone(); + result.iusToAdd = iusToAdd == null ? null : (ArrayList) iusToAdd.clone(); + result.propertiesToRemove = propertiesToRemove == null ? null : (ArrayList) propertiesToRemove.clone(); + result.propertiesToAdd = propertiesToAdd == null ? null : (HashMap) propertiesToAdd.clone(); + result.iuPropertiesToAdd = iuPropertiesToAdd == null ? null : (HashMap>) iuPropertiesToAdd.clone(); + result.iuPropertiesToRemove = iuPropertiesToRemove == null ? null : (HashMap>) iuPropertiesToRemove.clone(); return result; } + + public String toString() { + StringBuffer result = new StringBuffer(1000); + result.append("==Profile change request for "); //$NON-NLS-1$ + result.append(profile.getProfileId()); + result.append('\n'); + result.append("==Additions=="); //$NON-NLS-1$ + result.append('\n'); + for (IInstallableUnit iu : iusToAdd) { + result.append('\t'); + result.append(iu); + result.append('\n'); + } + result.append("==Removals=="); //$NON-NLS-1$ + result.append('\n'); + for (IInstallableUnit iu : iusToRemove) { + result.append('\t'); + result.append(iu); + result.append('\n'); + } + return result.toString(); + } } diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/ProvisioningPlan.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/ProvisioningPlan.java deleted file mode 100644 index e231b38b2..000000000 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/ProvisioningPlan.java +++ /dev/null @@ -1,130 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.director; - -import java.util.*; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.p2.director.QueryableArray; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.engine.Operand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; - -public class ProvisioningPlan { - IStatus status; - Operand[] operands; - Map actualChangeRequest; - Map sideEffectChanges; - ProvisioningPlan installerPlan; - RequestStatus globalRequestStatus; - ProfileChangeRequest originalChangeRequest; - IQueryable completeState; - - public ProvisioningPlan(IStatus status, ProfileChangeRequest originalRequest, ProvisioningPlan installerPlan) { - this(status, new Operand[0], null, null, installerPlan, originalRequest, null); - } - - public ProvisioningPlan(IStatus status, Operand[] operands, Map[] actualChangeRequest, RequestStatus globalStatus, ProvisioningPlan installerPlan, ProfileChangeRequest originalRequest, IQueryable futureState) { - this.status = status; - this.operands = operands; - if (actualChangeRequest != null) { - this.actualChangeRequest = actualChangeRequest[0]; - this.sideEffectChanges = actualChangeRequest[1]; - } - this.globalRequestStatus = globalStatus; - this.installerPlan = installerPlan; - originalChangeRequest = originalRequest; - if (futureState == null) - futureState = new QueryableArray(new IInstallableUnit[0]); - completeState = futureState; - } - - public IStatus getStatus() { - return status; - } - - public ProfileChangeRequest getProfileChangeRequest() { - return originalChangeRequest; - } - - /** - * The operands to pass to the engine. - * @return the operands to be executed. This may be an empty array if the - * plan has errors or if there is nothing to do. - */ - public Operand[] getOperands() { - return operands; - } - - public IQueryable getRemovals() { - return new QueryablePlan(false); - } - - public IQueryable getAdditions() { - return new QueryablePlan(true); - } - - public RequestStatus getRequestStatus(IInstallableUnit iu) { - if (actualChangeRequest == null) - return null; - return (RequestStatus) actualChangeRequest.get(iu); - } - - public RequestStatus getRequestStatus() { - return globalRequestStatus; - } - - public Map getSideEffectChanges() { - if (sideEffectChanges == null) - return Collections.EMPTY_MAP; - return sideEffectChanges; - } - - private class QueryablePlan implements IQueryable { - private boolean addition; - - public QueryablePlan(boolean add) { - this.addition = add; - } - - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - if (operands == null || status.getSeverity() == IStatus.ERROR) - return collector; - Collection list = new ArrayList(); - for (int i = 0; i < operands.length; i++) { - if (!(operands[i] instanceof InstallableUnitOperand)) - continue; - InstallableUnitOperand op = ((InstallableUnitOperand) operands[i]); - IInstallableUnit iu = addition ? op.second() : op.first(); - if (iu != null) - list.add(iu); - } - return query.perform(list.iterator(), collector); - } - } - - public ProvisioningPlan getInstallerPlan() { - return installerPlan; - } - - public void setInstallerPlan(ProvisioningPlan p) { - installerPlan = p; - } - - public IQueryable getCompleteState() { - return completeState; - } - - protected void setCompleteState(IQueryable state) { - completeState = state; - } -} diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/RequestStatus.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/RequestStatus.java index 42e502653..b1f6796b7 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/RequestStatus.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/provisional/p2/director/RequestStatus.java @@ -10,33 +10,34 @@ package org.eclipse.equinox.internal.provisional.p2.director; import java.util.*; -import org.eclipse.equinox.internal.p2.director.Explanation; +import org.eclipse.core.runtime.Status; +import org.eclipse.equinox.internal.p2.director.*; import org.eclipse.equinox.internal.p2.director.Explanation.IUInstalled; import org.eclipse.equinox.internal.p2.director.Explanation.IUToInstall; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.osgi.util.NLS; -public class RequestStatus { +public class RequestStatus extends Status { public static final byte ADDED = 0; public static final byte REMOVED = 1; private byte initialRequestType; private IInstallableUnit iu; - private int severity; - private Set explanation; + private Set explanation; private Explanation detailedExplanation; - private Set conflictingRootIUs; - private Set conflictingInstalledIUs; + private Set conflictingRootIUs; + private Set conflictingInstalledIUs; - public RequestStatus(IInstallableUnit iu, byte initialRequesType, int severity, Set explanation) { + public RequestStatus(IInstallableUnit iu, byte initialRequesType, int severity, Set explanation) { + super(severity, DirectorActivator.PI_DIRECTOR, NLS.bind(Messages.RequestStatus_message, iu)); this.iu = iu; - this.severity = severity; this.initialRequestType = initialRequesType; this.explanation = explanation; - conflictingRootIUs = new HashSet(); - conflictingInstalledIUs = new HashSet(); + conflictingRootIUs = new HashSet(); + conflictingInstalledIUs = new HashSet(); if (explanation != null) { - Iterator iterator = explanation.iterator(); - Object o = null; + Iterator iterator = explanation.iterator(); + Explanation o = null; while (iterator.hasNext() && ((o = iterator.next()) instanceof Explanation.IUToInstall)) { conflictingRootIUs.add(((IUToInstall) o).iu); } @@ -46,7 +47,7 @@ public class RequestStatus { conflictingInstalledIUs.add(((IUInstalled) o).iu); } } - detailedExplanation = (Explanation) o; + detailedExplanation = o; } } @@ -58,24 +59,20 @@ public class RequestStatus { return iu; } - public int getSeverity() { - return severity; - } - //Return the already installed roots with which this IU is in conflict //Return an empty set if there is no conflict - public Set getConflictsWithInstalledRoots() { + public Set getConflictsWithInstalledRoots() { return conflictingRootIUs; } //Return the already installed roots with which this IU is in conflict //Return an empty set if there is no conflict - public Set getConflictsWithAnyRoots() { + public Set getConflictsWithAnyRoots() { return conflictingInstalledIUs; } //Return an explanation as to why this IU can not be resolved. - public Set getExplanations() { + public Set getExplanations() { //To start with, this does not have to return the most specific explanation. If it simply returns an global explanation it is good enough. return explanation; } diff --git a/bundles/org.eclipse.equinox.p2.directorywatcher/.classpath b/bundles/org.eclipse.equinox.p2.directorywatcher/.classpath index 6f3b481ac..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.directorywatcher/.classpath +++ b/bundles/org.eclipse.equinox.p2.directorywatcher/.classpath @@ -1,6 +1,6 @@ - + diff --git a/bundles/org.eclipse.equinox.p2.directorywatcher/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.directorywatcher/.settings/org.eclipse.jdt.core.prefs index b94ca9b4f..925b1bff0 100644 --- a/bundles/org.eclipse.equinox.p2.directorywatcher/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.directorywatcher/.settings/org.eclipse.jdt.core.prefs @@ -1,329 +1,329 @@ -#Thu Oct 09 08:15:15 EDT 2008 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert -org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning -org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false -org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false -org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +#Wed Dec 23 00:33:28 CET 2009 +eclipse.preferences.version=1 +org.eclipse.jdt.core.builder.cleanOutputFolder=clean +org.eclipse.jdt.core.builder.duplicateResourceTask=warning +org.eclipse.jdt.core.builder.invalidClasspath=abort +org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch +org.eclipse.jdt.core.circularClasspath=error +org.eclipse.jdt.core.classpath.exclusionPatterns=enabled +org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.doc.comment.support=enabled +org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=public -org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=warning -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fieldHiding=warning -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning -org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert -org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=error +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=warning +org.eclipse.jdt.core.compiler.problem.invalidJavadoc=error +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private +org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=enabled +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public +org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=public +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.formatter.comment.format_source_code=true -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=warning -org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=warning -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -org.eclipse.jdt.core.classpath.exclusionPatterns=enabled +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=warning +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=enabled +org.eclipse.jdt.core.compiler.problem.unusedImport=error +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.5 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 -org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert -org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.formatter.comment.format_header=false -org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.comment.line_length=80 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert -org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert -org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.builder.cleanOutputFolder=clean -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=enabled -org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert -org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=false -org.eclipse.jdt.core.formatter.continuation_indentation=2 -org.eclipse.jdt.core.compiler.problem.invalidJavadoc=error -org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 -org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line -org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.incompleteClasspath=error -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=enabled -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false org.eclipse.jdt.core.formatter.comment.format_block_comments=false -org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert -org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=insert +org.eclipse.jdt.core.formatter.comment.format_header=false org.eclipse.jdt.core.formatter.comment.format_html=true -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning -org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=error -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=false +org.eclipse.jdt.core.formatter.comment.format_line_comments=false +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=false +org.eclipse.jdt.core.formatter.comment.indent_root_tags=false +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert -org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.comment.line_length=80 +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert -org.eclipse.jdt.core.circularClasspath=error -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning -org.eclipse.jdt.core.formatter.tabulation.char=tab -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert -org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert -org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false -org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false -org.eclipse.jdt.core.formatter.compact_else_if=true -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert -org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert -org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore -org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true -org.eclipse.jdt.core.compiler.problem.discouragedReference=error -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 -org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert -org.eclipse.jdt.core.formatter.comment.format_line_comments=false -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert -org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert -org.eclipse.jdt.core.formatter.comment.indent_parameter_description=false -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=enabled -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert -org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.comment.indent_root_tags=false -org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert -org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false -org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true -org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.blank_lines_before_package=0 org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert -org.eclipse.jdt.core.formatter.indent_empty_lines=false -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert -org.eclipse.jdt.core.compiler.problem.unusedImport=error -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert -org.eclipse.jdt.core.builder.invalidClasspath=abort -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.incompatibleJDKLevel=ignore -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false org.eclipse.jdt.core.formatter.lineSplit=800 -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled -org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 -org.eclipse.jdt.core.compiler.source=1.3 -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false +org.eclipse.jdt.core.formatter.tabulation.char=tab org.eclipse.jdt.core.formatter.tabulation.size=4 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert -org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert -org.eclipse.jdt.core.builder.duplicateResourceTask=warning -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=insert -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.compiler.doc.comment.support=enabled -org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.compiler.compliance=1.4 -org.eclipse.jdt.core.formatter.blank_lines_after_package=1 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert -org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.incompatibleJDKLevel=ignore +org.eclipse.jdt.core.incompleteClasspath=error diff --git a/bundles/org.eclipse.equinox.p2.directorywatcher/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.directorywatcher/META-INF/MANIFEST.MF index c0b1ba690..b38923555 100644 --- a/bundles/org.eclipse.equinox.p2.directorywatcher/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.directorywatcher/META-INF/MANIFEST.MF @@ -5,23 +5,30 @@ Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-Localization: plugin Bundle-Version: 1.0.100.qualifier -Import-Package: org.eclipse.equinox.internal.p2.core.helpers, +Import-Package: org.eclipse.equinox.internal.p2.artifact.repository, + org.eclipse.equinox.internal.p2.artifact.repository.simple, + org.eclipse.equinox.internal.p2.core.helpers, org.eclipse.equinox.internal.p2.update, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.p2.repository, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, org.eclipse.equinox.p2.publisher, org.eclipse.equinox.p2.publisher.actions, org.eclipse.equinox.p2.publisher.eclipse, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.artifact.spi, + org.eclipse.equinox.p2.repository.metadata, org.eclipse.osgi.service.resolver;version="1.1.0", org.eclipse.osgi.util, org.osgi.framework;version="1.4.0", org.osgi.service.packageadmin;version="1.2.0" -Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, - J2SE-1.4 +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 Export-Package: org.eclipse.equinox.internal.provisional.p2.directorywatcher;x-friends:="org.eclipse.equinox.p2.reconciler.dropins,org.eclipse.equinox.p2.extensionlocation" Require-Bundle: org.eclipse.equinox.common;bundle-version="[3.3.0,4.0)" Bundle-Activator: org.eclipse.equinox.internal.provisional.p2.directorywatcher.Activator diff --git a/bundles/org.eclipse.equinox.p2.directorywatcher/build.properties b/bundles/org.eclipse.equinox.p2.directorywatcher/build.properties index dc77b9c16..ca5030900 100644 --- a/bundles/org.eclipse.equinox.p2.directorywatcher/build.properties +++ b/bundles/org.eclipse.equinox.p2.directorywatcher/build.properties @@ -15,3 +15,5 @@ bin.includes = META-INF/,\ about.html,\ plugin.properties src.includes = about.html +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/Activator.java b/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/Activator.java index 54c196c30..05cd04b94 100644 --- a/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/Activator.java +++ b/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/Activator.java @@ -14,8 +14,9 @@ package org.eclipse.equinox.internal.provisional.p2.directorywatcher; import java.io.File; import java.net.URI; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.osgi.framework.*; import org.osgi.service.packageadmin.PackageAdmin; @@ -40,11 +41,11 @@ public class Activator implements BundleActivator { } public static IArtifactRepositoryManager getArtifactRepositoryManager() { - return (IArtifactRepositoryManager) ServiceHelper.getService(context, IArtifactRepositoryManager.class.getName()); + return (IArtifactRepositoryManager) ((IProvisioningAgent) ServiceHelper.getService(context, IProvisioningAgent.SERVICE_NAME)).getService(IArtifactRepositoryManager.SERVICE_NAME); } public static IMetadataRepositoryManager getMetadataRepositoryManager() { - return (IMetadataRepositoryManager) ServiceHelper.getService(context, IMetadataRepositoryManager.class.getName()); + return (IMetadataRepositoryManager) ((IProvisioningAgent) ServiceHelper.getService(context, IProvisioningAgent.SERVICE_NAME)).getService(IMetadataRepositoryManager.SERVICE_NAME); } public static URI getDefaultRepositoryLocation(Object object, String repositoryName) { diff --git a/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/CachingArtifactRepository.java b/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/CachingArtifactRepository.java index 8abed2915..419339d3e 100644 --- a/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/CachingArtifactRepository.java +++ b/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/CachingArtifactRepository.java @@ -14,17 +14,20 @@ import java.io.OutputStream; import java.net.URI; import java.util.*; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.internal.p2.artifact.repository.FlatteningIterator; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; public class CachingArtifactRepository implements IArtifactRepository, IFileArtifactRepository { private static final String NULL = ""; //$NON-NLS-1$ private IArtifactRepository innerRepo; - private Set descriptorsToAdd = new HashSet(); - private Map artifactMap = new HashMap(); - private Set descriptorsToRemove = new HashSet(); - private Map propertyChanges = new HashMap(); + private Set descriptorsToAdd = new HashSet(); + private Map> artifactMap = new HashMap>(); + private Set descriptorsToRemove = new HashSet(); + private Map propertyChanges = new HashMap(); protected CachingArtifactRepository(IArtifactRepository innerRepo) { this.innerRepo = innerRepo; @@ -37,23 +40,22 @@ public class CachingArtifactRepository implements IArtifactRepository, IFileArti } private void saveRemovals() { - for (Iterator i = descriptorsToRemove.iterator(); i.hasNext();) - innerRepo.removeDescriptor((IArtifactDescriptor) i.next()); + for (IArtifactDescriptor desc : descriptorsToRemove) + innerRepo.removeDescriptor(desc); descriptorsToRemove.clear(); } private void saveAdditions() { if (descriptorsToAdd.isEmpty()) return; - innerRepo.addDescriptors((IArtifactDescriptor[]) descriptorsToAdd.toArray(new IArtifactDescriptor[descriptorsToAdd.size()])); + innerRepo.addDescriptors(descriptorsToAdd.toArray(new IArtifactDescriptor[descriptorsToAdd.size()])); descriptorsToAdd.clear(); artifactMap.clear(); } private void savePropertyChanges() { - for (Iterator i = propertyChanges.keySet().iterator(); i.hasNext();) { - String key = (String) i.next(); - String value = (String) propertyChanges.get(key); + for (String key : propertyChanges.keySet()) { + String value = propertyChanges.get(key); innerRepo.setProperty(key, value == NULL ? null : value); } propertyChanges.clear(); @@ -61,9 +63,9 @@ public class CachingArtifactRepository implements IArtifactRepository, IFileArti private void mapDescriptor(IArtifactDescriptor descriptor) { IArtifactKey key = descriptor.getArtifactKey(); - Collection descriptors = (Collection) artifactMap.get(key); + List descriptors = artifactMap.get(key); if (descriptors == null) { - descriptors = new ArrayList(); + descriptors = new ArrayList(); artifactMap.put(key, descriptors); } descriptors.add(descriptor); @@ -71,7 +73,7 @@ public class CachingArtifactRepository implements IArtifactRepository, IFileArti private void unmapDescriptor(IArtifactDescriptor descriptor) { IArtifactKey key = descriptor.getArtifactKey(); - Collection descriptors = (Collection) artifactMap.get(key); + List descriptors = artifactMap.get(key); if (descriptors == null) { // we do not have the descriptor locally so remember it to be removed from // the inner repo on save. @@ -99,19 +101,12 @@ public class CachingArtifactRepository implements IArtifactRepository, IFileArti } public synchronized IArtifactDescriptor[] getArtifactDescriptors(IArtifactKey key) { - Collection result = (Collection) artifactMap.get(key); + List result = artifactMap.get(key); if (result == null) return innerRepo.getArtifactDescriptors(key); + result = new ArrayList(result); result.addAll(Arrays.asList(innerRepo.getArtifactDescriptors(key))); - return (IArtifactDescriptor[]) result.toArray(new IArtifactDescriptor[result.size()]); - } - - public synchronized IArtifactKey[] getArtifactKeys() { - // there may be more descriptors than keys to collect up the unique keys - HashSet result = new HashSet(); - result.addAll(artifactMap.keySet()); - result.addAll(Arrays.asList(innerRepo.getArtifactKeys())); - return (IArtifactKey[]) result.toArray(new IArtifactKey[result.size()]); + return result.toArray(new IArtifactDescriptor[result.size()]); } public synchronized boolean contains(IArtifactDescriptor descriptor) { @@ -139,7 +134,7 @@ public class CachingArtifactRepository implements IArtifactRepository, IFileArti } public synchronized void removeAll() { - IArtifactDescriptor[] toRemove = (IArtifactDescriptor[]) descriptorsToAdd.toArray(new IArtifactDescriptor[descriptorsToAdd.size()]); + IArtifactDescriptor[] toRemove = descriptorsToAdd.toArray(new IArtifactDescriptor[descriptorsToAdd.size()]); for (int i = 0; i < toRemove.length; i++) doRemoveArtifact(toRemove[i]); } @@ -180,7 +175,7 @@ public class CachingArtifactRepository implements IArtifactRepository, IFileArti return innerRepo.getName(); } - public Map getProperties() { + public Map getProperties() { // TODO need to combine the local and inner properties return innerRepo.getProperties(); } @@ -210,7 +205,7 @@ public class CachingArtifactRepository implements IArtifactRepository, IFileArti } public String setProperty(String key, String value) { - String result = (String) getProperties().get(key); + String result = getProperties().get(key); propertyChanges.put(key, value == null ? NULL : value); return result; } @@ -219,6 +214,7 @@ public class CachingArtifactRepository implements IArtifactRepository, IFileArti innerRepo.setProvider(provider); } + @SuppressWarnings("rawtypes") public Object getAdapter(Class adapter) { return innerRepo.getAdapter(adapter); } @@ -234,4 +230,31 @@ public class CachingArtifactRepository implements IArtifactRepository, IFileArti return ((IFileArtifactRepository) innerRepo).getArtifactFile(descriptor); return null; } + + public IArtifactDescriptor createArtifactDescriptor(IArtifactKey key) { + return innerRepo.createArtifactDescriptor(key); + } + + public IQueryable descriptorQueryable() { + final Collection> descs = artifactMap.values(); + IQueryable cached = new IQueryable() { + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return query.perform(new FlatteningIterator(descs.iterator())); + } + }; + + return new CompoundQueryable(cached, innerRepo.descriptorQueryable()); + } + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + final Iterator keyIterator = artifactMap.keySet().iterator(); + IQueryable cached = new IQueryable() { + public IQueryResult query(IQuery q, IProgressMonitor mon) { + return q.perform(keyIterator); + } + }; + + CompoundQueryable compound = new CompoundQueryable(cached, innerRepo); + return compound.query(query, monitor); + } } diff --git a/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/DirectoryWatcher.java b/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/DirectoryWatcher.java index dea2d358d..c47d07603 100644 --- a/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/DirectoryWatcher.java +++ b/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/DirectoryWatcher.java @@ -62,14 +62,14 @@ public class DirectoryWatcher { final File[] directories; long poll = 2000; - private Set listeners = new HashSet(); - private HashSet scannedFiles = new HashSet(); - private HashSet removals; - private Set pendingDeletions; + private Set listeners = new HashSet(); + private HashSet scannedFiles = new HashSet(); + private HashSet removals; + private Set pendingDeletions; private WatcherThread watcher; - public DirectoryWatcher(Dictionary properties, BundleContext context) { - String dir = (String) properties.get(DIR); + public DirectoryWatcher(Map properties, BundleContext context) { + String dir = properties.get(DIR); if (dir == null) dir = "./load"; //$NON-NLS-1$ @@ -131,10 +131,10 @@ public class DirectoryWatcher { private void startPoll() { removals = scannedFiles; - scannedFiles = new HashSet(); - pendingDeletions = new HashSet(); - for (Iterator i = listeners.iterator(); i.hasNext();) - ((DirectoryChangeListener) i.next()).startPoll(); + scannedFiles = new HashSet(); + pendingDeletions = new HashSet(); + for (DirectoryChangeListener listener : listeners) + listener.startPoll(); } private void scanDirectories() { @@ -155,8 +155,7 @@ public class DirectoryWatcher { // removed at the end. Then notify all the listeners as needed. scannedFiles.add(file); removals.remove(file); - for (Iterator iterator = listeners.iterator(); iterator.hasNext();) { - DirectoryChangeListener listener = (DirectoryChangeListener) iterator.next(); + for (DirectoryChangeListener listener : listeners) { if (isInterested(listener, file)) processFile(file, listener); } @@ -168,8 +167,8 @@ public class DirectoryWatcher { private void stopPoll() { notifyRemovals(); removals = scannedFiles; - for (Iterator i = listeners.iterator(); i.hasNext();) - ((DirectoryChangeListener) i.next()).stopPoll(); + for (DirectoryChangeListener listener : listeners) + listener.stopPoll(); processPendingDeletions(); } @@ -181,11 +180,9 @@ public class DirectoryWatcher { * Notify the listeners of the files that have been deleted or marked for deletion. */ private void notifyRemovals() { - Set removed = removals; - for (Iterator i = listeners.iterator(); i.hasNext();) { - DirectoryChangeListener listener = (DirectoryChangeListener) i.next(); - for (Iterator j = removed.iterator(); j.hasNext();) { - File file = (File) j.next(); + Set removed = removals; + for (DirectoryChangeListener listener : listeners) { + for (File file : removed) { if (isInterested(listener, file)) listener.removed(file); } @@ -213,8 +210,8 @@ public class DirectoryWatcher { * Try to remove the files that have been marked for deletion. */ private void processPendingDeletions() { - for (Iterator iterator = pendingDeletions.iterator(); iterator.hasNext();) { - File file = (File) iterator.next(); + for (Iterator iterator = pendingDeletions.iterator(); iterator.hasNext();) { + File file = iterator.next(); if (!file.exists() || file.delete()) iterator.remove(); new File(file.getPath() + DEL_EXT).delete(); diff --git a/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/EntryAdvice.java b/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/EntryAdvice.java index 60f6b537c..97877937f 100644 --- a/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/EntryAdvice.java +++ b/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/EntryAdvice.java @@ -10,17 +10,17 @@ ******************************************************************************/ package org.eclipse.equinox.internal.provisional.p2.directorywatcher; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import java.net.URI; +import java.util.HashMap; import java.util.Map; -import java.util.Properties; import org.eclipse.equinox.internal.p2.update.Site; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.actions.IPropertyAdvice; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; /** * Entry advice captures the name, location, modified time, shape etc of something @@ -28,8 +28,8 @@ import org.eclipse.equinox.p2.publisher.actions.IPropertyAdvice; * only one entry at a time and that entry is the the only entry being published. */ public class EntryAdvice implements IPropertyAdvice { - private Properties metadataProps = new Properties(); - private Properties artifactProps = new Properties(); + private Map metadataProps = new HashMap(); + private Map artifactProps = new HashMap(); public boolean isApplicable(String configSpec, boolean includeDefault, String id, Version version) { return true; @@ -43,27 +43,23 @@ public class EntryAdvice implements IPropertyAdvice { if (reference == null) artifactProps.remove(RepositoryListener.ARTIFACT_REFERENCE); else - artifactProps.setProperty(RepositoryListener.ARTIFACT_REFERENCE, reference.toString()); + artifactProps.put(RepositoryListener.ARTIFACT_REFERENCE, reference.toString()); if (location.isDirectory()) - artifactProps.setProperty(RepositoryListener.ARTIFACT_FOLDER, Boolean.TRUE.toString()); + artifactProps.put(RepositoryListener.ARTIFACT_FOLDER, Boolean.TRUE.toString()); else artifactProps.remove(RepositoryListener.ARTIFACT_FOLDER); - artifactProps.setProperty(RepositoryListener.FILE_NAME, location.getAbsolutePath()); - metadataProps.setProperty(RepositoryListener.FILE_NAME, location.getAbsolutePath()); - metadataProps.setProperty(RepositoryListener.FILE_LAST_MODIFIED, Long.toString(timestamp)); + artifactProps.put(RepositoryListener.FILE_NAME, location.getAbsolutePath()); + metadataProps.put(RepositoryListener.FILE_NAME, location.getAbsolutePath()); + metadataProps.put(RepositoryListener.FILE_LAST_MODIFIED, Long.toString(timestamp)); if (linkFile != null) - metadataProps.setProperty(Site.PROP_LINK_FILE, linkFile); + metadataProps.put(Site.PROP_LINK_FILE, linkFile); } - public Map getInstructions(File location) { - return null; - } - - public Properties getArtifactProperties(IInstallableUnit iu, IArtifactDescriptor descriptor) { + public Map getArtifactProperties(IInstallableUnit iu, IArtifactDescriptor descriptor) { return artifactProps; } - public Properties getInstallableUnitProperties(InstallableUnitDescription iu) { + public Map getInstallableUnitProperties(InstallableUnitDescription iu) { return metadataProps; } } diff --git a/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/RepositoryListener.java b/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/RepositoryListener.java index 3d57a80d4..dcf0dd358 100644 --- a/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/RepositoryListener.java +++ b/bundles/org.eclipse.equinox.p2.directorywatcher/src/org/eclipse/equinox/internal/provisional/p2/directorywatcher/RepositoryListener.java @@ -15,19 +15,20 @@ import java.io.File; import java.net.URI; import java.util.*; import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactDescriptor; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.update.Site; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.publisher.*; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; import org.eclipse.equinox.p2.publisher.eclipse.FeaturesAction; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.service.resolver.BundleDescription; import org.eclipse.osgi.util.NLS; @@ -40,8 +41,8 @@ public class RepositoryListener extends DirectoryChangeListener { private final CachingArtifactRepository artifactRepository; // at any point in time currentFiles is the list of files/dirs that the watcher has seen and // believes to be on disk. - private final Map currentFiles = new HashMap(); - private final Collection polledSeenFiles = new HashSet(); + private final Map currentFiles = new HashMap(); + private final Collection polledSeenFiles = new HashSet(); private EntryAdvice advice = new EntryAdvice(); private PublisherInfo info; @@ -88,7 +89,7 @@ public class RepositoryListener extends DirectoryChangeListener { } try { String name = repositoryName; - Map properties = new HashMap(1); + Map properties = new HashMap(1); if (hidden) { properties.put(IRepository.PROP_SYSTEM, Boolean.TRUE.toString()); name = "artifact listener " + repositoryName; //$NON-NLS-1$ @@ -113,7 +114,7 @@ public class RepositoryListener extends DirectoryChangeListener { } try { String name = repositoryName; - Map properties = new HashMap(1); + Map properties = new HashMap(1); if (hidden) { properties.put(IRepository.PROP_SYSTEM, Boolean.TRUE.toString()); name = "metadata listener " + repositoryName; //$NON-NLS-1$ @@ -162,7 +163,7 @@ public class RepositoryListener extends DirectoryChangeListener { } private boolean processFeature(File file, boolean isAddition) { - String link = (String) metadataRepository.getProperties().get(Site.PROP_LINK_FILE); + String link = metadataRepository.getProperties().get(Site.PROP_LINK_FILE); advice.setProperties(file, file.lastModified(), file.toURI(), link); return publish(new FeaturesAction(new File[] {file}), isAddition); } @@ -177,7 +178,7 @@ public class RepositoryListener extends DirectoryChangeListener { } public Long getSeenFile(File file) { - Long lastSeen = (Long) currentFiles.get(file); + Long lastSeen = currentFiles.get(file); if (lastSeen != null) polledSeenFiles.add(file); return lastSeen; @@ -190,7 +191,7 @@ public class RepositoryListener extends DirectoryChangeListener { } public void stopPoll() { - final Set filesToRemove = new HashSet(currentFiles.keySet()); + final Set filesToRemove = new HashSet(currentFiles.keySet()); filesToRemove.removeAll(polledSeenFiles); polledSeenFiles.clear(); @@ -203,20 +204,17 @@ public class RepositoryListener extends DirectoryChangeListener { /** * Flush all the pending changes to the metadata repository. */ - private void synchronizeMetadataRepository(final Collection removedFiles) { + private void synchronizeMetadataRepository(final Collection removedFiles) { if (metadataRepository == null) return; - final Collection changes = iusToChange.getIUs(null, null); + final Collection changes = iusToChange.getIUs(null, null); // first remove any IUs that have changed or that are associated with removed files if (!removedFiles.isEmpty() || !changes.isEmpty()) { - // create a query that will identify all ius related to removed files or ius that have changed - IMatchQuery removeQuery = new MatchQuery() { - public boolean isMatch(Object candidate) { - if (!(candidate instanceof IInstallableUnit)) - return false; - IInstallableUnit iu = (IInstallableUnit) candidate; - if (changes.contains(iu)) - return true; + metadataRepository.removeInstallableUnits(changes.toArray(new IInstallableUnit[changes.size()]), null); + + // create a query that will identify all ius related to removed files + IMatchQuery removeQuery = new MatchQuery() { + public boolean isMatch(IInstallableUnit iu) { String filename = iu.getProperty(FILE_NAME); if (filename == null) { String message = NLS.bind(Messages.filename_missing, "installable unit", iu.getId()); //$NON-NLS-1$ @@ -227,13 +225,14 @@ public class RepositoryListener extends DirectoryChangeListener { return removedFiles.contains(iuFile); } }; - metadataRepository.removeInstallableUnits(removeQuery, null); + IQueryResult toRemove = metadataRepository.query(removeQuery, null); + metadataRepository.removeInstallableUnits(toRemove.toArray(IInstallableUnit.class), null); } // Then add all the new IUs as well as the new copies of the ones that have changed - Collection additions = iusToAdd.getIUs(null, null); + Collection additions = iusToAdd.getIUs(null, null); additions.addAll(changes); if (!additions.isEmpty()) - metadataRepository.addInstallableUnits((IInstallableUnit[]) additions.toArray(new IInstallableUnit[additions.size()])); + metadataRepository.addInstallableUnits(additions.toArray(new IInstallableUnit[additions.size()])); } /** @@ -241,25 +240,21 @@ public class RepositoryListener extends DirectoryChangeListener { * descriptors related to any file that has been removed and flush the repo * to ensure that all the additions and removals have been completed. */ - private void synchronizeArtifactRepository(final Collection removedFiles) { + private void synchronizeArtifactRepository(final Collection removedFiles) { if (artifactRepository == null) return; if (!removedFiles.isEmpty()) { - final List keys = new ArrayList(Arrays.asList(artifactRepository.getArtifactKeys())); - for (Iterator it = keys.iterator(); it.hasNext();) { - IArtifactKey key = (IArtifactKey) it.next(); - IArtifactDescriptor[] descriptors = artifactRepository.getArtifactDescriptors(key); - for (int i = 0; i < descriptors.length; i++) { - ArtifactDescriptor descriptor = (ArtifactDescriptor) descriptors[i]; - String filename = descriptor.getRepositoryProperty(FILE_NAME); - if (filename == null) { - String message = NLS.bind(Messages.filename_missing, "artifact", descriptor.getArtifactKey()); //$NON-NLS-1$ - LogHelper.log(new Status(IStatus.ERROR, Activator.ID, message, null)); - } else { - File artifactFile = new File(filename); - if (removedFiles.contains(artifactFile)) - artifactRepository.removeDescriptor(descriptor); - } + IQueryResult descriptors = artifactRepository.descriptorQueryable().query(ArtifactDescriptorQuery.ALL_DESCRIPTORS, null); + for (Iterator iterator = descriptors.iterator(); iterator.hasNext();) { + SimpleArtifactDescriptor descriptor = (SimpleArtifactDescriptor) iterator.next(); + String filename = descriptor.getRepositoryProperty(FILE_NAME); + if (filename == null) { + String message = NLS.bind(Messages.filename_missing, "artifact", descriptor.getArtifactKey()); //$NON-NLS-1$ + LogHelper.log(new Status(IStatus.ERROR, Activator.ID, message, null)); + } else { + File artifactFile = new File(filename); + if (removedFiles.contains(artifactFile)) + artifactRepository.removeDescriptor(descriptor); } } } @@ -273,9 +268,9 @@ public class RepositoryListener extends DirectoryChangeListener { private void synchronizeCurrentFiles() { currentFiles.clear(); if (metadataRepository != null) { - Collector ius = metadataRepository.query(InstallableUnitQuery.ANY, new Collector(), null); - for (Iterator it = ius.iterator(); it.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) it.next(); + IQueryResult ius = metadataRepository.query(InstallableUnitQuery.ANY, null); + for (Iterator it = ius.iterator(); it.hasNext();) { + IInstallableUnit iu = it.next(); String filename = iu.getProperty(FILE_NAME); if (filename == null) { String message = NLS.bind(Messages.filename_missing, "installable unit", iu.getId()); //$NON-NLS-1$ diff --git a/bundles/org.eclipse.equinox.p2.engine/.classpath b/bundles/org.eclipse.equinox.p2.engine/.classpath index 2fbb7a23e..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.engine/.classpath +++ b/bundles/org.eclipse.equinox.p2.engine/.classpath @@ -1,6 +1,6 @@ - + diff --git a/bundles/org.eclipse.equinox.p2.engine/.settings/.api_filters b/bundles/org.eclipse.equinox.p2.engine/.settings/.api_filters new file mode 100644 index 000000000..5cac838bf --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/.settings/.api_filters @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/bundles/org.eclipse.equinox.p2.engine/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.engine/.settings/org.eclipse.jdt.core.prefs index c98c987a2..0c5749676 100644 --- a/bundles/org.eclipse.equinox.p2.engine/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.engine/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Fri Feb 22 09:19:01 EST 2008 +#Mon Dec 21 23:51:30 CET 2009 eclipse.preferences.version=1 instance/org.eclipse.core.net/org.eclipse.core.net.hasMigrated=true org.eclipse.jdt.core.builder.cleanOutputFolder=clean @@ -8,24 +8,24 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fieldHiding=warning org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning @@ -72,7 +72,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=en org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 diff --git a/bundles/org.eclipse.equinox.p2.engine/ExtensionWizardPage.java b/bundles/org.eclipse.equinox.p2.engine/ExtensionWizardPage.java new file mode 100644 index 000000000..fb7f024d0 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/ExtensionWizardPage.java @@ -0,0 +1,121 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - Initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.server.discovery.internal.wizard; + +import org.eclipse.equinox.p2.engine.ProvisioningPlan; + +import java.lang.reflect.InvocationTargetException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.ui.AcceptLicensesWizardPage; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.wst.server.discovery.ExtensionWizard; +import org.eclipse.wst.server.discovery.internal.Messages; +import org.eclipse.wst.server.discovery.internal.Trace; +import org.eclipse.wst.server.discovery.internal.model.Extension; + +public class ExtensionWizardPage extends WizardPage { + private ExtensionComposite comp; + protected AcceptLicensesWizardPage licensePage; + protected ErrorWizardPage errorPage; + protected IWizardPage nextPage; + private Extension extension; + + public ExtensionWizardPage(AcceptLicensesWizardPage licenseWizardPage, ErrorWizardPage errorWizardPage) { + super("extension"); + this.licensePage = licenseWizardPage; + this.errorPage = errorWizardPage; + setTitle(Messages.wizExtensionTitle); + setDescription(Messages.wizExtensionDescription); + setPageComplete(false); + } + + public void createControl(Composite parent) { + initializeDialogUnits(parent); + Composite composite = new Composite(parent, SWT.NULL); + GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); + composite.setLayoutData(data); + + GridLayout layout = new GridLayout(); + layout.horizontalSpacing = convertHorizontalDLUsToPixels(4); + layout.verticalSpacing = convertVerticalDLUsToPixels(4); + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + //WorkbenchHelp.setHelp(this, ContextIds.SELECT_CLIENT_WIZARD); + + Label label = new Label(composite, SWT.WRAP); + data = new GridData(SWT.FILL, SWT.BEGINNING, false, false); + data.widthHint = 350; + label.setLayoutData(data); + label.setText(Messages.wizExtensionMessage); + + comp = new ExtensionComposite(composite, SWT.NONE, new ExtensionComposite.ExtensionSelectionListener() { + public void extensionSelected(Extension sel) { + handleSelection(sel); + } + }); + data = new GridData(SWT.FILL, SWT.FILL, true, true); + data.heightHint = 375; + comp.setLayoutData(data); + + Dialog.applyDialogFont(composite); + setControl(composite); + } + + protected void handleSelection(Extension sel) { + extension = sel; + if (extension == null) + licensePage.update(new IInstallableUnit[0], null); + else { + try { + getContainer().run(true, true, new IRunnableWithProgress() { + public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { + final ProvisioningPlan plan = extension.getProvisioningPlan(true, monitor); + if (plan != null && plan.getStatus().isOK()) { + getShell().getDisplay().asyncExec(new Runnable() { + public void run() { + licensePage.update(extension.getIUs(), plan); + nextPage = licensePage; + ((ExtensionWizard)getWizard()).setSecondPage(nextPage); + } + }); + } else { + getShell().getDisplay().asyncExec(new Runnable() { + public void run() { + errorPage.setStatus(plan.getStatus()); + } + }); + nextPage = errorPage; + ((ExtensionWizard)getWizard()).setSecondPage(nextPage); + } + monitor.done(); + } + }); + } catch (Exception e) { + Trace.trace(Trace.SEVERE, "Error verifying license", e); + } + } + setPageComplete(extension != null); + } + + public Extension getExtension() { + return extension; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.engine/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.engine/META-INF/MANIFEST.MF index ac818ce52..d77b5cc24 100644 --- a/bundles/org.eclipse.equinox.p2.engine/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.engine/META-INF/MANIFEST.MF @@ -4,46 +4,47 @@ Bundle-SymbolicName: org.eclipse.equinox.p2.engine;singleton:=true Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-Localization: plugin -Bundle-Version: 1.1.0.qualifier -Export-Package: org.eclipse.equinox.internal.p2.engine;x-friends:="org.eclipse.equinox.p2.touchpoint.eclipse,org.eclipse.equinox.p2.touchpoint.natives", - org.eclipse.equinox.internal.provisional.p2.engine; - x-friends:="org.eclipse.equinox.p2.console, - org.eclipse.equinox.p2.director, - org.eclipse.equinox.p2.director.app, - org.eclipse.equinox.p2.extensionlocation, - org.eclipse.equinox.p2.garbagecollector, - org.eclipse.equinox.p2.installer, - org.eclipse.equinox.p2.reconciler.dropins, - org.eclipse.equinox.p2.touchpoint.eclipse, +Bundle-Version: 2.0.0.qualifier +Export-Package: org.eclipse.equinox.internal.p2.engine; + x-friends:="org.eclipse.equinox.p2.touchpoint.eclipse, org.eclipse.equinox.p2.touchpoint.natives, - org.eclipse.equinox.p2.ui, - org.eclipse.equinox.p2.ui.admin, - org.eclipse.equinox.p2.ui.sdk, + org.eclipse.equinox.p2.operations, + org.eclipse.equinox.p2.director, org.eclipse.equinox.p2.ui.sdk.scheduler, - org.eclipse.equinox.p2.updatechecker, - org.eclipse.pde.ui, - org.eclipse.equinox.p2.repository.tools, + org.eclipse.pde.build, org.eclipse.pde.core", - org.eclipse.equinox.internal.provisional.p2.engine.phases;x-friends:="org.eclipse.equinox.p2.ui,org.eclipse.equinox.p2.repository.tools,org.eclipse.equinox.p2.director.app" + org.eclipse.equinox.internal.p2.engine.phases; + x-friends:="org.eclipse.equinox.p2.operations, + org.eclipse.equinox.p2.ui.sdk.scheduler, + org.eclipse.equinox.p2.repository.tools, + org.eclipse.equinox.p2.director.app", + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.engine.query, + org.eclipse.equinox.p2.engine.spi Import-Package: javax.xml.parsers, org.eclipse.core.internal.preferences, org.eclipse.core.runtime.preferences, org.eclipse.equinox.internal.p2.core.helpers, + org.eclipse.equinox.internal.p2.metadata, + org.eclipse.equinox.internal.p2.metadata.query, org.eclipse.equinox.internal.p2.metadata.repository, org.eclipse.equinox.internal.p2.metadata.repository.io, org.eclipse.equinox.internal.p2.persistence, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.core.eventbus, - org.eclipse.equinox.internal.provisional.p2.core.location, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, org.eclipse.equinox.internal.provisional.p2.repository, - org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.spi.p2.repository, org.eclipse.equinox.p2.core, org.eclipse.equinox.p2.core.spi, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.metadata, + org.eclipse.equinox.p2.repository.metadata.spi, + org.eclipse.equinox.p2.repository.spi, + org.eclipse.equinox.security.storage;version="1.0.0", org.eclipse.osgi.service.datalocation;version="1.0.0", org.eclipse.osgi.service.debug;version="1.1.0", org.eclipse.osgi.service.security;version="1.0.0", @@ -56,7 +57,8 @@ Import-Package: javax.xml.parsers, Bundle-Activator: org.eclipse.equinox.internal.p2.engine.EngineActivator Bundle-ActivationPolicy: lazy Eclipse-RegisterBuddy: org.eclipse.equinox.p2.metadata.repository -Bundle-RequiredExecutionEnvironment: J2SE-1.4, +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, CDC-1.1/Foundation-1.1 Require-Bundle: org.eclipse.equinox.common, org.eclipse.equinox.registry, diff --git a/bundles/org.eclipse.equinox.p2.engine/OSGI-INF/engine.xml b/bundles/org.eclipse.equinox.p2.engine/OSGI-INF/engine.xml index 2f6630ca2..e656d3628 100644 --- a/bundles/org.eclipse.equinox.p2.engine/OSGI-INF/engine.xml +++ b/bundles/org.eclipse.equinox.p2.engine/OSGI-INF/engine.xml @@ -4,5 +4,5 @@ - + \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.engine/OSGI-INF/profileRegistry.xml b/bundles/org.eclipse.equinox.p2.engine/OSGI-INF/profileRegistry.xml index 4cb89bde7..3d4ac8384 100644 --- a/bundles/org.eclipse.equinox.p2.engine/OSGI-INF/profileRegistry.xml +++ b/bundles/org.eclipse.equinox.p2.engine/OSGI-INF/profileRegistry.xml @@ -4,5 +4,5 @@ - + \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.engine/build.properties b/bundles/org.eclipse.equinox.p2.engine/build.properties index f55cc8399..c83017ced 100644 --- a/bundles/org.eclipse.equinox.p2.engine/build.properties +++ b/bundles/org.eclipse.equinox.p2.engine/build.properties @@ -19,3 +19,5 @@ bin.includes = META-INF/,\ src.includes = about.html,\ schema/ source.. = src/ +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.engine/schema/actions.exsd b/bundles/org.eclipse.equinox.p2.engine/schema/actions.exsd index 05b25cc0c..d1069d52e 100644 --- a/bundles/org.eclipse.equinox.p2.engine/schema/actions.exsd +++ b/bundles/org.eclipse.equinox.p2.engine/schema/actions.exsd @@ -2,9 +2,9 @@ - + - + [Enter description of this extension point.] @@ -12,9 +12,9 @@ - + - + @@ -39,9 +39,9 @@ - + - + @@ -68,9 +68,9 @@ - - - + + + @@ -98,36 +98,36 @@ - + - + [Enter the first release in which this extension point appears.] - + - + [Enter extension point usage example here.] - + - + [Enter API information here.] - + - + [Enter information about supplied implementation of this extension point.] diff --git a/bundles/org.eclipse.equinox.p2.engine/schema/touchpoints.exsd b/bundles/org.eclipse.equinox.p2.engine/schema/touchpoints.exsd index 12a2d81c7..6635c9790 100644 --- a/bundles/org.eclipse.equinox.p2.engine/schema/touchpoints.exsd +++ b/bundles/org.eclipse.equinox.p2.engine/schema/touchpoints.exsd @@ -69,7 +69,7 @@ - + diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ActionManager.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ActionManager.java index fb11e168f..acbca8436 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ActionManager.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ActionManager.java @@ -10,15 +10,14 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.engine; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.engine.Touchpoint; -import org.eclipse.equinox.internal.provisional.p2.metadata.ITouchpointType; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.Touchpoint; +import org.eclipse.equinox.p2.metadata.ITouchpointType; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.osgi.util.NLS; public class ActionManager implements IRegistryChangeListener { @@ -29,8 +28,13 @@ public class ActionManager implements IRegistryChangeListener { private static final String ATTRIBUTE_NAME = "name"; //$NON-NLS-1$ private static final String TOUCHPOINT_TYPE = "touchpointType"; //$NON-NLS-1$ private static final String TOUCHPOINT_VERSION = "touchpointVersion"; //$NON-NLS-1$ + /** + * Service name constant for the action manager service. This service is used internally + * by the engine implementation and should not be referenced directly by clients. + */ + public static final String SERVICE_NAME = ActionManager.class.getName(); - private HashMap actionMap; + private HashMap actionMap; private TouchpointManager touchpointManager; public ActionManager() { @@ -58,7 +62,7 @@ public class ActionManager implements IRegistryChangeListener { } public ProvisioningAction getAction(String actionId, VersionRange versionRange) { - IConfigurationElement actionElement = (IConfigurationElement) getActionMap().get(actionId); + IConfigurationElement actionElement = getActionMap().get(actionId); if (actionElement != null && actionElement.isValid()) { try { ProvisioningAction action = (ProvisioningAction) actionElement.createExecutableExtension(ATTRIBUTE_CLASS); @@ -81,12 +85,12 @@ public class ActionManager implements IRegistryChangeListener { return null; } - private synchronized Map getActionMap() { + private synchronized Map getActionMap() { if (actionMap != null) return actionMap; IExtensionPoint point = RegistryFactory.getRegistry().getExtensionPoint(EngineActivator.ID, PT_ACTIONS); IExtension[] extensions = point.getExtensions(); - actionMap = new HashMap(extensions.length); + actionMap = new HashMap(extensions.length); for (int i = 0; i < extensions.length; i++) { try { IConfigurationElement[] elements = extensions[i].getConfigurationElements(); diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/DebugHelper.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/DebugHelper.java index 04df2dfdb..ec9ebd502 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/DebugHelper.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/DebugHelper.java @@ -14,9 +14,10 @@ import java.io.File; import java.util.*; import java.util.Map.Entry; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.osgi.service.debug.DebugOptions; public class DebugHelper { @@ -52,8 +53,8 @@ public class DebugHelper { System.out.println(buffer.toString()); } - public static String formatArray(Object[] array, boolean toString, boolean newLines) { - if (array == null || array.length == 0) + public static String formatArray(List array, boolean toString, boolean newLines) { + if (array == null || array.size() == 0) return "[]"; //$NON-NLS-1$ StringBuffer buffer = new StringBuffer(); @@ -61,11 +62,11 @@ public class DebugHelper { int i = 0; for (;;) { if (toString) - buffer.append(array[i].toString()); + buffer.append(array.get(i).toString()); else - buffer.append(array[i].getClass().getName()); + buffer.append(array.get(i).getClass().getName()); i++; - if (i == array.length) + if (i == array.size()) break; buffer.append(','); if (newLines) @@ -99,7 +100,7 @@ public class DebugHelper { operandStrings[i] = operands[i].toString(); } } - return DebugHelper.formatArray(operandStrings, true, true); + return DebugHelper.formatArray(Arrays.asList(operandStrings), true, true); } public static String formatInstallableUnitOperand(InstallableUnitOperand iuOperand) { @@ -116,19 +117,19 @@ public class DebugHelper { public static String formatPhaseSet(PhaseSet phaseSet) { StringBuffer buffer = new StringBuffer(phaseSet.getClass().getName()); - buffer.append(DebugHelper.formatArray(phaseSet.getPhases(), false, false)); + buffer.append(DebugHelper.formatArray(Arrays.asList(phaseSet.getPhases()), false, false)); return buffer.toString(); } public static String formatContext(ProvisioningContext context) { StringBuffer buffer = new StringBuffer(); - buffer.append("{artifactRepos=" + DebugHelper.formatArray(context.getArtifactRepositories(), true, false)); //$NON-NLS-1$ - buffer.append(", metadataRepos=" + DebugHelper.formatArray(context.getMetadataRepositories(), true, false)); //$NON-NLS-1$ + buffer.append("{artifactRepos=" + DebugHelper.formatArray(Arrays.asList(context.getArtifactRepositories()), true, false)); //$NON-NLS-1$ + buffer.append(", metadataRepos=" + DebugHelper.formatArray(Arrays.asList(context.getMetadataRepositories()), true, false)); //$NON-NLS-1$ buffer.append(", properties=" + context.getProperties() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ return buffer.toString(); } - public static String formatAction(ProvisioningAction action, Map parameters) { + public static String formatAction(ProvisioningAction action, Map parameters) { StringBuffer buffer = new StringBuffer(); buffer.append(action.getClass().getName()); if (action instanceof ParameterizedProvisioningAction) { @@ -141,16 +142,16 @@ public class DebugHelper { return buffer.toString(); } - public static String formatParameters(Map parameters) { - Iterator it = parameters.entrySet().iterator(); + public static String formatParameters(Map parameters) { + Iterator> it = parameters.entrySet().iterator(); if (!it.hasNext()) return "{}"; //$NON-NLS-1$ StringBuffer buffer = new StringBuffer(); buffer.append('{'); for (;;) { - Entry e = (Entry) it.next(); - String key = (String) e.getKey(); + Entry e = it.next(); + String key = e.getKey(); buffer.append(key); buffer.append('='); Object value = e.getValue(); diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/DownloadManager.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/DownloadManager.java index 9f1486c71..0db1b83d0 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/DownloadManager.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/DownloadManager.java @@ -14,29 +14,25 @@ package org.eclipse.equinox.internal.p2.engine; import java.net.URI; import java.util.*; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.*; public class DownloadManager { private ProvisioningContext provContext = null; - ArrayList requestsToProcess = new ArrayList(); + ArrayList requestsToProcess = new ArrayList(); private static final String FILE_PROTOCOL = "file"; //$NON-NLS-1$ /** - * This Comparator sorts the repositories such that ´local´ repositories are first + * This Comparator sorts the repositories such that �local� repositories are first */ - private static final Comparator LOCAL_FIRST_COMPARATOR = new Comparator() { + private static final Comparator LOCAL_FIRST_COMPARATOR = new Comparator() { - public int compare(Object arg0, Object arg1) { - Assert.isTrue(arg0 instanceof URI); - Assert.isTrue(arg1 instanceof URI); - - String protocol0 = ((URI) arg0).getScheme(); - String protocol1 = ((URI) arg1).getScheme(); + public int compare(URI arg0, URI arg1) { + String protocol0 = arg0.getScheme(); + String protocol1 = arg1.getScheme(); if (FILE_PROTOCOL.equals(protocol0) && !FILE_PROTOCOL.equals(protocol1)) return -1; @@ -45,9 +41,11 @@ public class DownloadManager { return 0; } }; + private final IArtifactRepositoryManager repositoryManager; - public DownloadManager(ProvisioningContext context) { + public DownloadManager(ProvisioningContext context, IArtifactRepositoryManager repositoryManager) { provContext = context; + this.repositoryManager = repositoryManager; } /* @@ -67,8 +65,8 @@ public class DownloadManager { } private void filterUnfetched() { - for (Iterator iterator = requestsToProcess.iterator(); iterator.hasNext();) { - IArtifactRequest request = (IArtifactRequest) iterator.next(); + for (Iterator iterator = requestsToProcess.iterator(); iterator.hasNext();) { + IArtifactRequest request = iterator.next(); if (request.getResult() != null && request.getResult().isOK()) { iterator.remove(); } @@ -84,26 +82,25 @@ public class DownloadManager { if (requestsToProcess.isEmpty()) return Status.OK_STATUS; - IArtifactRepositoryManager repoMgr = (IArtifactRepositoryManager) ServiceHelper.getService(EngineActivator.getContext(), IArtifactRepositoryManager.class.getName()); URI[] repositories = null; if (provContext == null || provContext.getArtifactRepositories() == null) - repositories = repoMgr.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); + repositories = repositoryManager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); else repositories = provContext.getArtifactRepositories(); if (repositories.length == 0) return new Status(IStatus.ERROR, EngineActivator.ID, Messages.download_no_repository, new Exception()); Arrays.sort(repositories, LOCAL_FIRST_COMPARATOR); - fetch(repoMgr, repositories, subMonitor); + fetch(repositories, subMonitor); return overallStatus(monitor); } finally { subMonitor.done(); } } - private void fetch(IArtifactRepositoryManager repoMgr, URI[] repositories, SubMonitor monitor) { + private void fetch(URI[] repositories, SubMonitor monitor) { for (int i = 0; i < repositories.length && !requestsToProcess.isEmpty() && !monitor.isCanceled(); i++) { try { - IArtifactRepository current = repoMgr.loadRepository(repositories[i], monitor.newChild(0)); + IArtifactRepository current = repositoryManager.loadRepository(repositories[i], monitor.newChild(0)); IArtifactRequest[] requests = getRequestsForRepository(current); IStatus dlStatus = current.getArtifacts(requests, monitor.newChild(requests.length)); if (dlStatus.getSeverity() == IStatus.CANCEL) @@ -117,13 +114,12 @@ public class DownloadManager { } private IArtifactRequest[] getRequestsForRepository(IArtifactRepository repository) { - ArrayList applicable = new ArrayList(); - for (Iterator it = requestsToProcess.iterator(); it.hasNext();) { - IArtifactRequest request = (IArtifactRequest) it.next(); + ArrayList applicable = new ArrayList(); + for (IArtifactRequest request : requestsToProcess) { if (repository.contains(request.getArtifactKey())) applicable.add(request); } - return (IArtifactRequest[]) applicable.toArray(new IArtifactRequest[applicable.size()]); + return applicable.toArray(new IArtifactRequest[applicable.size()]); } // private void notifyFetched() { @@ -139,8 +135,8 @@ public class DownloadManager { return Status.OK_STATUS; MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); - for (Iterator iterator = requestsToProcess.iterator(); iterator.hasNext();) { - IStatus failed = ((IArtifactRequest) iterator.next()).getResult(); + for (IArtifactRequest request : requestsToProcess) { + IStatus failed = request.getResult(); if (failed != null && !failed.isOK()) result.add(failed); } diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Engine.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Engine.java new file mode 100644 index 000000000..c9c10ad3b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Engine.java @@ -0,0 +1,129 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.engine; + +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; +import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.*; + +/** + * TODO Move concrete class to non-API package + */ +public class Engine implements IEngine { + + private static final String ENGINE = "engine"; //$NON-NLS-1$ + private IProvisioningAgent agent; + + public Engine(IProvisioningAgent agent) { + this.agent = agent; + agent.registerService(ActionManager.SERVICE_NAME, new ActionManager()); + } + + private void checkArguments(IProfile iprofile, PhaseSet phaseSet, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) { + if (iprofile == null) + throw new IllegalArgumentException(Messages.null_profile); + + if (phaseSet == null) + throw new IllegalArgumentException(Messages.null_phaseset); + + if (operands == null) + throw new IllegalArgumentException(Messages.null_operands); + } + + public IStatus perform(IProvisioningPlan plan, IPhaseSet phaseSet, IProgressMonitor monitor) { + return perform(plan.getProfile(), phaseSet, plan.getOperands(), plan.getContext(), monitor); + } + + public IStatus perform(IProvisioningPlan plan, IProgressMonitor monitor) { + return perform(plan.getProfile(), new DefaultPhaseSet(), plan.getOperands(), plan.getContext(), monitor); + } + + public IStatus perform(IProfile iprofile, IPhaseSet phases, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) { + PhaseSet phaseSet = (PhaseSet) phases; + checkArguments(iprofile, phaseSet, operands, context, monitor); + SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME); + IProvisioningEventBus eventBus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME); + + if (context == null) + context = new ProvisioningContext(); + + if (monitor == null) + monitor = new NullProgressMonitor(); + + Profile profile = profileRegistry.validate(iprofile); + + profileRegistry.lockProfile(profile); + try { + eventBus.publishEvent(new BeginOperationEvent(profile, phaseSet, operands, this)); + if (DebugHelper.DEBUG_ENGINE) + DebugHelper.debug(ENGINE, "Beginning engine operation for profile=" + profile.getProfileId() + " [" + profile.getTimestamp() + "]:" + DebugHelper.LINE_SEPARATOR + DebugHelper.formatOperation(phaseSet, operands, context)); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + + EngineSession session = new EngineSession(agent, profile, context); + + MultiStatus result = phaseSet.perform(session, operands, monitor); + if (result.isOK() || result.matches(IStatus.INFO | IStatus.WARNING)) { + if (DebugHelper.DEBUG_ENGINE) + DebugHelper.debug(ENGINE, "Preparing to commit engine operation for profile=" + profile.getProfileId()); //$NON-NLS-1$ + result.merge(session.prepare(monitor)); + } + if (result.matches(IStatus.ERROR | IStatus.CANCEL)) { + if (DebugHelper.DEBUG_ENGINE) + DebugHelper.debug(ENGINE, "Rolling back engine operation for profile=" + profile.getProfileId() + ". Reason was: " + result.toString()); //$NON-NLS-1$ //$NON-NLS-2$ + IStatus status = session.rollback(monitor, result.getSeverity()); + if (status.matches(IStatus.ERROR)) + LogHelper.log(status); + eventBus.publishEvent(new RollbackOperationEvent(profile, phaseSet, operands, this, result)); + } else { + if (DebugHelper.DEBUG_ENGINE) + DebugHelper.debug(ENGINE, "Committing engine operation for profile=" + profile.getProfileId()); //$NON-NLS-1$ + if (profile.isChanged()) + profileRegistry.updateProfile(profile); + IStatus status = session.commit(monitor); + if (status.matches(IStatus.ERROR)) + LogHelper.log(status); + eventBus.publishEvent(new CommitOperationEvent(profile, phaseSet, operands, this)); + } + //if there is only one child status, return that status instead because it will have more context + IStatus[] children = result.getChildren(); + return children.length == 1 ? children[0] : result; + } finally { + profileRegistry.unlockProfile(profile); + profile.setChanged(false); + } + } + + public IStatus validate(IProfile iprofile, PhaseSet phaseSet, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) { + checkArguments(iprofile, phaseSet, operands, context, monitor); + + if (context == null) + context = new ProvisioningContext(); + + if (monitor == null) + monitor = new NullProgressMonitor(); + + ActionManager actionManager = (ActionManager) agent.getService(ActionManager.SERVICE_NAME); + return phaseSet.validate(actionManager, iprofile, operands, context, monitor); + } + + public IPhaseSet createPhaseSetExcluding(String[] excludes) { + return PhaseSet.createPhaseSetExcluding(excludes); + } + + public IPhaseSet createPhaseSetIncluding(String[] includes) { + return PhaseSet.createPhaseSetIncluding(includes); + } + + public IProvisioningPlan createCustomPlan(IProfile profile, Operand[] operands, ProvisioningContext context) { + return new ProvisioningPlan(profile, operands, context); + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineActivator.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineActivator.java index ead37e3b0..114b2caea 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineActivator.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineActivator.java @@ -11,9 +11,8 @@ package org.eclipse.equinox.internal.p2.engine; import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.engine.Engine; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IEngine; import org.osgi.framework.*; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; @@ -67,9 +66,11 @@ public class EngineActivator implements BundleActivator, ServiceTrackerCustomize public Object addingService(ServiceReference reference) { if (registration == null) { - IProvisioningEventBus eventBus = (IProvisioningEventBus) context.getService(reference); - registration = context.registerService(IEngine.SERVICE_NAME, new Engine(eventBus), null); - return eventBus; + //TODO: eventually we shouldn't register a singleton engine automatically + IProvisioningAgent agent = (IProvisioningAgent) context.getService(reference); + IEngine engine = (IEngine) agent.getService(IEngine.SERVICE_NAME); + registration = context.registerService(IEngine.SERVICE_NAME, engine, null); + return agent; } return null; } @@ -87,7 +88,9 @@ public class EngineActivator implements BundleActivator, ServiceTrackerCustomize public void start(BundleContext aContext) throws Exception { EngineActivator.context = aContext; - tracker = new ServiceTracker(aContext, IProvisioningEventBus.SERVICE_NAME, this); + //only want to register a service for the agent of the currently running system + String filter = "(&(objectClass=" + IProvisioningAgent.SERVICE_NAME + ")(agent.current=true))"; //$NON-NLS-1$ //$NON-NLS-2$ + tracker = new ServiceTracker(context, aContext.createFilter(filter), this); tracker.open(); } diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineComponent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineComponent.java index 6a8de3a60..7a20606d7 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineComponent.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineComponent.java @@ -10,10 +10,9 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.engine; -import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.p2.core.IProvisioningAgent; import org.eclipse.equinox.p2.core.spi.IAgentServiceFactory; +import org.eclipse.equinox.p2.engine.IEngine; /** * Component that provides a factory that can create and initialize @@ -25,9 +24,7 @@ public class EngineComponent implements IAgentServiceFactory { * @see org.eclipse.equinox.p2.core.spi.IAgentServiceFactory#createService(org.eclipse.equinox.p2.core.IProvisioningAgent) */ public Object createService(IProvisioningAgent agent) { - IProvisioningEventBus bus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME); - Engine result = new Engine(bus); - result.setProfileRegistry((IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME)); - return result; + //various parts of the engine may need an open-ended set of services, so we pass the agent to the engine directly + return new Engine(agent); } } diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineSession.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineSession.java new file mode 100644 index 000000000..e9f6b1919 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/EngineSession.java @@ -0,0 +1,399 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.engine; + +import java.io.File; +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.Touchpoint; +import org.eclipse.osgi.util.NLS; + +/** + * TODO: not API + */ +public class EngineSession { + private static final String ENGINE_SESSION = "enginesession"; //$NON-NLS-1$ + + private static final String EMPTY_STRING = ""; //$NON-NLS-1$ + + private static class ActionsRecord { + Operand operand; + List actions = new ArrayList(); + + ActionsRecord(Operand operand) { + this.operand = operand; + } + } + + private List phaseActionRecordsPairs = new ArrayList(); + + private Phase currentPhase; + boolean currentPhaseActive; + + private List currentActionRecords; + private ActionsRecord currentRecord; + + private IProfile profile; + + private ProvisioningContext context; + + private final HashMap sessionServices = new HashMap(); + + private Set touchpoints = new HashSet(); + + private final IProvisioningAgent agent; + + public EngineSession(IProvisioningAgent agent, IProfile profile, ProvisioningContext context) { + super(); + this.agent = agent; + this.profile = profile; + this.context = context; + } + + public IProfile getProfile() { + return profile; + } + + public IProvisioningAgent getAgent() { + return agent; + } + + public ProvisioningContext getProvisioningContext() { + return context; + } + + public File getProfileDataDirectory() { + SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME); + return profileRegistry.getProfileDataDirectory(profile.getProfileId()); + } + + /** + * This is the interface through which parts of the engine obtain the services they need + * @param serviceName The name of the service to obtain + * @return The service instance, or null if no such service is available + */ + public Object getxService(String serviceName) { + Object result = sessionServices.get(serviceName); + if (result != null) + return result; + return agent.getService(serviceName); + } + + IStatus prepare(IProgressMonitor monitor) { + monitor.subTask(Messages.preparing); + MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); + for (Touchpoint touchpoint : touchpoints) { + try { + status.add(touchpoint.prepare(profile)); + } catch (RuntimeException e) { + // "touchpoint.prepare" calls user code and might throw an unchecked exception + // we catch the error here to gather information on where the problem occurred. + status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.touchpoint_prepare_error, touchpoint.getClass().getName()), e)); + } catch (LinkageError e) { + // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) + status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.touchpoint_prepare_error, touchpoint.getClass().getName()), e)); + } + } + + if (status.matches(IStatus.ERROR)) { + MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.ERROR, NLS.bind(Messages.session_prepare_error, profile.getProfileId()), null); + result.merge(status); + return result; + } + return status; + } + + IStatus commit(IProgressMonitor monitor) { + monitor.subTask(Messages.committing); + MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); + phaseActionRecordsPairs.clear(); + for (Touchpoint touchpoint : touchpoints) { + try { + IStatus result = touchpoint.commit(profile); + if (!result.isOK()) + status.add(result); + } catch (RuntimeException e) { + // "touchpoint.commit" calls user code and might throw an unchecked exception + // we catch the error here to gather information on where the problem occurred. + status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.touchpoint_commit_error, touchpoint.getClass().getName()), e)); + } catch (LinkageError e) { + // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) + status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.touchpoint_commit_error, touchpoint.getClass().getName()), e)); + } + } + + if (status.matches(IStatus.ERROR)) { + MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.ERROR, NLS.bind(Messages.session_commit_error, profile.getProfileId()), null); + result.merge(status); + return result; + } + return status; + } + + IStatus rollback(IProgressMonitor monitor, int severity) { + if (severity == IStatus.CANCEL) + monitor.subTask(Messages.rollingback_cancel); + + if (severity == IStatus.ERROR) + monitor.subTask(Messages.rollingback_error); + + MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); + + if (currentPhaseActive) { + try { + IStatus result = rollBackPhase(currentPhase, currentActionRecords); + if (!result.isOK()) + status.add(result); + } catch (RuntimeException e) { + // "phase.prePerform and phase.postPerform" calls user code and might throw an unchecked exception + // we catch the error here to gather information on where the problem occurred. + status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.phase_undo_error, currentPhase.getClass().getName()), e)); + } catch (LinkageError e) { + // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) + status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.phase_undo_error, currentPhase.getClass().getName()), e)); + } + currentPhaseActive = false; + currentActionRecords = null; + currentRecord = null; + } + currentPhase = null; + + for (ListIterator it = phaseActionRecordsPairs.listIterator(phaseActionRecordsPairs.size()); it.hasPrevious();) { + Object[] pair = it.previous(); + Phase phase = (Phase) pair[0]; + @SuppressWarnings("unchecked") + List actionRecords = (List) pair[1]; + try { + final IStatus result = rollBackPhase(phase, actionRecords); + if (!result.isOK()) + status.add(result); + } catch (RuntimeException e) { + // "phase.prePerform and phase.postPerform" calls user code and might throw an unchecked exception + // we catch the error here to gather information on where the problem occurred. + status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.phase_undo_error, phase.getClass().getName()), e)); + } catch (LinkageError e) { + // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) + status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.phase_undo_error, phase.getClass().getName()), e)); + } + } + + phaseActionRecordsPairs.clear(); + for (Touchpoint touchpoint : touchpoints) { + try { + IStatus result = touchpoint.rollback(profile); + if (!result.isOK()) + status.add(result); + } catch (RuntimeException e) { + // "touchpoint.rollback" calls user code and might throw an unchecked exception + // we catch the error here to gather information on where the problem occurred. + status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.touchpoint_rollback_error, touchpoint.getClass().getName()), e)); + } catch (LinkageError e) { + // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) + status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.touchpoint_rollback_error, touchpoint.getClass().getName()), e)); + } + } + + if (status.matches(IStatus.ERROR)) { + MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.ERROR, NLS.bind(Messages.session_commit_error, profile.getProfileId()), null); + result.merge(status); + return result; + } + return status; + } + + private IStatus rollBackPhase(Phase phase, List actionRecords) { + MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); + try { + phase.actionManager = (ActionManager) agent.getService(ActionManager.SERVICE_NAME); + + if (!currentPhaseActive) + phase.prePerform(result, this, new NullProgressMonitor()); + + for (ListIterator it = actionRecords.listIterator(actionRecords.size()); it.hasPrevious();) { + ActionsRecord record = it.previous(); + ProvisioningAction[] actions = record.actions.toArray(new ProvisioningAction[record.actions.size()]); + try { + phase.undo(result, this, profile, record.operand, actions, context); + } catch (RuntimeException e) { + // "phase.undo" calls user code and might throw an unchecked exception + // we catch the error here to gather information on where the problem occurred. + result.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.phase_undo_operand_error, phase.getClass().getName(), record.operand), e)); + } catch (LinkageError e) { + // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) + result.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.phase_undo_operand_error, phase.getClass().getName(), record.operand), e)); + } + } + phase.postPerform(result, this, new NullProgressMonitor()); + } finally { + phase.actionManager = null; + } + return result; + } + + void recordPhaseEnter(Phase phase) { + if (phase == null) + throw new IllegalArgumentException(Messages.null_phase); + + if (currentPhase != null) + throw new IllegalStateException(Messages.phase_started); + + currentPhase = phase; + + if (DebugHelper.DEBUG_ENGINE_SESSION) + debugPhaseEnter(phase); + } + + void recordPhaseStart(Phase phase) { + if (phase == null) + throw new IllegalArgumentException(Messages.null_phase); + + if (currentPhase != phase) + throw new IllegalArgumentException(Messages.not_current_phase); + + currentPhaseActive = true; + currentActionRecords = new ArrayList(); + } + + void recordPhaseEnd(Phase phase) { + if (currentPhase == null) + throw new IllegalStateException(Messages.phase_not_started); + + if (currentPhase != phase) + throw new IllegalArgumentException(Messages.not_current_phase); + + phaseActionRecordsPairs.add(new Object[] {currentPhase, currentActionRecords}); + currentActionRecords = null; + currentPhaseActive = false; + } + + void recordPhaseExit(Phase phase) { + if (currentPhase == null) + throw new IllegalStateException(Messages.phase_not_started); + + if (currentPhase != phase) + throw new IllegalArgumentException(Messages.not_current_phase); + + currentPhase = null; + if (DebugHelper.DEBUG_ENGINE_SESSION) + debugPhaseExit(phase); + } + + void recordOperandStart(Operand operand) { + if (operand == null) + throw new IllegalArgumentException(Messages.null_operand); + + if (currentRecord != null) + throw new IllegalStateException(Messages.operand_started); + + currentRecord = new ActionsRecord(operand); + currentActionRecords.add(currentRecord); + + if (DebugHelper.DEBUG_ENGINE_SESSION) + debugOperandStart(operand); + } + + void recordOperandEnd(Operand operand) { + if (currentRecord == null) + throw new IllegalStateException(Messages.operand_not_started); + + if (currentRecord.operand != operand) + throw new IllegalArgumentException(Messages.not_current_operand); + + currentRecord = null; + + if (DebugHelper.DEBUG_ENGINE_SESSION) + debugOperandEnd(operand); + } + + void recordActionExecute(ProvisioningAction action, Map parameters) { + if (action == null) + throw new IllegalArgumentException(Messages.null_action); + + currentRecord.actions.add(action); + + Touchpoint touchpoint = action.getTouchpoint(); + if (touchpoint != null) + touchpoints.add(touchpoint); + + if (DebugHelper.DEBUG_ENGINE_SESSION) + debugActionExecute(action, parameters); + } + + public void recordActionUndo(ProvisioningAction action, Map parameters) { + if (DebugHelper.DEBUG_ENGINE_SESSION) + debugActionUndo(action, parameters); + } + + public String getContextString(Phase phase, Operand operand, ProvisioningAction action) { + if (action instanceof ParameterizedProvisioningAction) { + ParameterizedProvisioningAction parameterizedAction = (ParameterizedProvisioningAction) action; + action = parameterizedAction.getAction(); + } + String message = NLS.bind(Messages.session_context, new Object[] {profile.getProfileId(), phase.getClass().getName(), operand.toString(), getCurrentActionId()}); + return message; + } + + public String getContextString() { + String message = NLS.bind(Messages.session_context, new Object[] {profile.getProfileId(), getCurrentPhaseId(), getCurrentOperandId(), getCurrentActionId()}); + return message; + } + + private Object getCurrentActionId() { + if (currentRecord == null || currentRecord.actions.isEmpty()) + return EMPTY_STRING; + + Object currentAction = currentRecord.actions.get(currentRecord.actions.size() - 1); + if (currentAction instanceof ParameterizedProvisioningAction) { + ParameterizedProvisioningAction parameterizedAction = (ParameterizedProvisioningAction) currentAction; + currentAction = parameterizedAction.getAction(); + } + return currentAction.getClass().getName(); + } + + private String getCurrentPhaseId() { + if (currentPhase == null) + return EMPTY_STRING; + return currentPhase.getClass().getName(); + } + + private String getCurrentOperandId() { + if (currentRecord == null) + return EMPTY_STRING; + return currentRecord.operand.toString(); + } + + private static void debugPhaseEnter(Phase phase) { + DebugHelper.debug(ENGINE_SESSION, "Entering phase: " + phase.getClass().getName()); //$NON-NLS-1$ + } + + private static void debugPhaseExit(Phase phase) { + DebugHelper.debug(ENGINE_SESSION, "Exiting phase: " + phase.getClass().getName()); //$NON-NLS-1$ + } + + private static void debugOperandStart(Operand operand) { + DebugHelper.debug(ENGINE_SESSION, "Starting processing of operand: " + operand.toString()); //$NON-NLS-1$ + } + + private static void debugOperandEnd(Operand operand) { + DebugHelper.debug(ENGINE_SESSION, "Ending processing of operand: " + operand.toString()); //$NON-NLS-1$ + } + + private static void debugActionExecute(ProvisioningAction action, Map parameters) { + DebugHelper.debug(ENGINE_SESSION, "Executing action: " + DebugHelper.formatAction(action, parameters)); //$NON-NLS-1$ + } + + private static void debugActionUndo(ProvisioningAction action, Map parameters) { + DebugHelper.debug(ENGINE_SESSION, "Undoing action: " + DebugHelper.formatAction(action, parameters)); //$NON-NLS-1$ + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/InstallableUnitPhase.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/InstallableUnitPhase.java new file mode 100644 index 000000000..8bf334353 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/InstallableUnitPhase.java @@ -0,0 +1,122 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * WindRiver - https://bugs.eclipse.org/bugs/show_bug.cgi?id=227372 + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.engine; + +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.Touchpoint; +import org.eclipse.equinox.p2.metadata.*; + +public abstract class InstallableUnitPhase extends Phase { + public static final String PARM_ARTIFACT = "artifact"; //$NON-NLS-1$ + public static final String PARM_IU = "iu"; //$NON-NLS-1$ + public static final String PARM_INSTALL_FOLDER = "installFolder"; //$NON-NLS-1$ + + protected InstallableUnitPhase(String phaseId, int weight, boolean forced) { + super(phaseId, weight, forced); + } + + protected InstallableUnitPhase(String phaseId, int weight) { + this(phaseId, weight, false); + } + + protected IStatus initializePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { + parameters.put(PARM_INSTALL_FOLDER, profile.getProperty(IProfile.PROP_INSTALL_FOLDER)); + return super.initializePhase(monitor, profile, parameters); + } + + protected IStatus initializeOperand(IProfile profile, Operand operand, Map parameters, IProgressMonitor monitor) { + InstallableUnitOperand iuOperand = (InstallableUnitOperand) operand; + MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); + mergeStatus(status, initializeOperand(profile, iuOperand, parameters, monitor)); + IInstallableUnit unit = (IInstallableUnit) parameters.get(PARM_IU); + if (unit != null) { + Touchpoint touchpoint = getActionManager().getTouchpointPoint(unit.getTouchpointType()); + if (touchpoint != null) { + parameters.put(PARM_TOUCHPOINT, touchpoint); + } + } + mergeStatus(status, super.initializeOperand(profile, operand, parameters, monitor)); + return status; + } + + protected IStatus initializeOperand(IProfile profile, InstallableUnitOperand operand, Map parameters, IProgressMonitor monitor) { + return Status.OK_STATUS; + } + + protected IStatus completeOperand(IProfile profile, Operand operand, Map parameters, IProgressMonitor monitor) { + InstallableUnitOperand iuOperand = (InstallableUnitOperand) operand; + + MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); + mergeStatus(status, super.completeOperand(profile, iuOperand, parameters, monitor)); + mergeStatus(status, completeOperand(profile, iuOperand, parameters, monitor)); + return status; + } + + protected IStatus completeOperand(IProfile profile, InstallableUnitOperand operand, Map parameters, IProgressMonitor monitor) { + return Status.OK_STATUS; + } + + final protected List getActions(Operand operand) { + if (!(operand instanceof InstallableUnitOperand)) + return null; + + InstallableUnitOperand iuOperand = (InstallableUnitOperand) operand; + return getActions(iuOperand); + } + + protected abstract List getActions(InstallableUnitOperand operand); + + final public boolean isApplicable(Operand operand) { + if (!(operand instanceof InstallableUnitOperand)) + return false; + + InstallableUnitOperand iuOperand = (InstallableUnitOperand) operand; + return isApplicable(iuOperand); + } + + protected boolean isApplicable(InstallableUnitOperand operand) { + return true; + } + + protected final List getActions(IInstallableUnit unit, String key) { + List instructions = getInstructions(unit, key); + int instrSize = instructions.size(); + if (instrSize == 0) + return null; + + List actions = new ArrayList(); + InstructionParser instructionParser = new InstructionParser(getActionManager()); + for (int i = 0; i < instrSize; i++) { + actions.addAll(instructionParser.parseActions(instructions.get(i), unit.getTouchpointType())); + } + return actions; + } + + private final static List getInstructions(IInstallableUnit unit, String key) { + List data = unit.getTouchpointData(); + int dataSize = data.size(); + if (dataSize == 0) + return CollectionUtils.emptyList(); + + ArrayList matches = new ArrayList(dataSize); + for (int i = 0; i < dataSize; i++) { + ITouchpointInstruction instructions = data.get(i).getInstruction(key); + if (instructions != null) + matches.add(instructions); + } + return matches; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/InstructionParser.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/InstructionParser.java index 19560ef9c..c84dd4719 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/InstructionParser.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/InstructionParser.java @@ -10,14 +10,12 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.engine; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.util.*; import org.eclipse.core.runtime.Assert; -import org.eclipse.equinox.internal.provisional.p2.engine.MissingAction; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.ITouchpointInstruction; -import org.eclipse.equinox.internal.provisional.p2.metadata.ITouchpointType; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; +import org.eclipse.equinox.p2.engine.MissingAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.osgi.util.NLS; public class InstructionParser { @@ -41,22 +39,21 @@ public class InstructionParser { this.actionManager = actionManager; } - public ProvisioningAction[] parseActions(ITouchpointInstruction instruction, ITouchpointType touchpointType) { - List actions = new ArrayList(); - Map importMap = parseImportAttribute(instruction.getImportAttribute()); + public List parseActions(ITouchpointInstruction instruction, ITouchpointType touchpointType) { + List actions = new ArrayList(); + Map importMap = parseImportAttribute(instruction.getImportAttribute()); StringTokenizer tokenizer = new StringTokenizer(instruction.getBody(), ";"); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) { actions.add(parseAction(tokenizer.nextToken(), importMap, touchpointType)); } - - return (ProvisioningAction[]) actions.toArray(new ProvisioningAction[actions.size()]); + return actions; } - private Map parseImportAttribute(String importAttribute) { + private Map parseImportAttribute(String importAttribute) { if (importAttribute == null) - return Collections.EMPTY_MAP; + return CollectionUtils.emptyMap(); - Map result = new HashMap(); + Map result = new HashMap(); StringTokenizer tokenizer = new StringTokenizer(importAttribute, ","); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) { StringTokenizer actionTokenizer = new StringTokenizer(tokenizer.nextToken(), ";"); //$NON-NLS-1$ @@ -75,7 +72,7 @@ public class InstructionParser { return result; } - private ProvisioningAction parseAction(String statement, Map qualifier, ITouchpointType touchpointType) { + private ProvisioningAction parseAction(String statement, Map qualifier, ITouchpointType touchpointType) { int openBracket = statement.indexOf('('); int closeBracket = statement.lastIndexOf(')'); if (openBracket == -1 || closeBracket == -1 || openBracket > closeBracket) @@ -87,10 +84,10 @@ public class InstructionParser { String nameValuePairs = statement.substring(openBracket + 1, closeBracket); if (nameValuePairs.length() == 0) - return new ParameterizedProvisioningAction(action, Collections.EMPTY_MAP, statement); + return new ParameterizedProvisioningAction(action, CollectionUtils. emptyMap(), statement); StringTokenizer tokenizer = new StringTokenizer(nameValuePairs, ","); //$NON-NLS-1$ - Map parameters = new HashMap(); + Map parameters = new HashMap(); while (tokenizer.hasMoreTokens()) { String nameValuePair = tokenizer.nextToken(); int colonIndex = nameValuePair.indexOf(":"); //$NON-NLS-1$ @@ -103,9 +100,9 @@ public class InstructionParser { return new ParameterizedProvisioningAction(action, parameters, statement); } - private ProvisioningAction lookupAction(String actionId, Map importMap, ITouchpointType touchpointType) { + private ProvisioningAction lookupAction(String actionId, Map importMap, ITouchpointType touchpointType) { VersionRange versionRange = null; - ActionEntry actionEntry = (ActionEntry) importMap.get(actionId); + ActionEntry actionEntry = importMap.get(actionId); if (actionEntry != null) { actionId = actionEntry.actionId; versionRange = actionEntry.versionRange; diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Messages.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Messages.java index 77be0e226..fbdf962fe 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Messages.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Messages.java @@ -12,46 +12,98 @@ package org.eclipse.equinox.internal.p2.engine; import org.eclipse.osgi.util.NLS; -class Messages extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.equinox.internal.p2.engine.messages"; //$NON-NLS-1$ +public class Messages extends NLS { + public static String action_not_found; + + public static String action_syntax_error; + public static String action_undo_error; public static String ActionManager_Exception_Creating_Action_Extension; public static String ActionManager_Required_Touchpoint_Not_Found; + + public static String actions_not_found; + private static final String BUNDLE_NAME = "org.eclipse.equinox.internal.p2.engine.messages"; //$NON-NLS-1$ + + public static String CertificateChecker_CertificateError; + public static String CertificateChecker_CertificateRejected; + public static String CertificateChecker_KeystoreConnectionError; + + public static String CertificateChecker_SignedContentError; + public static String CertificateChecker_SignedContentIOError; + public static String CertificateChecker_UnsignedNotAllowed; + + public static String committing; public static String download_artifact; public static String download_no_repository; - + public static String Engine_Operation_Canceled_By_User; public static String error_parsing_profile; - public static String error_persisting_profile; + public static String forced_action_execute_error; + public static String InstallableUnitEvent_type_not_install_or_uninstall; + public static String io_FailedRead; + public static String io_NotFound; + public static String not_current_operand; + public static String not_current_phase; + public static String null_action; - public static String ParameterizedProvisioningAction_action_or_parameters_null; + public static String null_operand; + public static String null_operands; + public static String null_phase; + public static String null_phases; + public static String null_phaseset; + public static String null_profile; + public static String operand_not_started; - public static String profile_does_not_exist; + public static String operand_started; + public static String ParameterizedProvisioningAction_action_or_parameters_null; + public static String phase_error; + public static String phase_not_started; + public static String phase_started; + public static String phase_undo_error; + public static String phase_undo_operand_error; + + public static String Phase_Collect_Error; + public static String Phase_Install_Error; + public static String Phase_Configure_Error; + public static String Phase_Configure_Task; + public static String Phase_Install_Task; + public static String Phase_Sizing_Error; + public static String Phase_Sizing_Warning; + public static String Phase_Unconfigure_Error; + public static String Phase_Uninstall_Error; + + public static String phaseid_not_positive; + public static String phaseid_not_set; + public static String preparing; + public static String profile_does_not_exist; + public static String Profile_Duplicate_Root_Profile_Id; + public static String profile_lock_not_reentrant; public static String profile_not_current; - public static String profile_not_registered; - - public static String Profile_Duplicate_Root_Profile_Id; public static String Profile_Null_Profile_Id; public static String Profile_Parent_Not_Found; - public static String ProfilePreferences_saving; - public static String reg_dir_not_available; + public static String rollingback_cancel; + public static String rollingback_error; + public static String session_commit_error; + public static String session_context; + public static String session_prepare_error; + public static String shared_profile_not_found; + public static String SimpleProfileRegistry_Bad_profile_location; + public static String SimpleProfileRegistry_CannotRemoveCurrentSnapshot; public static String SimpleProfileRegistry_Parser_Error_Parsing_Registry; public static String SimpleProfileRegistry_Parser_Has_Incompatible_Version; - public static String SimpleProfileRegistry_Profile_in_use; public static String SimpleProfileRegistry_Profile_not_locked; public static String SimpleProfileRegistry_Profile_not_locked_due_to_exception; - public static String SimpleProfileRegistry_Bad_profile_location; - - public static String SimpleProfileRegistry_CannotRemoveCurrentSnapshot; public static String thread_not_owner; - public static String profile_lock_not_reentrant; + public static String touchpoint_commit_error; + public static String touchpoint_prepare_error; + public static String touchpoint_rollback_error; public static String TouchpointManager_Attribute_Not_Specified; public static String TouchpointManager_Conflicting_Touchpoint_Types; @@ -59,12 +111,6 @@ class Messages extends NLS { public static String TouchpointManager_Incorrectly_Named_Extension; public static String TouchpointManager_Null_Creating_Touchpoint_Extension; public static String TouchpointManager_Null_Touchpoint_Type_Argument; - public static String shared_profile_not_found; - public static String action_syntax_error; - - public static String io_FailedRead; - - public static String io_NotFound; static { // initialize resource bundles diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ParameterizedProvisioningAction.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ParameterizedProvisioningAction.java index 3005e2290..0b73128fa 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ParameterizedProvisioningAction.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ParameterizedProvisioningAction.java @@ -13,16 +13,16 @@ package org.eclipse.equinox.internal.p2.engine; import java.util.*; import java.util.Map.Entry; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.engine.Touchpoint; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.Touchpoint; public class ParameterizedProvisioningAction extends ProvisioningAction { private ProvisioningAction action; - private Map actionParameters; + private Map actionParameters; private String actionText; - public ParameterizedProvisioningAction(ProvisioningAction action, Map actionParameters, String actionText) { + public ParameterizedProvisioningAction(ProvisioningAction action, Map actionParameters, String actionText) { if (action == null || actionParameters == null) throw new IllegalArgumentException(Messages.ParameterizedProvisioningAction_action_or_parameters_null); this.action = action; @@ -30,28 +30,27 @@ public class ParameterizedProvisioningAction extends ProvisioningAction { this.actionText = actionText; } - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { parameters = processActionParameters(parameters); return action.execute(parameters); } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { parameters = processActionParameters(parameters); return action.undo(parameters); } - private Map processActionParameters(Map parameters) { - Map result = new HashMap(parameters); - for (Iterator it = actionParameters.entrySet().iterator(); it.hasNext();) { - Entry entry = (Entry) it.next(); - String name = (String) entry.getKey(); - String value = processVariables((String) entry.getValue(), parameters); + private Map processActionParameters(Map parameters) { + Map result = new HashMap(parameters); + for (Entry entry : actionParameters.entrySet()) { + String name = entry.getKey(); + String value = processVariables(entry.getValue(), parameters); result.put(name, value); } return Collections.unmodifiableMap(result); } - private String processVariables(String parameterValue, Map parameters) { + private String processVariables(String parameterValue, Map parameters) { int variableBeginIndex = parameterValue.indexOf("${"); //$NON-NLS-1$ if (variableBeginIndex == -1) @@ -85,7 +84,7 @@ public class ParameterizedProvisioningAction extends ProvisioningAction { return action; } - public Map getParameters() { + public Map getParameters() { return actionParameters; } diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Phase.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Phase.java new file mode 100644 index 000000000..88b3cb0d5 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Phase.java @@ -0,0 +1,325 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.engine; + +import java.util.*; +import java.util.Map.Entry; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.Touchpoint; +import org.eclipse.osgi.util.NLS; + +public abstract class Phase { + protected static final String PARM_OPERAND = "operand"; //$NON-NLS-1$ + protected static final String PARM_PHASE_ID = "phaseId"; //$NON-NLS-1$ + protected static final String PARM_PROFILE = "profile"; //$NON-NLS-1$ + protected static final String PARM_PROFILE_DATA_DIRECTORY = "profileDataDirectory"; //$NON-NLS-1$ + protected static final String PARM_CONTEXT = "context"; //$NON-NLS-1$ + /** + * Internal property. + */ + protected static final String PARM_AGENT = "agent"; //$NON-NLS-1$ + protected static final String PARM_FORCED = "forced"; //$NON-NLS-1$ + protected static final String PARM_TOUCHPOINT = "touchpoint"; //$NON-NLS-1$ + + protected final String phaseId; + protected final int weight; + protected final boolean forced; + protected int prePerformWork = 1000; + protected int mainPerformWork = 10000; + protected int postPerformWork = 1000; + private Map operandParameters = null; + private Map phaseParameters = new HashMap(); + private Map> touchpointToTouchpointPhaseParameters = new HashMap>(); + private Map> touchpointToTouchpointOperandParameters = new HashMap>(); + ActionManager actionManager; // injected from phaseset + + protected Phase(String phaseId, int weight, boolean forced) { + if (phaseId == null || phaseId.length() == 0) + throw new IllegalArgumentException(Messages.phaseid_not_set); + if (weight <= 0) + throw new IllegalArgumentException(Messages.phaseid_not_positive); + this.weight = weight; + this.phaseId = phaseId; + this.forced = forced; + } + + protected Phase(String phaseId, int weight) { + this(phaseId, weight, false); + } + + final protected ActionManager getActionManager() { + return actionManager; + } + + public String toString() { + return getClass().getName() + " - " + this.weight; //$NON-NLS-1$ + } + + void perform(MultiStatus status, EngineSession session, Operand[] operands, IProgressMonitor monitor) { + SubMonitor subMonitor = SubMonitor.convert(monitor, prePerformWork + mainPerformWork + postPerformWork); + session.recordPhaseEnter(this); + prePerform(status, session, subMonitor.newChild(prePerformWork)); + if (status.matches(IStatus.ERROR | IStatus.CANCEL)) + return; + session.recordPhaseStart(this); + + subMonitor.setWorkRemaining(mainPerformWork + postPerformWork); + mainPerform(status, session, operands, subMonitor.newChild(mainPerformWork)); + if (status.matches(IStatus.ERROR | IStatus.CANCEL)) + return; + + session.recordPhaseEnd(this); + subMonitor.setWorkRemaining(postPerformWork); + postPerform(status, session, subMonitor.newChild(postPerformWork)); + phaseParameters.clear(); + if (status.matches(IStatus.ERROR | IStatus.CANCEL)) + return; + session.recordPhaseExit(this); + subMonitor.done(); + } + + void prePerform(MultiStatus status, EngineSession session, IProgressMonitor monitor) { + IProfile profile = session.getProfile(); + phaseParameters.put(PARM_PROFILE, profile); + phaseParameters.put(PARM_PROFILE_DATA_DIRECTORY, session.getProfileDataDirectory()); + phaseParameters.put(PARM_CONTEXT, session.getProvisioningContext()); + phaseParameters.put(PARM_PHASE_ID, phaseId); + phaseParameters.put(PARM_FORCED, Boolean.toString(forced)); + phaseParameters.put(PARM_AGENT, session.getAgent()); + mergeStatus(status, initializePhase(monitor, profile, phaseParameters)); + } + + private void mainPerform(MultiStatus status, EngineSession session, Operand[] operands, SubMonitor subMonitor) { + IProfile profile = session.getProfile(); + subMonitor.beginTask("", operands.length); //$NON-NLS-1$ + for (int i = 0; i < operands.length; i++) { + subMonitor.setWorkRemaining(operands.length - i); + if (subMonitor.isCanceled()) + throw new OperationCanceledException(); + Operand operand = operands[i]; + if (!isApplicable(operand)) + continue; + + session.recordOperandStart(operand); + List actions = getActions(operand); + operandParameters = new HashMap(phaseParameters); + operandParameters.put(PARM_OPERAND, operand); + mergeStatus(status, initializeOperand(profile, operand, operandParameters, subMonitor)); + if (status.matches(IStatus.ERROR | IStatus.CANCEL)) { + operandParameters = null; + return; + } + + Touchpoint operandTouchpoint = (Touchpoint) operandParameters.get(PARM_TOUCHPOINT); + if (operandTouchpoint != null) { + mergeStatus(status, initializeTouchpointParameters(profile, operand, operandTouchpoint, subMonitor)); + if (status.matches(IStatus.ERROR | IStatus.CANCEL)) + return; + + operandParameters = touchpointToTouchpointOperandParameters.get(operandTouchpoint); + } + + operandParameters = Collections.unmodifiableMap(operandParameters); + if (actions != null) { + for (int j = 0; j < actions.size(); j++) { + ProvisioningAction action = actions.get(j); + Map parameters = operandParameters; + Touchpoint touchpoint = action.getTouchpoint(); + if (touchpoint != null) { + mergeStatus(status, initializeTouchpointParameters(profile, operand, touchpoint, subMonitor)); + if (status.matches(IStatus.ERROR | IStatus.CANCEL)) + return; + + parameters = touchpointToTouchpointOperandParameters.get(touchpoint); + } + IStatus actionStatus = null; + try { + session.recordActionExecute(action, parameters); + actionStatus = action.execute(parameters); + } catch (RuntimeException e) { + if (!forced) + throw e; + // "action.execute" calls user code and might throw an unchecked exception + // we catch the error here to gather information on where the problem occurred. + actionStatus = new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.forced_action_execute_error, action.getClass().getName()), e); + } catch (LinkageError e) { + if (!forced) + throw e; + // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) + actionStatus = new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.forced_action_execute_error, action.getClass().getName()), e); + } + if (forced && actionStatus != null && actionStatus.matches(IStatus.ERROR)) { + MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.ERROR, getProblemMessage(), null); + result.add(new Status(IStatus.ERROR, EngineActivator.ID, session.getContextString(this, operand, action), null)); + LogHelper.log(result); + actionStatus = Status.OK_STATUS; + } + mergeStatus(status, actionStatus); + if (status.matches(IStatus.ERROR | IStatus.CANCEL)) + return; + } + } + mergeStatus(status, touchpointCompleteOperand(profile, operand, operandParameters, subMonitor)); + mergeStatus(status, completeOperand(profile, operand, operandParameters, subMonitor)); + if (status.matches(IStatus.ERROR | IStatus.CANCEL)) + return; + operandParameters = null; + session.recordOperandEnd(operand); + subMonitor.worked(1); + } + } + + private IStatus initializeTouchpointParameters(IProfile profile, Operand operand, Touchpoint touchpoint, IProgressMonitor monitor) { + if (touchpointToTouchpointOperandParameters.containsKey(touchpoint)) + return Status.OK_STATUS; + + Map touchpointPhaseParameters = touchpointToTouchpointPhaseParameters.get(touchpoint); + if (touchpointPhaseParameters == null) { + touchpointPhaseParameters = new HashMap(phaseParameters); + IStatus status = touchpoint.initializePhase(monitor, profile, phaseId, touchpointPhaseParameters); + if (status != null && status.matches(IStatus.ERROR | IStatus.CANCEL)) + return status; + touchpointToTouchpointPhaseParameters.put(touchpoint, touchpointPhaseParameters); + } + + Map touchpointOperandParameters = new HashMap(touchpointPhaseParameters); + touchpointOperandParameters.putAll(operandParameters); + IStatus status = touchpoint.initializeOperand(profile, operand, touchpointOperandParameters); + if (status != null && status.matches(IStatus.ERROR | IStatus.CANCEL)) + return status; + touchpointToTouchpointOperandParameters.put(touchpoint, touchpointOperandParameters); + return Status.OK_STATUS; + } + + /** + * Merges a given IStatus into a MultiStatus + */ + protected static void mergeStatus(MultiStatus multi, IStatus status) { + if (status != null && !status.isOK()) + multi.merge(status); + } + + void postPerform(MultiStatus status, EngineSession session, IProgressMonitor monitor) { + IProfile profile = session.getProfile(); + mergeStatus(status, touchpointCompletePhase(monitor, profile, phaseParameters)); + mergeStatus(status, completePhase(monitor, profile, phaseParameters)); + } + + void undo(MultiStatus status, EngineSession session, IProfile profile, Operand operand, ProvisioningAction[] actions, ProvisioningContext context) { + if (operandParameters == null) { + operandParameters = new HashMap(phaseParameters); + operandParameters.put(PARM_OPERAND, operand); + mergeStatus(status, initializeOperand(profile, operand, operandParameters, new NullProgressMonitor())); + Touchpoint operandTouchpoint = (Touchpoint) operandParameters.get(PARM_TOUCHPOINT); + if (operandTouchpoint != null) { + mergeStatus(status, initializeTouchpointParameters(profile, operand, operandTouchpoint, new NullProgressMonitor())); + if (status.matches(IStatus.ERROR | IStatus.CANCEL)) + return; + + operandParameters = touchpointToTouchpointOperandParameters.get(operandTouchpoint); + } + operandParameters = Collections.unmodifiableMap(operandParameters); + } + for (int j = 0; j < actions.length; j++) { + ProvisioningAction action = actions[j]; + Map parameters = operandParameters; + Touchpoint touchpoint = action.getTouchpoint(); + if (touchpoint != null) { + mergeStatus(status, initializeTouchpointParameters(profile, operand, touchpoint, new NullProgressMonitor())); + if (status.matches(IStatus.ERROR)) + return; + + parameters = touchpointToTouchpointOperandParameters.get(touchpoint); + } + IStatus actionStatus = null; + try { + session.recordActionUndo(action, parameters); + actionStatus = action.undo(parameters); + } catch (RuntimeException e) { + // "action.undo" calls user code and might throw an unchecked exception + // we catch the error here to gather information on where the problem occurred. + actionStatus = new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.action_undo_error, action.getClass().getName()), e); + } catch (LinkageError e) { + // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) + actionStatus = new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.action_undo_error, action.getClass().getName()), e); + } + if (actionStatus != null && actionStatus.matches(IStatus.ERROR)) { + MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.ERROR, getProblemMessage(), null); + result.add(new Status(IStatus.ERROR, EngineActivator.ID, session.getContextString(this, operand, action), null)); + result.merge(actionStatus); + } + } + mergeStatus(status, touchpointCompleteOperand(profile, operand, operandParameters, new NullProgressMonitor())); + mergeStatus(status, completeOperand(profile, operand, operandParameters, new NullProgressMonitor())); + operandParameters = null; + } + + public boolean isApplicable(Operand operand) { + return true; + } + + protected IStatus initializePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { + return Status.OK_STATUS; + } + + protected IStatus completePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { + return Status.OK_STATUS; + } + + IStatus touchpointCompletePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { + if (touchpointToTouchpointPhaseParameters.isEmpty()) + return Status.OK_STATUS; + + MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); + for (Entry> entry : touchpointToTouchpointPhaseParameters.entrySet()) { + Touchpoint touchpoint = entry.getKey(); + Map touchpointParameters = entry.getValue(); + mergeStatus(status, touchpoint.completePhase(monitor, profile, phaseId, touchpointParameters)); + } + touchpointToTouchpointPhaseParameters.clear(); + return status; + } + + protected IStatus completeOperand(IProfile profile, Operand operand, Map parameters, IProgressMonitor monitor) { + return Status.OK_STATUS; + } + + IStatus touchpointCompleteOperand(IProfile profile, Operand operand, Map parameters, IProgressMonitor monitor) { + if (touchpointToTouchpointOperandParameters.isEmpty()) + return Status.OK_STATUS; + + MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); + for (Entry> entry : touchpointToTouchpointOperandParameters.entrySet()) { + Touchpoint touchpoint = entry.getKey(); + Map touchpointParameters = entry.getValue(); + mergeStatus(status, touchpoint.completeOperand(profile, operand, touchpointParameters)); + } + touchpointToTouchpointOperandParameters.clear(); + return status; + } + + protected IStatus initializeOperand(IProfile profile, Operand operand, Map parameters, IProgressMonitor monitor) { + return Status.OK_STATUS; + } + + protected abstract List getActions(Operand operand); + + /** + * Returns a human-readable message to be displayed in case of an error performing + * this phase. Subclasses should override. + */ + protected String getProblemMessage() { + return NLS.bind(Messages.phase_error, getClass().getName()); + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/PhaseSet.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/PhaseSet.java new file mode 100644 index 000000000..e215cc820 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/PhaseSet.java @@ -0,0 +1,196 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.engine; + +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.engine.phases.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.osgi.util.NLS; + +public class PhaseSet implements IPhaseSet { + + public static final List DEFAULT_PHASES = Arrays.asList(new String[] {IPhaseSet.PHASE_COLLECT, IPhaseSet.PHASE_UNCONFIGURE, IPhaseSet.PHASE_UNINSTALL, IPhaseSet.PHASE_PROPERTY, IPhaseSet.PHASE_CHECK_TRUST, IPhaseSet.PHASE_INSTALL, IPhaseSet.PHASE_CONFIGURE}); + + public static final boolean forcedUninstall = Boolean.valueOf(EngineActivator.getContext().getProperty("org.eclipse.equinox.p2.engine.forcedUninstall")).booleanValue(); //$NON-NLS-1$ + + private final Phase[] phases; + + public static IPhaseSet createPhaseSetExcluding(String[] excludes) { + ArrayList phases = new ArrayList(DEFAULT_PHASES); + if (excludes != null) { + for (int i = 0; i < excludes.length; i++) { + phases.remove(excludes[i]); + } + } + return createPhaseSetIncluding(phases.toArray(new String[phases.size()])); + } + + public static IPhaseSet createPhaseSetIncluding(String[] includes) { + ArrayList phases = new ArrayList(); + for (int i = 0; i < includes.length; i++) { + String current = includes[i]; + if (current.equals(IPhaseSet.PHASE_CONFIGURE)) + phases.add(new Configure(10)); + else if (current.equals(IPhaseSet.PHASE_CHECK_TRUST)) + phases.add(new CheckTrust(10)); + else if (current.equals(IPhaseSet.PHASE_COLLECT)) + phases.add(new Collect(100)); + else if (current.equals(IPhaseSet.PHASE_INSTALL)) + phases.add(new Install(50)); + else if (current.equals(IPhaseSet.PHASE_PROPERTY)) + phases.add(new Property(1)); + else if (current.equals(IPhaseSet.PHASE_UNCONFIGURE)) + phases.add(new Unconfigure(10, forcedUninstall)); + else if (current.equals(IPhaseSet.PHASE_UNINSTALL)) + phases.add(new Uninstall(50, forcedUninstall)); + } + return new PhaseSet(phases.toArray(new Phase[phases.size()])); + } + + public PhaseSet(Phase[] phases) { + if (phases == null) + throw new IllegalArgumentException(Messages.null_phases); + + this.phases = phases; + } + + public final MultiStatus perform(EngineSession session, Operand[] operands, IProgressMonitor monitor) { + MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); + int[] weights = getProgressWeights(operands); + int totalWork = getTotalWork(weights); + SubMonitor pm = SubMonitor.convert(monitor, totalWork); + try { + for (int i = 0; i < phases.length; i++) { + if (pm.isCanceled()) { + status.add(Status.CANCEL_STATUS); + return status; + } + Phase phase = phases[i]; + phase.actionManager = (ActionManager) session.getAgent().getService(ActionManager.SERVICE_NAME); + try { + phase.perform(status, session, operands, pm.newChild(weights[i])); + } catch (OperationCanceledException e) { + // propagate operation cancellation + status.add(new Status(IStatus.CANCEL, EngineActivator.ID, e.getMessage(), e)); + } catch (RuntimeException e) { + // "perform" calls user code and might throw an unchecked exception + // we catch the error here to gather information on where the problem occurred. + status.add(new Status(IStatus.ERROR, EngineActivator.ID, e.getMessage(), e)); + } catch (LinkageError e) { + // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) + status.add(new Status(IStatus.ERROR, EngineActivator.ID, e.getMessage(), e)); + } finally { + phase.actionManager = null; + } + if (status.matches(IStatus.CANCEL)) { + MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.CANCEL, Messages.Engine_Operation_Canceled_By_User, null); + result.merge(status); + return result; + } else if (status.matches(IStatus.ERROR)) { + MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.ERROR, phase.getProblemMessage(), null); + result.add(new Status(IStatus.ERROR, EngineActivator.ID, session.getContextString(), null)); + result.merge(status); + return result; + } + } + } finally { + pm.done(); + } + return status; + } + + public final IStatus validate(ActionManager actionManager, IProfile profile, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) { + Set missingActions = new HashSet(); + for (int i = 0; i < phases.length; i++) { + Phase phase = phases[i]; + phase.actionManager = actionManager; + try { + for (int j = 0; j < operands.length; j++) { + Operand operand = operands[j]; + try { + if (!phase.isApplicable(operand)) + continue; + + List actions = phase.getActions(operand); + if (actions == null) + continue; + for (int k = 0; k < actions.size(); k++) { + ProvisioningAction action = actions.get(k); + if (action instanceof MissingAction) + missingActions.add((MissingAction) action); + } + } catch (RuntimeException e) { + // "perform" calls user code and might throw an unchecked exception + // we catch the error here to gather information on where the problem occurred. + return new Status(IStatus.ERROR, EngineActivator.ID, e.getMessage() + " " + getContextString(profile, phase, operand), e); //$NON-NLS-1$ + } catch (LinkageError e) { + // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) + return new Status(IStatus.ERROR, EngineActivator.ID, e.getMessage() + " " + getContextString(profile, phase, operand), e); //$NON-NLS-1$ + } + } + } finally { + phase.actionManager = null; + } + } + if (!missingActions.isEmpty()) { + MissingAction[] missingActionsArray = missingActions.toArray(new MissingAction[missingActions.size()]); + MissingActionsException exception = new MissingActionsException(missingActionsArray); + return (new Status(IStatus.ERROR, EngineActivator.ID, exception.getMessage(), exception)); + } + return Status.OK_STATUS; + } + + private String getContextString(IProfile profile, Phase phase, Operand operand) { + return NLS.bind(Messages.session_context, new Object[] {profile.getProfileId(), phase.getClass().getName(), operand.toString(), ""}); //$NON-NLS-1$ + } + + private int getTotalWork(int[] weights) { + int sum = 0; + for (int i = 0; i < weights.length; i++) + sum += weights[i]; + return sum; + } + + private int[] getProgressWeights(Operand[] operands) { + int[] weights = new int[phases.length]; + for (int i = 0; i < phases.length; i += 1) { + if (operands.length > 0) + //alter weights according to the number of operands applicable to that phase + weights[i] = (phases[i].weight * countApplicable(phases[i], operands) / operands.length); + else + weights[i] = phases[i].weight; + } + return weights; + } + + private int countApplicable(Phase phase, Operand[] operands) { + int count = 0; + for (int i = 0; i < operands.length; i++) { + if (phase.isApplicable(operands[i])) + count++; + } + return count; + } + + public String[] getPhaseIds() { + String[] ids = new String[phases.length]; + for (int i = 0; i < ids.length; i++) { + ids[i] = phases[i].phaseId; + } + return ids; + } + + public Phase[] getPhases() { + return phases; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Profile.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Profile.java index 46261ff7a..6e08b69c0 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Profile.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/Profile.java @@ -11,13 +11,17 @@ package org.eclipse.equinox.internal.p2.engine; import java.util.*; import java.util.Map.Entry; import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.ISurrogateProfileHandler; +import org.eclipse.equinox.p2.engine.query.IUProfilePropertyQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.*; import org.eclipse.osgi.util.NLS; -public class Profile implements IQueryable, IProfile { +public class Profile implements IProfile { //Internal id of the profile private final String profileId; @@ -27,22 +31,21 @@ public class Profile implements IQueryable, IProfile { /** * A collection of child profiles. */ - private List subProfileIds; // child profile ids + private List subProfileIds; // child profile ids - private static final String[] noSubProfiles = new String[0]; /** * This storage is to be used by the touchpoints to store data. */ private OrderedProperties storage = new OrderedProperties(); - private Set ius = new HashSet(); - private Map iuProperties = new HashMap(); + private Set ius = new HashSet(); + private Map iuProperties = new HashMap(); private boolean changed = false; private long timestamp; private ISurrogateProfileHandler surrogateProfileHandler; - public Profile(String profileId, Profile parent, Map properties) { + public Profile(String profileId, Profile parent, Map properties) { if (profileId == null || profileId.length() == 0) { throw new IllegalArgumentException(NLS.bind(Messages.Profile_Null_Profile_Id, null)); } @@ -91,7 +94,7 @@ public class Profile implements IQueryable, IProfile { public void addSubProfile(String subProfileId) throws IllegalArgumentException { if (subProfileIds == null) - subProfileIds = new ArrayList(); + subProfileIds = new ArrayList(); if (!subProfileIds.contains(subProfileId)) subProfileIds.add(subProfileId); @@ -115,11 +118,10 @@ public class Profile implements IQueryable, IProfile { /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.engine.IProfile#getSubProfileIds() */ - public String[] getSubProfileIds() { + public List getSubProfileIds() { if (subProfileIds == null) - return noSubProfiles; - - return (String[]) subProfileIds.toArray(new String[subProfileIds.size()]); + return CollectionUtils.emptyList(); + return Collections.unmodifiableList(subProfileIds); } /* (non-Javadoc) @@ -157,25 +159,39 @@ public class Profile implements IQueryable, IProfile { /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.engine.IProfile#query(org.eclipse.equinox.internal.provisional.p2.query.Query, org.eclipse.equinox.internal.provisional.p2.query.Collector, org.eclipse.core.runtime.IProgressMonitor) */ - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + propagateProfileContext(query); + if (query instanceof IUProfilePropertyQuery) { + return query.perform(iuProperties.keySet().iterator()); + } + return query.perform(ius.iterator()); + } + + private void propagateProfileContext(IQuery query) { + // FIXME if (query instanceof IUProfilePropertyQuery) { ((IUProfilePropertyQuery) query).setProfile(this); - return query.perform(iuProperties.keySet().iterator(), collector); + return; + } + if (query instanceof ICompositeQuery) { + List> queries = ((ICompositeQuery) query).getQueries(); + for (int i = 0; i < queries.size(); i++) { + propagateProfileContext(queries.get(i)); + } } - return query.perform(ius.iterator(), collector); } - public Collector available(Query query, Collector collector, IProgressMonitor monitor) { + public IQueryResult available(IQuery query, IProgressMonitor monitor) { if (surrogateProfileHandler != null) - return surrogateProfileHandler.queryProfile(this, query, collector, monitor); - return query(query, collector, monitor); + return surrogateProfileHandler.queryProfile(this, query, monitor); + return query(query, new NullProgressMonitor()); } /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.engine.IProfile#getInstallableUnitProperty(org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit, java.lang.String) */ public String getInstallableUnitProperty(IInstallableUnit iu, String key) { - OrderedProperties properties = (OrderedProperties) iuProperties.get(iu); + OrderedProperties properties = iuProperties.get(iu); if (properties == null) return null; @@ -184,7 +200,7 @@ public class Profile implements IQueryable, IProfile { public String setInstallableUnitProperty(IInstallableUnit iu, String key, String value) { // String iuKey = createIUKey(iu); - OrderedProperties properties = (OrderedProperties) iuProperties.get(iu); + OrderedProperties properties = iuProperties.get(iu); if (properties == null) { properties = new OrderedProperties(); iuProperties.put(iu, properties); @@ -196,11 +212,11 @@ public class Profile implements IQueryable, IProfile { public String removeInstallableUnitProperty(IInstallableUnit iu, String key) { // String iuKey = createIUKey(iu); - OrderedProperties properties = (OrderedProperties) iuProperties.get(iu); + OrderedProperties properties = iuProperties.get(iu); if (properties == null) return null; - String oldValue = (String) properties.remove(key); + String oldValue = properties.remove(key); if (properties.isEmpty()) iuProperties.remove(iu); @@ -215,18 +231,18 @@ public class Profile implements IQueryable, IProfile { /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.engine.IProfile#getLocalProperties() */ - public Map getLocalProperties() { + public Map getLocalProperties() { return OrderedProperties.unmodifiableProperties(storage); } /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.engine.IProfile#getProperties() */ - public Map getProperties() { + public Map getProperties() { if (parentProfile == null) return getLocalProperties(); - Map properties = new HashMap(parentProfile.getProperties()); + Map properties = new HashMap(parentProfile.getProperties()); properties.putAll(storage); return OrderedProperties.unmodifiableProperties(properties); } @@ -235,7 +251,7 @@ public class Profile implements IQueryable, IProfile { * Add all the properties in the map to the local properties * of the profile. */ - public void addProperties(Map properties) { + public void addProperties(Map properties) { storage.putAll(properties); changed = true; } @@ -258,8 +274,8 @@ public class Profile implements IQueryable, IProfile { /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.engine.IProfile#getInstallableUnitProperties(org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit) */ - public Map getInstallableUnitProperties(IInstallableUnit iu) { - OrderedProperties properties = (OrderedProperties) iuProperties.get(iu); + public Map getInstallableUnitProperties(IInstallableUnit iu) { + OrderedProperties properties = iuProperties.get(iu); if (properties == null) properties = new OrderedProperties(); @@ -296,16 +312,14 @@ public class Profile implements IQueryable, IProfile { snapshot.setTimestamp(timestamp); if (subProfileIds != null) { - for (Iterator it = subProfileIds.iterator(); it.hasNext();) { - String subProfileId = (String) it.next(); + for (String subProfileId : subProfileIds) { snapshot.addSubProfile(subProfileId); } } - for (Iterator it = ius.iterator(); it.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) it.next(); + for (IInstallableUnit iu : ius) { snapshot.addInstallableUnit(iu); - Map properties = getInstallableUnitProperties(iu); + Map properties = getInstallableUnitProperties(iu); if (properties != null) snapshot.addInstallableUnitProperties(iu, properties); } @@ -313,12 +327,9 @@ public class Profile implements IQueryable, IProfile { return snapshot; } - public void addInstallableUnitProperties(IInstallableUnit iu, Map properties) { - for (Iterator it = properties.entrySet().iterator(); it.hasNext();) { - Entry entry = (Entry) it.next(); - String key = (String) entry.getKey(); - String value = (String) entry.getValue(); - setInstallableUnitProperty(iu, key, value); + public void addInstallableUnitProperties(IInstallableUnit iu, Map properties) { + for (Entry entry : properties.entrySet()) { + setInstallableUnitProperty(iu, entry.getKey(), entry.getValue()); } } @@ -328,17 +339,16 @@ public class Profile implements IQueryable, IProfile { } public void clearOrphanedInstallableUnitProperties() { - Set keys = iuProperties.keySet(); + Set keys = iuProperties.keySet(); // Set orphans = new HashSet(); - Collection toRemove = new ArrayList(); - for (Iterator iterator = keys.iterator(); iterator.hasNext();) { - Object iu = iterator.next(); + Collection toRemove = new ArrayList(); + for (IInstallableUnit iu : keys) { if (!ius.contains(iu)) toRemove.add(iu); } - for (Iterator iterator = toRemove.iterator(); iterator.hasNext();) { - iuProperties.remove(iterator.next()); + for (IInstallableUnit iu : toRemove) { + iuProperties.remove(iu); } // List iuKeys = new ArrayList(); // for (Iterator it = ius.iterator(); it.hasNext();) @@ -358,4 +368,11 @@ public class Profile implements IQueryable, IProfile { public void setSurrogateProfileHandler(ISurrogateProfileHandler surrogateProfileHandler) { this.surrogateProfileHandler = surrogateProfileHandler; } + + /** + * Prints a string representation for debugging purposes only. + */ + public String toString() { + return "Profile(" + getProfileId() + ')'; //$NON-NLS-1$ + } } diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileMetadataRepository.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileMetadataRepository.java index 20224db15..02e396f0b 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileMetadataRepository.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileMetadataRepository.java @@ -18,14 +18,15 @@ import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.metadata.repository.Activator; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.AbstractMetadataRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.spi.AbstractMetadataRepository; import org.eclipse.osgi.util.NLS; public class ProfileMetadataRepository extends AbstractMetadataRepository { @@ -50,19 +51,18 @@ public class ProfileMetadataRepository extends AbstractMetadataRepository { } private void publishArtifactRepos() { - List artifactRepos = findArtifactRepos(); + List artifactRepos = findArtifactRepos(); IProvisioningEventBus bus = (IProvisioningEventBus) ServiceHelper.getService(EngineActivator.getContext(), IProvisioningEventBus.SERVICE_NAME); if (bus == null) return; - for (Iterator it = artifactRepos.iterator(); it.hasNext();) { - URI repo = (URI) it.next(); + for (URI repo : artifactRepos) { bus.publishEvent(new RepositoryEvent(repo, IRepository.TYPE_ARTIFACT, RepositoryEvent.DISCOVERED, true)); } } - private List findArtifactRepos() { - List artifactRepos = new ArrayList(); + private List findArtifactRepos() { + List artifactRepos = new ArrayList(); File p2Directory = findP2Directory(); // Add the profile registry's default agent artifact repository. @@ -155,8 +155,8 @@ public class ProfileMetadataRepository extends AbstractMetadataRepository { // nothing to do } - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - return profile.query(query, collector, monitor); + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return profile.query(query, monitor); } public static void validate(URI location, IProgressMonitor monitor) throws ProvisionException { diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileMetadataRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileMetadataRepositoryFactory.java index 0b92907f3..1eba1a3d6 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileMetadataRepositoryFactory.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileMetadataRepositoryFactory.java @@ -13,10 +13,10 @@ package org.eclipse.equinox.internal.p2.engine; import java.net.URI; import java.util.Map; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory; public class ProfileMetadataRepositoryFactory extends MetadataRepositoryFactory { @@ -24,7 +24,7 @@ public class ProfileMetadataRepositoryFactory extends MetadataRepositoryFactory * @throws ProvisionException * documenting to avoid warning */ - public IMetadataRepository create(URI location, String name, String type, Map properties) throws ProvisionException { + public IMetadataRepository create(URI location, String name, String type, Map properties) throws ProvisionException { return null; } diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileParser.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileParser.java index d62dae1c2..0a6becaf6 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileParser.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileParser.java @@ -10,12 +10,11 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.engine; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; - import java.util.LinkedHashMap; import java.util.Map; import org.eclipse.equinox.internal.p2.metadata.repository.io.MetadataParser; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.Version; import org.osgi.framework.BundleContext; import org.xml.sax.Attributes; @@ -97,7 +96,7 @@ public abstract class ProfileParser extends MetadataParser implements ProfileXML return 0; } - public Map getProperties() { + public Map getProperties() { if (propertiesHandler == null) return null; return propertiesHandler.getProperties(); @@ -109,16 +108,16 @@ public abstract class ProfileParser extends MetadataParser implements ProfileXML return unitsHandler.getUnits(); } - public Map getIUProperties(IInstallableUnit iu) { + public Map getIUProperties(IInstallableUnit iu) { if (iusPropertiesHandler == null) return null; - Map iusPropertiesMap = iusPropertiesHandler.getIUsPropertiesMap(); + Map> iusPropertiesMap = iusPropertiesHandler.getIUsPropertiesMap(); if (iusPropertiesMap == null) return null; String iuIdentity = iu.getId() + "_" + iu.getVersion().toString(); //$NON-NLS-1$ - return (Map) iusPropertiesMap.get(iuIdentity); + return iusPropertiesMap.get(iuIdentity); } } @@ -127,10 +126,10 @@ public abstract class ProfileParser extends MetadataParser implements ProfileXML private final String[] required = new String[] {ID_ATTRIBUTE, VERSION_ATTRIBUTE}; private String iuIdentity; - private Map iusPropertiesMap; + private Map> iusPropertiesMap; private PropertiesHandler propertiesHandler; - public IUPropertiesHandler(AbstractHandler parentHandler, Attributes attributes, Map iusPropertiesMap) { + public IUPropertiesHandler(AbstractHandler parentHandler, Attributes attributes, Map> iusPropertiesMap) { super(parentHandler, IU_PROPERTIES_ELEMENT); this.iusPropertiesMap = iusPropertiesMap; @@ -157,15 +156,16 @@ public abstract class ProfileParser extends MetadataParser implements ProfileXML protected class IUsPropertiesHandler extends AbstractHandler { - private Map iusPropertiesMap; + private Map> iusPropertiesMap; public IUsPropertiesHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, IUS_PROPERTIES_ELEMENT); - String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - iusPropertiesMap = (size != null ? new LinkedHashMap(new Integer(size).intValue()) : new LinkedHashMap(4)); + String sizeStr = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); + int size = (sizeStr != null ? new Integer(sizeStr).intValue() : 4); + iusPropertiesMap = new LinkedHashMap>(size); } - public Map getIUsPropertiesMap() { + public Map> getIUsPropertiesMap() { return iusPropertiesMap; } diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfilePreferences.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfilePreferences.java index 8c84e4031..362f9f289 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfilePreferences.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfilePreferences.java @@ -17,10 +17,11 @@ import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.equinox.internal.p2.core.helpers.*; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.security.storage.EncodingUtils; +import org.osgi.framework.*; import org.osgi.service.prefs.BackingStoreException; /** @@ -50,7 +51,7 @@ public class ProfilePreferences extends EclipsePreferences { } // cache which nodes have been loaded from disk - private static Set loadedNodes = Collections.synchronizedSet(new HashSet()); + private static Set loadedNodes = Collections.synchronizedSet(new HashSet()); public static final Object PROFILE_SAVE_JOB_FAMILY = new Object(); @@ -69,25 +70,26 @@ public class ProfilePreferences extends EclipsePreferences { public ProfilePreferences(EclipsePreferences nodeParent, String nodeName) { super(nodeParent, nodeName); + //path is /profile/{agent location}/{profile id}/qualifier // cache the segment count String path = absolutePath(); segmentCount = getSegmentCount(path); - if (segmentCount <= 1) + if (segmentCount <= 2) return; - if (segmentCount == 2) + if (segmentCount == 3) profileLock = new Object(); - if (segmentCount < 3) + if (segmentCount < 4) return; // cache the qualifier - qualifier = getSegment(path, 2); + qualifier = getSegment(path, 3); } - private boolean containsProfile(String profileId) { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(EngineActivator.getContext(), IProfileRegistry.class.getName()); + private boolean containsProfile(IProvisioningAgent agent, String profileId) { + IProfileRegistry profileRegistry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME); if (profileId == null || profileRegistry == null) return false; return profileRegistry.containsProfile(profileId); @@ -99,22 +101,68 @@ public class ProfilePreferences extends EclipsePreferences { */ protected void doSave() throws BackingStoreException { synchronized (((ProfilePreferences) parent).profileLock) { - String profileId = getSegment(absolutePath(), 1); - if (!containsProfile(profileId)) { - //use the default location for the self profile, otherwise just do nothing and return - if (IProfileRegistry.SELF.equals(profileId)) { - IPath location = getDefaultLocation(); - if (location != null) { - super.save(location); - return; + ServiceReference agentRef = getAgent(getSegment(absolutePath(), 1)); + IProvisioningAgent agent = (IProvisioningAgent) EngineActivator.getContext().getService(agentRef); + try { + String profileId = getSegment(absolutePath(), 2); + if (!containsProfile(agent, profileId)) { + //use the default location for the self profile, otherwise just do nothing and return + if (IProfileRegistry.SELF.equals(profileId)) { + IPath location = getDefaultLocation(); + if (location != null) { + super.save(location); + return; + } } + if (Tracing.DEBUG_PROFILE_PREFERENCES) + Tracing.debug("Not saving preferences since there is no file for node: " + absolutePath()); //$NON-NLS-1$ + return; } - if (Tracing.DEBUG_PROFILE_PREFERENCES) - Tracing.debug("Not saving preferences since there is no file for node: " + absolutePath()); //$NON-NLS-1$ - return; + super.save(getProfileLocation(agent, profileId)); + } finally { + EngineActivator.getContext().ungetService(agentRef); + } + } + } + + /** + * Returns a reference to the agent service corresponding to the given encoded + * agent location. Never returns null; throws an exception if the agent could not be found. + */ + private ServiceReference getAgent(String segment) throws BackingStoreException { + String locationString = EncodingUtils.decodeSlashes(segment); + Exception failure = null; + try { + String filter = "(locationURI=" + encodeForFilter(locationString) + ')'; //$NON-NLS-1$ + ServiceReference[] refs = EngineActivator.getContext().getServiceReferences(IProvisioningAgent.SERVICE_NAME, filter); + if (refs != null && refs.length > 0) + return refs[0]; + } catch (InvalidSyntaxException e) { + failure = e; + } + throw new BackingStoreException("Unable to determine provisioning agent from location: " + segment, failure); //$NON-NLS-1$ + } + + /** + * Encodes a string so that it is suitable for use as a value for a filter property. + * Any reserved filter characters are escaped. + */ + private String encodeForFilter(String string) { + StringBuffer result = new StringBuffer(string.length()); + char[] input = string.toCharArray(); + for (int i = 0; i < input.length; i++) { + switch (input[i]) { + case '(' : + case ')' : + case '*' : + case '\\' : + result.append('\\'); + //fall through + default : + result.append(input[i]); } - super.save(getProfileLocation(profileId)); } + return result.toString(); } /** @@ -122,12 +170,12 @@ public class ProfilePreferences extends EclipsePreferences { */ private IPath getDefaultLocation() { //use engine agent location for preferences if there is no self profile - AgentLocation location = (AgentLocation) ServiceHelper.getService(EngineActivator.getContext(), AgentLocation.SERVICE_NAME); + IAgentLocation location = (IAgentLocation) ServiceHelper.getService(EngineActivator.getContext(), IAgentLocation.SERVICE_NAME); if (location == null) { LogHelper.log(new Status(IStatus.WARNING, EngineActivator.ID, "Agent location service not available", new RuntimeException())); //$NON-NLS-1$ return null; } - IPath dataArea = new Path(URLUtil.toFile(location.getDataArea(EngineActivator.ID)).getAbsolutePath()); + IPath dataArea = new Path(URIUtil.toFile(location.getDataArea(EngineActivator.ID)).getAbsolutePath()); return computeLocation(dataArea, qualifier); } @@ -139,7 +187,7 @@ public class ProfilePreferences extends EclipsePreferences { // Walk backwards up the tree starting at this node. // This is important to avoid a chicken/egg thing on startup. IEclipsePreferences node = this; - for (int i = 3; i < segmentCount; i++) + for (int i = 4; i < segmentCount; i++) node = (EclipsePreferences) node.parent(); loadLevel = node; } @@ -149,8 +197,8 @@ public class ProfilePreferences extends EclipsePreferences { /** * Returns the location of the preference file for the given profile. */ - private IPath getProfileLocation(String profileId) { - SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(EngineActivator.getContext(), IProfileRegistry.class.getName()); + private IPath getProfileLocation(IProvisioningAgent agent, String profileId) { + SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME); File profileDataDirectory = profileRegistry.getProfileDataDirectory(profileId); return computeLocation(new Path(profileDataDirectory.getAbsolutePath()), qualifier); } @@ -173,21 +221,27 @@ public class ProfilePreferences extends EclipsePreferences { */ protected void load() throws BackingStoreException { synchronized (((ProfilePreferences) parent).profileLock) { - String profileId = getSegment(absolutePath(), 1); - if (!containsProfile(profileId)) { - //use the default location for the self profile, otherwise just do nothing and return - if (IProfileRegistry.SELF.equals(profileId)) { - IPath location = getDefaultLocation(); - if (location != null) { - load(location); - return; + ServiceReference agentRef = getAgent(getSegment(absolutePath(), 1)); + IProvisioningAgent agent = (IProvisioningAgent) EngineActivator.getContext().getService(agentRef); + try { + String profileId = getSegment(absolutePath(), 2); + if (!containsProfile(agent, profileId)) { + //use the default location for the self profile, otherwise just do nothing and return + if (IProfileRegistry.SELF.equals(profileId)) { + IPath location = getDefaultLocation(); + if (location != null) { + load(location); + return; + } } + if (Tracing.DEBUG_PROFILE_PREFERENCES) + Tracing.debug("Not loading preferences since there is no file for node: " + absolutePath()); //$NON-NLS-1$ + return; } - if (Tracing.DEBUG_PROFILE_PREFERENCES) - Tracing.debug("Not loading preferences since there is no file for node: " + absolutePath()); //$NON-NLS-1$ - return; + load(getProfileLocation(agent, profileId)); + } finally { + EngineActivator.getContext().ungetService(agentRef); } - load(getProfileLocation(profileId)); } } diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileRegistryComponent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileRegistryComponent.java index 1e05b8a91..1870b5989 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileRegistryComponent.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileRegistryComponent.java @@ -11,10 +11,10 @@ package org.eclipse.equinox.internal.p2.engine; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.core.IAgentLocation; import org.eclipse.equinox.p2.core.IProvisioningAgent; import org.eclipse.equinox.p2.core.spi.IAgentServiceFactory; +import org.eclipse.equinox.p2.engine.IProfileRegistry; /** * Instantiates default instances of {@link IProfileRegistry}. @@ -22,7 +22,7 @@ import org.eclipse.equinox.p2.core.spi.IAgentServiceFactory; public class ProfileRegistryComponent implements IAgentServiceFactory { public Object createService(IProvisioningAgent agent) { - AgentLocation location = (AgentLocation) agent.getService(AgentLocation.SERVICE_NAME); + IAgentLocation location = (IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME); SimpleProfileRegistry registry = new SimpleProfileRegistry(SimpleProfileRegistry.getDefaultRegistryDirectory(location)); registry.setEventBus((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)); return registry; diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileWriter.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileWriter.java index 01d1d1e47..1af6717c4 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileWriter.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileWriter.java @@ -14,10 +14,9 @@ import java.io.IOException; import java.io.OutputStream; import java.util.*; import org.eclipse.equinox.internal.p2.metadata.repository.io.MetadataWriter; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; public class ProfileWriter extends MetadataWriter implements ProfileXMLConstants { @@ -29,16 +28,10 @@ public class ProfileWriter extends MetadataWriter implements ProfileXMLConstants start(PROFILE_ELEMENT); attribute(ID_ATTRIBUTE, profile.getProfileId()); attribute(TIMESTAMP_ATTRIBUTE, Long.toString(profile.getTimestamp())); - IProfile parentProfile = profile.getParentProfile(); - if (parentProfile != null) - attribute(PARENT_ID_ATTRIBUTE, parentProfile.getProfileId()); - writeProperties(profile.getLocalProperties()); - Collector collector = profile.query(InstallableUnitQuery.ANY, new Collector(), null); - ArrayList ius = new ArrayList(collector.toCollection()); - Collections.sort(ius, new Comparator() { - public int compare(Object o1, Object o2) { - IInstallableUnit iu1 = (IInstallableUnit) o1; - IInstallableUnit iu2 = (IInstallableUnit) o2; + writeProperties(profile.getProperties()); + ArrayList ius = new ArrayList(profile.query(InstallableUnitQuery.ANY, null).unmodifiableSet()); + Collections.sort(ius, new Comparator() { + public int compare(IInstallableUnit iu1, IInstallableUnit iu2) { int IdCompare = iu1.getId().compareTo(iu2.getId()); if (IdCompare != 0) return IdCompare; @@ -52,14 +45,14 @@ public class ProfileWriter extends MetadataWriter implements ProfileXMLConstants flush(); } - private void writeInstallableUnitsProperties(Iterator it, int size, IProfile profile) { + private void writeInstallableUnitsProperties(Iterator it, int size, IProfile profile) { if (size == 0) return; start(IUS_PROPERTIES_ELEMENT); attribute(COLLECTION_SIZE_ATTRIBUTE, size); while (it.hasNext()) { - IInstallableUnit iu = (IInstallableUnit) it.next(); - Map properties = profile.getInstallableUnitProperties(iu); + IInstallableUnit iu = it.next(); + Map properties = profile.getInstallableUnitProperties(iu); if (properties.isEmpty()) continue; diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileXMLConstants.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileXMLConstants.java index 20b15ee9e..f28e9e0b0 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileXMLConstants.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/ProfileXMLConstants.java @@ -10,10 +10,9 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.engine; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import org.eclipse.equinox.internal.p2.persistence.XMLConstants; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; /** * Constants defining the structure of the XML for a Profile @@ -21,9 +20,9 @@ import org.eclipse.equinox.internal.p2.persistence.XMLConstants; public interface ProfileXMLConstants extends XMLConstants { // A format version number for profile XML. - public static final Version CURRENT_VERSION = new Version(1, 0, 0); - public static final Version COMPATIBLE_VERSION = new Version(0, 0, 1); - public static final VersionRange XML_TOLERANCE = new VersionRange(COMPATIBLE_VERSION, true, new Version(2, 0, 0), false); + public static final Version CURRENT_VERSION = Version.createOSGi(1, 0, 0); + public static final Version COMPATIBLE_VERSION = Version.createOSGi(0, 0, 1); + public static final VersionRange XML_TOLERANCE = new VersionRange(COMPATIBLE_VERSION, true, Version.createOSGi(2, 0, 0), false); // Constants for profile elements diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/SimpleProfileRegistry.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/SimpleProfileRegistry.java index 6febf6915..2b18f2f39 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/SimpleProfileRegistry.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/SimpleProfileRegistry.java @@ -8,13 +8,9 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.engine; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.io.*; import java.lang.ref.SoftReference; -import java.net.MalformedURLException; -import java.net.URL; +import java.net.URI; import java.util.*; import java.util.Map.Entry; import java.util.zip.GZIPInputStream; @@ -22,16 +18,18 @@ import java.util.zip.GZIPOutputStream; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.*; -import org.eclipse.equinox.internal.provisional.p2.core.*; +import org.eclipse.equinox.internal.p2.metadata.TranslationSupport; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.osgi.service.datalocation.Location; import org.eclipse.osgi.util.NLS; import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -47,8 +45,8 @@ public class SimpleProfileRegistry implements IProfileRegistry { /** * Reference to Map of String(Profile id)->Profile. */ - private SoftReference profiles; - private Map profileLocks = new HashMap(); + private SoftReference> profiles; + private Map profileLocks = new HashMap(); private String self; @@ -68,24 +66,38 @@ public class SimpleProfileRegistry implements IProfileRegistry { public SimpleProfileRegistry(File registryDirectory, ISurrogateProfileHandler handler, boolean updateSelfProfile) { store = registryDirectory; surrogateProfileHandler = handler; - self = EngineActivator.getContext().getProperty("eclipse.p2.profile"); //$NON-NLS-1$ Assert.isNotNull(store, "Profile registry requires a directory"); //$NON-NLS-1$ + findSelf(); this.updateSelfProfile = updateSelfProfile; } - public static File getDefaultRegistryDirectory(AgentLocation agent) { + /** + * Determine the id of the "self" profile. This is only applicable for the registry + * of the currently running system. + */ + private void findSelf() { + //the location for the currently running system is registered as a service + ServiceReference ref = EngineActivator.getContext().getServiceReference(IAgentLocation.SERVICE_NAME); + if (ref == null) + return; + IAgentLocation location = (IAgentLocation) EngineActivator.getContext().getService(ref); + if (location == null) + return; + if (store.equals(getDefaultRegistryDirectory(location))) { + //we are the registry for the currently running system + self = EngineActivator.getContext().getProperty("eclipse.p2.profile"); //$NON-NLS-1$ + } + EngineActivator.getContext().ungetService(ref); + } + + public static File getDefaultRegistryDirectory(IAgentLocation agent) { File registryDirectory = null; if (agent == null) throw new IllegalStateException("Profile Registry inialization failed: Agent Location is not available"); //$NON-NLS-1$ - final URL engineDataArea = agent.getDataArea(EngineActivator.ID); - try { - URL registryURL = new URL(engineDataArea, DEFAULT_STORAGE_DIR); - registryDirectory = new File(registryURL.getPath()); - registryDirectory.mkdirs(); - } catch (MalformedURLException e) { - //this is not possible because we know the above URL is valid - throw new IllegalStateException("Profile Registry inialization failed. Agent Location is invalid:" + engineDataArea); //$NON-NLS-1$ - } + final URI engineDataArea = agent.getDataArea(EngineActivator.ID); + URI registryURL = URIUtil.append(engineDataArea, DEFAULT_STORAGE_DIR); + registryDirectory = new File(registryURL); + registryDirectory.mkdirs(); return registryDirectory; } @@ -93,13 +105,17 @@ public class SimpleProfileRegistry implements IProfileRegistry { * If the current profile for self is marked as a roaming profile, we need * to update its install and bundle pool locations. */ - private void updateSelfProfile(Map profileMap) { + private void updateSelfProfile(Map profileMap) { if (profileMap == null) return; - Profile selfProfile = (Profile) profileMap.get(self); + Profile selfProfile = profileMap.get(self); if (selfProfile == null) return; + //register default locale provider where metadata translations are found + //TODO ideally this should not be hard-coded to the current profile + TranslationSupport.getInstance().setTranslationSource(selfProfile); + if (DebugHelper.DEBUG_PROFILE_REGISTRY) DebugHelper.debug(PROFILE_REGISTRY, "SimpleProfileRegistry.updateSelfProfile"); //$NON-NLS-1$ boolean changed = false; @@ -172,7 +188,7 @@ public class SimpleProfileRegistry implements IProfileRegistry { } catch (IOException e) { LogHelper.log(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.error_parsing_profile, profileFile), e)); } - return (IProfile) parser.getProfileMap().get(id); + return parser.getProfileMap().get(id); } public synchronized long[] listProfileTimestamps(String id) { @@ -209,7 +225,7 @@ public class SimpleProfileRegistry implements IProfileRegistry { private Profile internalGetProfile(String id) { if (SELF.equals(id)) id = self; - Profile profile = (Profile) getProfileMap().get(id); + Profile profile = getProfileMap().get(id); if (profile == null && self != null && self.equals(id)) profile = createSurrogateProfile(id); @@ -226,16 +242,15 @@ public class SimpleProfileRegistry implements IProfileRegistry { saveProfile(profile); resetProfiles(); - return (Profile) getProfileMap().get(id); + return getProfileMap().get(id); } public synchronized IProfile[] getProfiles() { - Map profileMap = getProfileMap(); + Map profileMap = getProfileMap(); Profile[] result = new Profile[profileMap.size()]; int i = 0; - for (Iterator it = profileMap.values().iterator(); it.hasNext(); i++) { - Profile profile = (Profile) it.next(); - result[i] = profile.snapshot(); + for (Profile profile : profileMap.values()) { + result[i++] = profile.snapshot(); } return result; } @@ -243,16 +258,16 @@ public class SimpleProfileRegistry implements IProfileRegistry { /** * Returns an initialized map of String(Profile id)->Profile. */ - protected Map getProfileMap() { + protected Map getProfileMap() { if (profiles != null) { - Map result = (Map) profiles.get(); + Map result = profiles.get(); if (result != null) return result; } - Map result = restore(); + Map result = restore(); if (result == null) - result = new LinkedHashMap(8); - profiles = new SoftReference(result); + result = new LinkedHashMap(8); + profiles = new SoftReference>(result); if (updateSelfProfile) { //update self profile on first load updateSelfProfile(result); @@ -266,18 +281,18 @@ public class SimpleProfileRegistry implements IProfileRegistry { if (current == null) throw new IllegalArgumentException(NLS.bind(Messages.profile_does_not_exist, id)); - ProfileLock lock = (ProfileLock) profileLocks.get(id); + ProfileLock lock = profileLocks.get(id); lock.checkLocked(); current.clearLocalProperties(); current.clearInstallableUnits(); current.addProperties(profile.getLocalProperties()); - Collector collector = profile.query(InstallableUnitQuery.ANY, new Collector(), null); - for (Iterator collectorIt = collector.iterator(); collectorIt.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) collectorIt.next(); + IQueryResult queryResult = profile.query(InstallableUnitQuery.ANY, null); + for (Iterator queryResultIt = queryResult.iterator(); queryResultIt.hasNext();) { + IInstallableUnit iu = queryResultIt.next(); current.addInstallableUnit(iu); - Map iuProperties = profile.getInstallableUnitProperties(iu); + Map iuProperties = profile.getInstallableUnitProperties(iu); if (iuProperties != null) current.addInstallableUnitProperties(iu, iuProperties); } @@ -291,14 +306,14 @@ public class SimpleProfileRegistry implements IProfileRegistry { return addProfile(id, null, null); } - public IProfile addProfile(String id, Map profileProperties) throws ProvisionException { + public IProfile addProfile(String id, Map profileProperties) throws ProvisionException { return addProfile(id, profileProperties, null); } - public synchronized IProfile addProfile(String id, Map profileProperties, String parentId) throws ProvisionException { + public synchronized IProfile addProfile(String id, Map profileProperties, String parentId) throws ProvisionException { if (SELF.equals(id)) id = self; - Map profileMap = getProfileMap(); + Map profileMap = getProfileMap(); if (profileMap.get(id) != null) throw new ProvisionException(NLS.bind(Messages.Profile_Duplicate_Root_Profile_Id, id)); @@ -306,7 +321,7 @@ public class SimpleProfileRegistry implements IProfileRegistry { if (parentId != null) { if (SELF.equals(parentId)) parentId = self; - parent = (Profile) profileMap.get(parentId); + parent = profileMap.get(parentId); if (parent == null) throw new ProvisionException(NLS.bind(Messages.Profile_Parent_Not_Found, parentId)); } @@ -324,14 +339,14 @@ public class SimpleProfileRegistry implements IProfileRegistry { if (SELF.equals(profileId)) profileId = self; //note we need to maintain a reference to the profile map until it is persisted to prevent gc - Map profileMap = getProfileMap(); - Profile profile = (Profile) profileMap.get(profileId); + Map profileMap = getProfileMap(); + Profile profile = profileMap.get(profileId); if (profile == null) return; - String[] subProfileIds = profile.getSubProfileIds(); - for (int i = 0; i < subProfileIds.length; i++) { - removeProfile(subProfileIds[i]); + List subProfileIds = profile.getSubProfileIds(); + for (int i = 0; i < subProfileIds.size(); i++) { + removeProfile(subProfileIds.get(i)); } internalLockProfile(profile); // The above call recursively locked the parent(s). So save it away to rewind the locking process. @@ -383,9 +398,9 @@ public class SimpleProfileRegistry implements IProfileRegistry { * Restores the profile registry from disk, and returns the loaded profile map. * Returns null if unable to read the registry. */ - private Map restore() { + private Map restore() { if (store == null || !store.isDirectory()) - throw new IllegalStateException(Messages.reg_dir_not_available); + throw new IllegalStateException(NLS.bind(Messages.reg_dir_not_available, store)); Parser parser = new Parser(EngineActivator.getContext(), EngineActivator.ID); File[] profileDirectories = store.listFiles(new FileFilter() { @@ -396,7 +411,7 @@ public class SimpleProfileRegistry implements IProfileRegistry { for (int i = 0; i < profileDirectories.length; i++) { String directoryName = profileDirectories[i].getName(); String profileId = unescape(directoryName.substring(0, directoryName.lastIndexOf(PROFILE_EXT))); - ProfileLock lock = (ProfileLock) profileLocks.get(profileId); + ProfileLock lock = profileLocks.get(profileId); if (lock == null) { lock = new ProfileLock(this, profileDirectories[i]); profileLocks.put(profileId, lock); @@ -502,7 +517,7 @@ public class SimpleProfileRegistry implements IProfileRegistry { return false; //check whether the profile contains the p2 engine from 3.5.0 or earlier - return profile.available(new InstallableUnitQuery("org.eclipse.equinox.p2.engine", new VersionRange("[0.0.0, 1.0.101)")), new Collector(), null).isEmpty(); //$NON-NLS-1$//$NON-NLS-2$ + return profile.available(new InstallableUnitQuery("org.eclipse.equinox.p2.engine", new VersionRange("[0.0.0, 1.0.101)")), null).isEmpty(); //$NON-NLS-1$//$NON-NLS-2$ } private void deleteProfile(String profileId) { @@ -570,7 +585,7 @@ public class SimpleProfileRegistry implements IProfileRegistry { * as written by the Writer class. */ class Parser extends ProfileParser { - private final Map profileHandlers = new HashMap(); + private final Map profileHandlers = new HashMap(); public Parser(BundleContext context, String bundleId) { super(context, bundleId); @@ -613,26 +628,25 @@ public class SimpleProfileRegistry implements IProfileRegistry { return this; } - public Map getProfileMap() { - Map profileMap = new HashMap(); - for (Iterator it = profileHandlers.keySet().iterator(); it.hasNext();) { - String profileId = (String) it.next(); + public Map getProfileMap() { + Map profileMap = new HashMap(); + for (String profileId : profileHandlers.keySet()) { addProfile(profileId, profileMap); } return profileMap; } - private void addProfile(String profileId, Map profileMap) { + private void addProfile(String profileId, Map profileMap) { if (profileMap.containsKey(profileId)) return; - ProfileHandler profileHandler = (ProfileHandler) profileHandlers.get(profileId); + ProfileHandler profileHandler = profileHandlers.get(profileId); Profile parentProfile = null; String parentId = profileHandler.getParentId(); if (parentId != null) { addProfile(parentId, profileMap); - parentProfile = (Profile) profileMap.get(parentId); + parentProfile = profileMap.get(parentId); } Profile profile = new Profile(profileId, parentProfile, profileHandler.getProperties()); @@ -646,13 +660,10 @@ public class SimpleProfileRegistry implements IProfileRegistry { for (int i = 0; i < ius.length; i++) { IInstallableUnit iu = ius[i]; profile.addInstallableUnit(iu); - Map iuProperties = profileHandler.getIUProperties(iu); + Map iuProperties = profileHandler.getIUProperties(iu); if (iuProperties != null) { - for (Iterator it = iuProperties.entrySet().iterator(); it.hasNext();) { - Entry entry = (Entry) it.next(); - String key = (String) entry.getKey(); - String value = (String) entry.getValue(); - profile.setInstallableUnitProperty(iu, key, value); + for (Entry entry : iuProperties.entrySet()) { + profile.setInstallableUnitProperty(iu, entry.getKey(), entry.getValue()); } } } @@ -732,26 +743,12 @@ public class SimpleProfileRegistry implements IProfileRegistry { } private boolean internalLockProfile(IProfile profile) { - ProfileLock lock = (ProfileLock) profileLocks.get(profile.getProfileId()); + ProfileLock lock = profileLocks.get(profile.getProfileId()); if (lock == null) { lock = new ProfileLock(this, new File(store, escape(profile.getProfileId()) + PROFILE_EXT)); profileLocks.put(profile.getProfileId(), lock); } - if (!lock.lock()) - return false; - - if (profile.getParentProfile() == null) - return true; - - boolean locked = false; - try { - locked = internalLockProfile(profile.getParentProfile()); - } finally { - // this check is done here to ensure we unlock even if a runtime exception is thrown - if (!locked) - lock.unlock(); - } - return locked; + return lock.lock(); } private boolean checkTimestamps(IProfile profile, IProfile internalProfile) { @@ -772,9 +769,6 @@ public class SimpleProfileRegistry implements IProfileRegistry { return false; } - if (profile.getParentProfile() != null) - return checkTimestamps(profile.getParentProfile(), internalProfile.getParentProfile()); - return true; } @@ -816,10 +810,7 @@ public class SimpleProfileRegistry implements IProfileRegistry { } private void internalUnlockProfile(IProfile profile) { - if (profile.getParentProfile() != null) - internalUnlockProfile(profile.getParentProfile()); - - ProfileLock lock = (ProfileLock) profileLocks.get(profile.getProfileId()); + ProfileLock lock = profileLocks.get(profile.getProfileId()); lock.unlock(); } diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/SurrogateProfileHandler.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/SurrogateProfileHandler.java index ec59aedc0..5e3448745 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/SurrogateProfileHandler.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/SurrogateProfileHandler.java @@ -17,21 +17,23 @@ import java.net.URL; import java.util.Iterator; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ISurrogateProfileHandler; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.ISurrogateProfileHandler; +import org.eclipse.equinox.p2.engine.query.IUProfilePropertyQuery; +import org.eclipse.equinox.p2.engine.query.UserVisibleRootQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.*; import org.eclipse.osgi.service.datalocation.Location; import org.eclipse.osgi.util.NLS; public class SurrogateProfileHandler implements ISurrogateProfileHandler { private static final String NATIVE_TOUCHPOINT_TYPE = "org.eclipse.equinox.p2.native"; //$NON-NLS-1$ - private static final String PROP_TYPE_ROOT = "org.eclipse.equinox.p2.type.root"; //$NON-NLS-1$ private static final String P2_ENGINE_DIR = "p2/" + EngineActivator.ID + "/"; //$NON-NLS-1$//$NON-NLS-2$ private static final String OSGI_INSTALL_AREA = "osgi.install.area"; //$NON-NLS-1$ private static final String ECLIPSE_INI_IGNORED = "eclipse.ini.ignored"; //$NON-NLS-1$ - private static final String IU_LOCKED = Integer.toString(IInstallableUnit.LOCK_UNINSTALL | IInstallableUnit.LOCK_UPDATE); + private static final String IU_LOCKED = Integer.toString(IProfile.LOCK_UNINSTALL | IProfile.LOCK_UPDATE); private static final String PROP_SURROGATE = "org.eclipse.equinox.p2.surrogate"; //$NON-NLS-1$ private static final String PROP_SHARED_TIMESTAMP = "org.eclipse.equinox.p2.shared.timestamp"; //$NON-NLS-1$ private static final String PROP_BASE = "org.eclipse.equinox.p2.base"; //$NON-NLS-1$ @@ -41,63 +43,37 @@ public class SurrogateProfileHandler implements ISurrogateProfileHandler { private SimpleProfileRegistry profileRegistry; - private SoftReference cachedProfile; + private SoftReference cachedProfile; private static void addSharedProfileBaseIUs(final IProfile sharedProfile, final Profile userProfile) { - Query rootIUQuery = new MatchQuery() { - public boolean isMatch(Object candidate) { - if (candidate instanceof IInstallableUnit) { - IInstallableUnit iu = (IInstallableUnit) candidate; - if (Boolean.valueOf(sharedProfile.getInstallableUnitProperty(iu, PROP_TYPE_ROOT)).booleanValue()) - return true; - if (iu.getTouchpointType().getId().equals(NATIVE_TOUCHPOINT_TYPE)) - return true; - } - return false; + IQuery rootIUQuery = CompoundQuery.createCompoundQuery(new UserVisibleRootQuery(), new MatchQuery() { + public boolean isMatch(IInstallableUnit iu) { + return iu.getTouchpointType().getId().equals(NATIVE_TOUCHPOINT_TYPE); } - }; - Collector rootIUs = sharedProfile.query(rootIUQuery, new Collector(), null); - for (Iterator iterator = rootIUs.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); + }, false); + IQueryResult rootIUs = sharedProfile.query(rootIUQuery, null); + for (Iterator iterator = rootIUs.iterator(); iterator.hasNext();) { + IInstallableUnit iu = iterator.next(); userProfile.addInstallableUnit(iu); userProfile.addInstallableUnitProperties(iu, sharedProfile.getInstallableUnitProperties(iu)); - userProfile.setInstallableUnitProperty(iu, IInstallableUnit.PROP_PROFILE_LOCKED_IU, IU_LOCKED); + userProfile.setInstallableUnitProperty(iu, IProfile.PROP_PROFILE_LOCKED_IU, IU_LOCKED); userProfile.setInstallableUnitProperty(iu, PROP_BASE, Boolean.TRUE.toString()); } } private static void removeUserProfileBaseIUs(final Profile userProfile) { - Query rootIUQuery = new MatchQuery() { - public boolean isMatch(Object candidate) { - if (candidate instanceof IInstallableUnit) { - IInstallableUnit iu = (IInstallableUnit) candidate; - if (Boolean.valueOf(userProfile.getInstallableUnitProperty(iu, PROP_BASE)).booleanValue()) - return true; - } - return false; - } - }; - Collector rootIUs = userProfile.query(rootIUQuery, new Collector(), null); - for (Iterator iterator = rootIUs.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); + IQuery rootIUQuery = new IUProfilePropertyQuery(PROP_BASE, Boolean.TRUE.toString()); + IQueryResult rootIUs = userProfile.query(rootIUQuery, null); + for (Iterator iterator = rootIUs.iterator(); iterator.hasNext();) { + IInstallableUnit iu = iterator.next(); userProfile.removeInstallableUnit(iu); } } private static void markRootsOptional(final Profile userProfile) { - Query rootIUQuery = new MatchQuery() { - public boolean isMatch(Object candidate) { - if (candidate instanceof IInstallableUnit) { - IInstallableUnit iu = (IInstallableUnit) candidate; - if (Boolean.valueOf(userProfile.getInstallableUnitProperty(iu, PROP_TYPE_ROOT)).booleanValue()) - return true; - } - return false; - } - }; - Collector rootIUs = userProfile.query(rootIUQuery, new Collector(), null); - for (Iterator iterator = rootIUs.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); + IQueryResult rootIUs = userProfile.query(new UserVisibleRootQuery(), null); + for (Iterator iterator = rootIUs.iterator(); iterator.hasNext();) { + IInstallableUnit iu = iterator.next(); userProfile.setInstallableUnitProperty(iu, PROP_INCLUSION_RULES, OPTIONAL); } } @@ -158,14 +134,14 @@ public class SurrogateProfileHandler implements ISurrogateProfileHandler { //see if we have a cached profile if (cachedProfile != null) { - IProfile profile = (IProfile) cachedProfile.get(); + IProfile profile = cachedProfile.get(); if (profile != null && profile.getProfileId().equals(id) && profile.getTimestamp() == currentTimestamp) return profile; } final IProfile profile = registry.getProfile(id, currentTimestamp); if (profile != null) - cachedProfile = new SoftReference(profile); + cachedProfile = new SoftReference(profile); return profile; } @@ -195,12 +171,16 @@ public class SurrogateProfileHandler implements ISurrogateProfileHandler { /* (non-Javadoc) * @see org.eclipse.equinox.internal.p2.engine.ISurrogateProfileHandler#queryProfile(org.eclipse.equinox.internal.provisional.p2.engine.IProfile, org.eclipse.equinox.internal.provisional.p2.query.Query, org.eclipse.equinox.internal.provisional.p2.query.Collector, org.eclipse.core.runtime.IProgressMonitor) */ - public Collector queryProfile(IProfile profile, Query query, Collector collector, IProgressMonitor monitor) { + public IQueryResult queryProfile(IProfile profile, IQuery query, IProgressMonitor monitor) { IProfile sharedProfile = getSharedProfile(profile.getProfileId()); - if (sharedProfile != null) - sharedProfile.query(query, collector, monitor); + if (sharedProfile == null) + return profile.query(query, monitor); - return profile.query(query, collector, monitor); + // TODO: Should consider using a sequenced iterator here instead of collecting + Collector result = new Collector(); + result.addAll(sharedProfile.query(query, monitor)); + result.addAll(profile.query(query, monitor)); + return result; } public boolean updateProfile(IProfile userProfile) { @@ -217,7 +197,7 @@ public class SurrogateProfileHandler implements ISurrogateProfileHandler { Profile writableUserProfile = (Profile) userProfile; updateProperties(sharedProfile, writableUserProfile); removeUserProfileBaseIUs(writableUserProfile); - if (!userProfile.query(InstallableUnitQuery.ANY, new Collector(), null).isEmpty()) { + if (!userProfile.query(InstallableUnitQuery.ANY, null).isEmpty()) { writableUserProfile.setProperty(PROP_RESOLVE, Boolean.TRUE.toString()); markRootsOptional(writableUserProfile); } diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/TouchpointManager.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/TouchpointManager.java index 8da1e0b66..fb5e4dfff 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/TouchpointManager.java +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/TouchpointManager.java @@ -10,15 +10,12 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.engine; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.provisional.p2.engine.Touchpoint; -import org.eclipse.equinox.internal.provisional.p2.metadata.ITouchpointType; +import org.eclipse.equinox.p2.engine.spi.Touchpoint; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.osgi.util.NLS; //TODO This needs to support multiple version of each touchpoint and have a lookup that supports version semantics @@ -65,7 +62,7 @@ public class TouchpointManager implements IRegistryChangeListener { public Version getVersion() { try { - return new Version(element.getAttribute(ATTRIBUTE_VERSION)); + return Version.create(element.getAttribute(ATTRIBUTE_VERSION)); } catch (InvalidRegistryObjectException e) { return null; } @@ -92,7 +89,7 @@ public class TouchpointManager implements IRegistryChangeListener { // TODO: Do we really want to store the touchpoints? The danger is // that if two installations are performed simultaneously, then... // TODO: Figure out locking, concurrency requirements for touchpoints. - private Map touchpointEntries; + private Map touchpointEntries; public TouchpointManager() { RegistryFactory.getRegistry().addRegistryChangeListener(this, EngineActivator.ID); @@ -116,7 +113,7 @@ public class TouchpointManager implements IRegistryChangeListener { if (typeId == null || typeId.length() == 0) throw new IllegalArgumentException(Messages.TouchpointManager_Null_Touchpoint_Type_Argument); - TouchpointEntry entry = (TouchpointEntry) getTouchpointEntries().get(typeId); + TouchpointEntry entry = getTouchpointEntries().get(typeId); if (entry == null) return null; if (versionRange != null) { @@ -131,13 +128,13 @@ public class TouchpointManager implements IRegistryChangeListener { /* * Construct a map of the extensions that implement the touchpoints extension point. */ - private synchronized Map getTouchpointEntries() { + private synchronized Map getTouchpointEntries() { if (touchpointEntries != null) return touchpointEntries; IExtensionPoint point = RegistryFactory.getRegistry().getExtensionPoint(EngineActivator.ID, PT_TOUCHPOINTS); IExtension[] extensions = point.getExtensions(); - touchpointEntries = new HashMap(extensions.length); + touchpointEntries = new HashMap(extensions.length); for (int i = 0; i < extensions.length; i++) { try { IConfigurationElement[] elements = extensions[i].getConfigurationElements(); @@ -155,7 +152,7 @@ public class TouchpointManager implements IRegistryChangeListener { if (touchpointEntries.get(id) == null) { touchpointEntries.put(id, new TouchpointEntry(elements[j])); } else { - reportError(NLS.bind(Messages.TouchpointManager_Conflicting_Touchpoint_Types, ATTRIBUTE_TYPE, id)); + reportError(NLS.bind(Messages.TouchpointManager_Conflicting_Touchpoint_Types, id)); } } } catch (InvalidRegistryObjectException e) { diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/messages.properties b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/messages.properties index a491c286a..f9bc0c30c 100644 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/messages.properties +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/messages.properties @@ -44,9 +44,61 @@ SimpleProfileRegistry_CannotRemoveCurrentSnapshot=Cannot remove the current prof profile_does_not_exist=Profile to be updated does not exist: {0}. profile_not_current=Profile {0} is not current. profile_not_registered=Profile {0} not registered. -reg_dir_not_available=Registry Directory not available. +reg_dir_not_available=Registry Directory not available: {0}. thread_not_owner=Thread not lock owner. profile_lock_not_reentrant=Lock failed. Profile does not permit reentrant locking. shared_profile_not_found=Shared profile {0} not found. ProfilePreferences_saving=Saving profile preferences +phase_error=An error occurred during the {0} phase. +action_undo_error=An error occurred while rolling back the engine operation while undoing the {0} action. +forced_action_execute_error=An error occurred while performing the engine operation while executing the {0} action in forced mode. The operation will continue. +phaseid_not_positive=Phase weight must be positive. +phaseid_not_set=Phase id must be set. +action_not_found=No action found for: {0}. +actions_not_found=No actions found for: {0}. +not_current_phase=Current phase does not match argument. +null_operands=Operands must not be null. +null_phase=Phase must not be null. +null_phases=Phases must not be null +null_phaseset=PhaseSet must not be null. +null_profile=Profile must not be null. +touchpoint_prepare_error=An error occurred while preparing the engine operation for the {0} touchpoint. +touchpoint_commit_error=An error occurred while committing the engine operation for the {0} touchpoint. +touchpoint_rollback_error=An error occurred while rolling back the engine operation for the {0} touchpoint. +phase_undo_error=An error occurred while undoing the {0} phase. +phase_undo_operand_error=An error occurred while undoing the {0} phase for operand {1}. +phase_not_started=There is no phase to end. +phase_started=A phase is already started. + +session_prepare_error=An error occurred while preparing the engine session for profile: {0}. +session_commit_error=An error occurred while committing the engine session for profile: {0}. +null_operand=Operand must not be null. +operand_started=An operand is already started. +operand_not_started=There is no operand to end. +not_current_operand=Current operand does not match argument. +null_action=Action must not be null +session_context=session context was:(profile={0}, phase={1}, operand={2}, action={3}). +preparing=Preparing to commit the provisioning operation. +committing=Committing the provisioning operation. +rollingback_error=An error was detected while performing the engine operation and the changes are being rolled back. See the log for details. +rollingback_cancel=The engine operation was cancelled and the changes are being rolled back. + +Engine_Operation_Canceled_By_User=Operation canceled by the user. +InstallableUnitEvent_type_not_install_or_uninstall=type must be either UNINSTALL(0) or INSTALL(1) +CertificateChecker_CertificateError=An invalid certificate was found. +CertificateChecker_CertificateRejected=One or more certificates rejected. Cannot proceed with installation. +CertificateChecker_KeystoreConnectionError=Cannot connect to keystore. +CertificateChecker_SignedContentError=Error with signed content. +CertificateChecker_SignedContentIOError=Error reading signed content. +CertificateChecker_UnsignedNotAllowed=Installing unsigned artifacts is not permitted: {0} + +Phase_Collect_Error=An error occurred while collecting items to be installed +Phase_Configure_Error=An error occurred while configuring the installed items +Phase_Configure_Task=Configuring {0} +Phase_Install_Error=An error occurred while installing the items +Phase_Install_Task=Installing {0} +Phase_Sizing_Error=Error computing the size. Some of the items to be installed could not be found. +Phase_Sizing_Warning=The size may not be accurate. Some of the items did not report a size. +Phase_Unconfigure_Error=An error occurred while unconfiguring the items to uninstall +Phase_Uninstall_Error=An error occurred while uninstalling diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/CertificateChecker.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/CertificateChecker.java new file mode 100644 index 000000000..42f04bcbf --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/CertificateChecker.java @@ -0,0 +1,184 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.engine.phases; + +import java.io.File; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.cert.Certificate; +import java.util.ArrayList; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.equinox.internal.p2.engine.EngineActivator; +import org.eclipse.equinox.internal.p2.engine.Messages; +import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI; +import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI.TrustInfo; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.osgi.service.security.TrustEngine; +import org.eclipse.osgi.signedcontent.*; +import org.eclipse.osgi.util.NLS; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; + +public class CertificateChecker { + private ArrayList artifacts; + private final IProvisioningAgent agent; + + public CertificateChecker() { + this(null); + } + + public CertificateChecker(IProvisioningAgent agent) { + this.agent = agent; + artifacts = new ArrayList(); + } + + public IStatus start() { + final BundleContext context = EngineActivator.getContext(); + ServiceReference contentFactoryRef = context.getServiceReference(SignedContentFactory.class.getName()); + SignedContentFactory verifierFactory = (SignedContentFactory) context.getService(contentFactoryRef); + ServiceReference trustEngineRef = context.getServiceReference(TrustEngine.class.getName()); + TrustEngine trustEngine = (TrustEngine) context.getService(trustEngineRef); + try { + return checkCertificates(trustEngine, verifierFactory); + } finally { + context.ungetService(contentFactoryRef); + context.ungetService(trustEngineRef); + } + } + + private IStatus checkCertificates(TrustEngine trustEngine, SignedContentFactory verifierFactory) { + IServiceUI serviceUI = (IServiceUI) agent.getService(IServiceUI.SERVICE_NAME); + SignedContent content = null; + SignerInfo[] signerInfo = null; + ArrayList untrusted = new ArrayList(); + ArrayList unsigned = new ArrayList(); + ArrayList untrustedChain = new ArrayList(); + IStatus status = Status.OK_STATUS; + if (artifacts.size() == 0 || serviceUI == null) + return status; + for (File artifact : artifacts) { + try { + content = verifierFactory.getSignedContent(artifact); + if (!content.isSigned()) { + unsigned.add(artifact); + continue; + } + signerInfo = content.getSignerInfos(); + } catch (GeneralSecurityException e) { + return new Status(IStatus.ERROR, EngineActivator.ID, Messages.CertificateChecker_SignedContentError, e); + } catch (IOException e) { + return new Status(IStatus.ERROR, EngineActivator.ID, Messages.CertificateChecker_SignedContentIOError, e); + } + for (int i = 0; i < signerInfo.length; i++) { + Certificate[] certificateChain = signerInfo[i].getCertificateChain(); + try { + Certificate trustAnchor = trustEngine.findTrustAnchor(certificateChain); + if (trustAnchor == null) { + if (!untrusted.contains(certificateChain[0])) { + untrusted.add(certificateChain[0]); + untrustedChain.add(certificateChain); + } + } + } catch (IOException e) { + return new Status(IStatus.ERROR, EngineActivator.ID, Messages.CertificateChecker_KeystoreConnectionError, e); + } + } + } + String policy = getUnsignedContentPolicy(); + //if there is unsigned content and we should never allow it, then fail without further checking certificates + if (!unsigned.isEmpty() && EngineActivator.UNSIGNED_FAIL.equals(policy)) + return new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.CertificateChecker_UnsignedNotAllowed, unsigned)); + + String[] details; + // If we always allow unsigned content, or we don't have any, we don't prompt the user about it + if (EngineActivator.UNSIGNED_ALLOW.equals(policy) || unsigned.isEmpty()) + details = null; + else { + details = new String[unsigned.size()]; + for (int i = 0; i < details.length; i++) { + details[i] = unsigned.get(i).toString(); + } + } + Certificate[][] unTrustedCertificateChains; + if (untrusted.isEmpty()) { + unTrustedCertificateChains = null; + } else { + unTrustedCertificateChains = new Certificate[untrustedChain.size()][]; + for (int i = 0; i < untrustedChain.size(); i++) { + unTrustedCertificateChains[i] = untrustedChain.get(i); + } + } + + // If there was no unsigned content, and nothing untrusted, no need to prompt. + if (details == null && unTrustedCertificateChains == null) + return status; + + TrustInfo trustInfo = serviceUI.getTrustInfo(unTrustedCertificateChains, details); + + // If user doesn't trust unsigned content, cancel the operation + if (!trustInfo.trustUnsignedContent()) + return Status.CANCEL_STATUS; + + Certificate[] trustedCertificates = trustInfo.getTrustedCertificates(); + // If we had untrusted chains and nothing was trusted, cancel the operation + if (unTrustedCertificateChains != null && trustedCertificates == null) { + return new Status(IStatus.CANCEL, EngineActivator.ID, Messages.CertificateChecker_CertificateRejected); + } + // Anything that was trusted should be removed from the untrusted list + if (trustedCertificates != null) { + for (int i = 0; i < trustedCertificates.length; i++) { + untrusted.remove(trustedCertificates[i]); + } + } + + // If there is still untrusted content, cancel the operation + if (untrusted.size() > 0) + return new Status(IStatus.CANCEL, EngineActivator.ID, Messages.CertificateChecker_CertificateRejected); + // If we should persist the trusted certificates, add them to the trust engine + if (trustInfo.persistTrust()) { + for (int i = 0; i < trustedCertificates.length; i++) { + try { + trustEngine.addTrustAnchor(trustedCertificates[i], trustedCertificates[i].toString()); + } catch (IOException e) { + //just return an INFO so the user can proceed with the install + return new Status(IStatus.INFO, EngineActivator.ID, Messages.CertificateChecker_KeystoreConnectionError, e); + } catch (GeneralSecurityException e) { + return new Status(IStatus.INFO, EngineActivator.ID, Messages.CertificateChecker_CertificateError, e); + } + } + } + + return status; + } + + /** + * Return the policy on unsigned content. + */ + private String getUnsignedContentPolicy() { + String policy = EngineActivator.getContext().getProperty(EngineActivator.PROP_UNSIGNED_POLICY); + if (policy == null) + policy = EngineActivator.UNSIGNED_PROMPT; + return policy; + + } + + public void add(File toAdd) { + artifacts.add(toAdd); + } + + public void add(Object[] toAdd) { + for (int i = 0; i < toAdd.length; i++) { + if (toAdd[i] instanceof File) + add((File) toAdd[i]); + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/CheckTrust.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/CheckTrust.java new file mode 100644 index 000000000..090aba5c7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/CheckTrust.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.engine.phases; + +import java.io.File; +import java.util.*; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.engine.InstallableUnitPhase; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.ITouchpointType; + +/** + * An install phase that checks if the certificates used to sign the artifacts + * being installed are from a trusted source. + */ +public class CheckTrust extends InstallableUnitPhase { + + private static final String PHASE_ID = IPhaseSet.PHASE_CHECK_TRUST; + public static final String PARM_ARTIFACT_FILES = "artifactFiles"; //$NON-NLS-1$ + + public CheckTrust(int weight) { + super(PHASE_ID, weight); + } + + protected boolean isApplicable(InstallableUnitOperand op) { + return (op.second() != null); + } + + protected IStatus completePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { + @SuppressWarnings("unchecked") + Collection artifactRequests = (Collection) parameters.get(PARM_ARTIFACT_FILES); + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT); + + // Instantiate a check trust manager + CertificateChecker certificateChecker = new CertificateChecker(agent); + certificateChecker.add(artifactRequests.toArray()); + IStatus status = certificateChecker.start(); + + return status; + } + + protected List getActions(InstallableUnitOperand operand) { + IInstallableUnit unit = operand.second(); + List parsedActions = getActions(unit, phaseId); + if (parsedActions != null) + return parsedActions; + + ITouchpointType type = unit.getTouchpointType(); + if (type == null || type == ITouchpointType.NONE) + return null; + + String actionId = getActionManager().getTouchpointQualifiedActionId(phaseId, type); + ProvisioningAction action = getActionManager().getAction(actionId, null); + if (action == null) { + return null; + } + return Collections.singletonList(action); + } + + protected IStatus initializeOperand(IProfile profile, InstallableUnitOperand operand, Map parameters, IProgressMonitor monitor) { + IInstallableUnit iu = operand.second(); + parameters.put(PARM_IU, iu); + + return super.initializeOperand(profile, operand, parameters, monitor); + } + + protected IStatus initializePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { + parameters.put(PARM_ARTIFACT_FILES, new ArrayList()); + return super.initializePhase(monitor, profile, parameters); + } + +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Collect.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Collect.java new file mode 100644 index 000000000..1993d49ab --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Collect.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * WindRiver - https://bugs.eclipse.org/bugs/show_bug.cgi?id=227372 + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.engine.phases; + +import java.util.*; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.engine.*; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.ITouchpointType; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRequest; + +/** + * The goal of the collect phase is to ask the touchpoints if the artifacts associated with an IU need to be downloaded. + */ +public class Collect extends InstallableUnitPhase { + private static final String PHASE_ID = IPhaseSet.PHASE_COLLECT; + public static final String PARM_ARTIFACT_REQUESTS = "artifactRequests"; //$NON-NLS-1$ + + public Collect(int weight) { + super(PHASE_ID, weight); + //re-balance work since postPerform will do almost all the time-consuming work + prePerformWork = 0; + mainPerformWork = 100; + postPerformWork = 1000; + } + + protected boolean isApplicable(InstallableUnitOperand op) { + return (op.second() != null && !op.second().equals(op.first())); + } + + protected List getActions(InstallableUnitOperand operand) { + IInstallableUnit unit = operand.second(); + List parsedActions = getActions(unit, phaseId); + if (parsedActions != null) + return parsedActions; + + ITouchpointType type = unit.getTouchpointType(); + if (type == null || type == ITouchpointType.NONE) + return null; + + String actionId = getActionManager().getTouchpointQualifiedActionId(phaseId, type); + ProvisioningAction action = getActionManager().getAction(actionId, null); + if (action == null) { + return null; + } + return Collections.singletonList(action); + } + + protected String getProblemMessage() { + return Messages.Phase_Collect_Error; + } + + protected IStatus completePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { + @SuppressWarnings("unchecked") + List artifactRequests = (List) parameters.get(PARM_ARTIFACT_REQUESTS); + ProvisioningContext context = (ProvisioningContext) parameters.get(PARM_CONTEXT); + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT); + IArtifactRepositoryManager repositoryManager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME); + + DownloadManager dm = new DownloadManager(context, repositoryManager); + for (IArtifactRequest[] requests : artifactRequests) { + dm.add(requests); + } + return dm.start(monitor); + } + + protected IStatus initializePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { + parameters.put(PARM_ARTIFACT_REQUESTS, new ArrayList()); + return null; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Configure.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Configure.java new file mode 100644 index 000000000..01dd52695 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Configure.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.engine.phases; + +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.engine.InstallableUnitPhase; +import org.eclipse.equinox.internal.p2.engine.Messages; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.FragmentQuery; +import org.eclipse.osgi.util.NLS; + +public class Configure extends InstallableUnitPhase { + + public Configure(int weight) { + super(IPhaseSet.PHASE_CONFIGURE, weight); + } + + protected boolean isApplicable(InstallableUnitOperand op) { + return (op.second() != null); + } + + protected List getActions(InstallableUnitOperand currentOperand) { + IInstallableUnit unit = currentOperand.second(); + if (FragmentQuery.isFragment(unit)) + return null; + return getActions(unit, phaseId); + } + + protected String getProblemMessage() { + return Messages.Phase_Configure_Error; + } + + protected IStatus initializeOperand(IProfile profile, InstallableUnitOperand operand, Map parameters, IProgressMonitor monitor) { + IInstallableUnit iu = operand.second(); + monitor.subTask(NLS.bind(Messages.Phase_Configure_Task, iu.getId())); + parameters.put(PARM_IU, iu); + + Collection artifacts = iu.getArtifacts(); + if (artifacts != null && artifacts.size() > 0) + parameters.put(PARM_ARTIFACT, artifacts.iterator().next()); + + return Status.OK_STATUS; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Install.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Install.java new file mode 100644 index 000000000..3fa36fb1e --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Install.java @@ -0,0 +1,127 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.engine.phases; + +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.engine.*; +import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.Touchpoint; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.FragmentQuery; +import org.eclipse.osgi.util.NLS; + +public class Install extends InstallableUnitPhase { + + final static class BeforeInstallEventAction extends ProvisioningAction { + + public IStatus execute(Map parameters) { + IProfile profile = (IProfile) parameters.get(PARM_PROFILE); + String phaseId = (String) parameters.get(PARM_PHASE_ID); + InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT); + ((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, operand, InstallableUnitEvent.INSTALL, getTouchpoint())); + return null; + } + + public IStatus undo(Map parameters) { + Profile profile = (Profile) parameters.get(PARM_PROFILE); + String phaseId = (String) parameters.get(PARM_PHASE_ID); + InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); + IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU); + profile.removeInstallableUnit(iu); + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT); + ((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, operand, InstallableUnitEvent.UNINSTALL, getTouchpoint())); + return null; + } + } + + final static class AfterInstallEventAction extends ProvisioningAction { + + public IStatus execute(Map parameters) { + Profile profile = (Profile) parameters.get(PARM_PROFILE); + String phaseId = (String) parameters.get(PARM_PHASE_ID); + InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); + IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU); + profile.addInstallableUnit(iu); + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT); + ((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, operand, InstallableUnitEvent.INSTALL, getTouchpoint())); + return null; + } + + public IStatus undo(Map parameters) { + IProfile profile = (IProfile) parameters.get(PARM_PROFILE); + String phaseId = (String) parameters.get(PARM_PHASE_ID); + InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT); + ((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, operand, InstallableUnitEvent.UNINSTALL, getTouchpoint())); + return null; + } + } + + private static final String PHASE_ID = IPhaseSet.PHASE_INSTALL; + + public Install(int weight) { + super(PHASE_ID, weight); + } + + protected boolean isApplicable(InstallableUnitOperand op) { + return (op.second() != null && !op.second().equals(op.first())); + } + + protected List getActions(InstallableUnitOperand currentOperand) { + //TODO: monitor.subTask(NLS.bind(Messages.Engine_Installing_IU, unit.getId())); + + ProvisioningAction beforeAction = new BeforeInstallEventAction(); + ProvisioningAction afterAction = new AfterInstallEventAction(); + + IInstallableUnit unit = currentOperand.second(); + Touchpoint touchpoint = getActionManager().getTouchpointPoint(unit.getTouchpointType()); + if (touchpoint != null) { + beforeAction.setTouchpoint(touchpoint); + afterAction.setTouchpoint(touchpoint); + } + + ArrayList actions = new ArrayList(); + actions.add(beforeAction); + + if (FragmentQuery.isFragment(unit)) { + actions.add(afterAction); + return actions; + } + + List parsedActions = getActions(unit, phaseId); + if (parsedActions != null) + actions.addAll(parsedActions); + actions.add(afterAction); + return actions; + } + + protected String getProblemMessage() { + return Messages.Phase_Install_Error; + } + + protected IStatus initializeOperand(IProfile profile, InstallableUnitOperand operand, Map parameters, IProgressMonitor monitor) { + IInstallableUnit iu = operand.second(); + monitor.subTask(NLS.bind(Messages.Phase_Install_Task, iu.getId())); + parameters.put(PARM_IU, iu); + + Collection artifacts = iu.getArtifacts(); + if (artifacts != null && artifacts.size() > 0) + parameters.put(PARM_ARTIFACT, artifacts.iterator().next()); + + return Status.OK_STATUS; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Property.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Property.java new file mode 100644 index 000000000..95d0a828f --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Property.java @@ -0,0 +1,159 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.engine.phases; + +import java.util.*; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.engine.Phase; +import org.eclipse.equinox.internal.p2.engine.Profile; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; + +public class Property extends Phase { + + public class ProfilePropertyAction extends ProvisioningAction { + + public IStatus execute(Map parameters) { + Profile profile = (Profile) parameters.get(PARM_PROFILE); + PropertyOperand propertyOperand = (PropertyOperand) parameters.get(PARM_OPERAND); + + if (propertyOperand.second() == null) + removeProfileProperty(profile, propertyOperand); + else + setProfileProperty(profile, propertyOperand, false); + + return null; + } + + public IStatus undo(Map parameters) { + Profile profile = (Profile) parameters.get(PARM_PROFILE); + PropertyOperand propertyOperand = (PropertyOperand) parameters.get(PARM_OPERAND); + + if (propertyOperand.first() == null) + removeProfileProperty(profile, propertyOperand); + else + setProfileProperty(profile, propertyOperand, true); + + return null; + } + + private void setProfileProperty(Profile profile, PropertyOperand propertyOperand, boolean undo) { + + String value = (String) (undo ? propertyOperand.first() : propertyOperand.second()); + + if (propertyOperand instanceof InstallableUnitPropertyOperand) { + InstallableUnitPropertyOperand iuPropertyOperand = (InstallableUnitPropertyOperand) propertyOperand; + profile.setInstallableUnitProperty(iuPropertyOperand.getInstallableUnit(), iuPropertyOperand.getKey(), value); + } else { + profile.setProperty(propertyOperand.getKey(), value); + } + } + + private void removeProfileProperty(Profile profile, PropertyOperand propertyOperand) { + if (propertyOperand instanceof InstallableUnitPropertyOperand) { + InstallableUnitPropertyOperand iuPropertyOperand = (InstallableUnitPropertyOperand) propertyOperand; + profile.removeInstallableUnitProperty(iuPropertyOperand.getInstallableUnit(), iuPropertyOperand.getKey()); + } else { + profile.removeProperty(propertyOperand.getKey()); + } + } + } + + public class UpdateInstallableUnitProfilePropertiesAction extends ProvisioningAction { + + // we do not need to use a memento here since the profile is not persisted unless the operation is successful + Map originalSourceProperties; + Map originalTargetProperties; + + public IStatus execute(Map parameters) { + Profile profile = (Profile) parameters.get(PARM_PROFILE); + InstallableUnitOperand iuOperand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); + + IInstallableUnit source = iuOperand.first(); + originalSourceProperties = profile.getInstallableUnitProperties(source); + + IInstallableUnit target = iuOperand.second(); + originalTargetProperties = profile.getInstallableUnitProperties(target); + + profile.addInstallableUnitProperties(target, originalSourceProperties); + profile.clearInstallableUnitProperties(source); + + return null; + } + + public IStatus undo(Map parameters) { + Profile profile = (Profile) parameters.get(PARM_PROFILE); + InstallableUnitOperand iuOperand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); + + IInstallableUnit source = iuOperand.first(); + profile.clearInstallableUnitProperties(source); + profile.addInstallableUnitProperties(source, originalSourceProperties); + + IInstallableUnit target = iuOperand.second(); + profile.clearInstallableUnitProperties(target); + profile.addInstallableUnitProperties(target, originalTargetProperties); + + return null; + } + } + + public class RemoveInstallableUnitProfilePropertiesAction extends ProvisioningAction { + + // we do not need to use a memento here since the profile is not persisted unless the operation is successful + Map originalSourceProperties; + Map originalTargetProperties; + + public IStatus execute(Map parameters) { + Profile profile = (Profile) parameters.get(PARM_PROFILE); + InstallableUnitOperand iuOperand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); + + IInstallableUnit source = iuOperand.first(); + originalSourceProperties = profile.getInstallableUnitProperties(source); + profile.clearInstallableUnitProperties(source); + + return null; + } + + public IStatus undo(Map parameters) { + Profile profile = (Profile) parameters.get(PARM_PROFILE); + InstallableUnitOperand iuOperand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); + + IInstallableUnit source = iuOperand.first(); + profile.clearInstallableUnitProperties(source); + profile.addInstallableUnitProperties(source, originalSourceProperties); + + return null; + } + } + + private static final String PHASE_ID = IPhaseSet.PHASE_PROPERTY; + + public Property(int weight) { + super(PHASE_ID, weight); + } + + protected List getActions(Operand operand) { + if (operand instanceof PropertyOperand) + return Collections. singletonList(new ProfilePropertyAction()); + + if (operand instanceof InstallableUnitOperand) { + InstallableUnitOperand iuOperand = (InstallableUnitOperand) operand; + if (iuOperand.first() != null) { + if (iuOperand.second() != null) { + return Collections. singletonList(new UpdateInstallableUnitProfilePropertiesAction()); + } + return Collections. singletonList(new RemoveInstallableUnitProfilePropertiesAction()); + } + } + return null; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Sizing.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Sizing.java new file mode 100644 index 000000000..7fba95408 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Sizing.java @@ -0,0 +1,138 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.engine.phases; + +import java.net.URI; +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.engine.*; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.ITouchpointType; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.*; + +public class Sizing extends InstallableUnitPhase { + private static final String PHASE_ID = "sizing"; //$NON-NLS-1$ + private static final String COLLECT_PHASE_ID = "collect"; //$NON-NLS-1$ + + private long sizeOnDisk; + private long dlSize; + + public Sizing(int weight, String phaseName) { + super(PHASE_ID, weight); + } + + protected boolean isApplicable(InstallableUnitOperand op) { + return (op.second() != null && !op.second().equals(op.first())); + } + + public long getDiskSize() { + return sizeOnDisk; + } + + public long getDlSize() { + return dlSize; + } + + protected List getActions(InstallableUnitOperand operand) { + IInstallableUnit unit = operand.second(); + List parsedActions = getActions(unit, COLLECT_PHASE_ID); + if (parsedActions != null) + return parsedActions; + + ITouchpointType type = unit.getTouchpointType(); + if (type == null || type == ITouchpointType.NONE) + return null; + + String actionId = getActionManager().getTouchpointQualifiedActionId(COLLECT_PHASE_ID, type); + ProvisioningAction action = getActionManager().getAction(actionId, null); + if (action == null) { + return null; + } + return Collections.singletonList(action); + } + + protected String getProblemMessage() { + return Messages.Phase_Sizing_Error; + } + + protected IStatus completePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { + @SuppressWarnings("unchecked") + List artifactRequests = (List) parameters.get(Collect.PARM_ARTIFACT_REQUESTS); + ProvisioningContext context = (ProvisioningContext) parameters.get(PARM_CONTEXT); + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT); + int statusCode = 0; + + Set artifactsToObtain = new HashSet(artifactRequests.size()); + + for (IArtifactRequest[] requests : artifactRequests) { + if (requests == null) + continue; + for (int i = 0; i < requests.length; i++) { + artifactsToObtain.add(requests[i]); + } + } + + if (monitor.isCanceled()) + return Status.CANCEL_STATUS; + + IArtifactRepositoryManager repoMgr = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME); + URI[] repositories = null; + if (context == null || context.getArtifactRepositories() == null) + repositories = repoMgr.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); + else + repositories = context.getArtifactRepositories(); + + for (IArtifactRequest artifactRequest : artifactsToObtain) { + if (monitor.isCanceled()) + break; + boolean found = false; + for (int i = 0; i < repositories.length; i++) { + IArtifactRepository repo; + try { + repo = repoMgr.loadRepository(repositories[i], monitor); + } catch (ProvisionException e) { + continue;//skip unresponsive repositories + } + if (monitor.isCanceled()) + return Status.CANCEL_STATUS; + IArtifactDescriptor[] descriptors = repo.getArtifactDescriptors(artifactRequest.getArtifactKey()); + if (descriptors.length > 0) { + if (descriptors[0].getProperty(IArtifactDescriptor.ARTIFACT_SIZE) != null) + sizeOnDisk += Long.parseLong(descriptors[0].getProperty(IArtifactDescriptor.ARTIFACT_SIZE)); + else + statusCode = ProvisionException.ARTIFACT_INCOMPLETE_SIZING; + if (descriptors[0].getProperty(IArtifactDescriptor.DOWNLOAD_SIZE) != null) + dlSize += Long.parseLong(descriptors[0].getProperty(IArtifactDescriptor.DOWNLOAD_SIZE)); + else + statusCode = ProvisionException.ARTIFACT_INCOMPLETE_SIZING; + found = true; + break; + } + } + if (!found) + // The artifact wasn't present in any repository + return new Status(IStatus.ERROR, EngineActivator.ID, ProvisionException.ARTIFACT_NOT_FOUND, Messages.Phase_Sizing_Error, null); + } + if (statusCode != 0) + return new Status(IStatus.WARNING, EngineActivator.ID, statusCode, Messages.Phase_Sizing_Warning, null); + return null; + } + + protected IStatus initializePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { + parameters.put(Collect.PARM_ARTIFACT_REQUESTS, new ArrayList()); + return null; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Unconfigure.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Unconfigure.java new file mode 100644 index 000000000..9142e300e --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Unconfigure.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.engine.phases; + +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.engine.InstallableUnitPhase; +import org.eclipse.equinox.internal.p2.engine.Messages; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.FragmentQuery; + +public class Unconfigure extends InstallableUnitPhase { + + public Unconfigure(int weight, boolean forced) { + super(IPhaseSet.PHASE_UNCONFIGURE, weight, forced); + } + + public Unconfigure(int weight) { + this(weight, false); + } + + protected boolean isApplicable(InstallableUnitOperand op) { + return (op.first() != null); + } + + protected List getActions(InstallableUnitOperand currentOperand) { + //TODO: monitor.subTask(NLS.bind(Messages.Engine_Unconfiguring_IU, unit.getId())); + + IInstallableUnit unit = currentOperand.first(); + if (FragmentQuery.isFragment(unit)) + return null; + + return getActions(unit, phaseId); + } + + protected String getProblemMessage() { + return Messages.Phase_Unconfigure_Error; + } + + protected IStatus initializeOperand(IProfile profile, InstallableUnitOperand operand, Map parameters, IProgressMonitor monitor) { + IInstallableUnit iu = operand.first(); + parameters.put(PARM_IU, iu); + + Collection artifacts = iu.getArtifacts(); + if (artifacts != null && artifacts.size() > 0) + parameters.put(PARM_ARTIFACT, artifacts.iterator().next()); + + return Status.OK_STATUS; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Uninstall.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Uninstall.java new file mode 100644 index 000000000..a58d9bbe6 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/p2/engine/phases/Uninstall.java @@ -0,0 +1,125 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.engine.phases; + +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.engine.*; +import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.Touchpoint; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.FragmentQuery; + +public class Uninstall extends InstallableUnitPhase { + + final static class BeforeUninstallEventAction extends ProvisioningAction { + public IStatus execute(Map parameters) { + IProfile profile = (IProfile) parameters.get(PARM_PROFILE); + String phaseId = (String) parameters.get(PARM_PHASE_ID); + InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT); + ((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, operand, InstallableUnitEvent.UNINSTALL, getTouchpoint())); + return null; + } + + public IStatus undo(Map parameters) { + Profile profile = (Profile) parameters.get(PARM_PROFILE); + String phaseId = (String) parameters.get(PARM_PHASE_ID); + InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); + IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU); + profile.addInstallableUnit(iu); + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT); + ((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, operand, InstallableUnitEvent.INSTALL, getTouchpoint())); + return null; + } + } + + final static class AfterUninstallEventAction extends ProvisioningAction { + public IStatus execute(Map parameters) { + Profile profile = (Profile) parameters.get(PARM_PROFILE); + String phaseId = (String) parameters.get(PARM_PHASE_ID); + InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); + IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU); + profile.removeInstallableUnit(iu); + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT); + ((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, operand, InstallableUnitEvent.UNINSTALL, getTouchpoint())); + return null; + } + + public IStatus undo(Map parameters) { + IProfile profile = (IProfile) parameters.get(PARM_PROFILE); + String phaseId = (String) parameters.get(PARM_PHASE_ID); + InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT); + ((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, operand, InstallableUnitEvent.INSTALL, getTouchpoint())); + return null; + } + } + + public Uninstall(int weight, boolean forced) { + super(IPhaseSet.PHASE_UNINSTALL, weight, forced); + } + + public Uninstall(int weight) { + this(weight, false); + } + + protected boolean isApplicable(InstallableUnitOperand op) { + return (op.first() != null && !op.first().equals(op.second())); + } + + protected List getActions(InstallableUnitOperand currentOperand) { + //TODO: monitor.subTask(NLS.bind(Messages.Engine_Uninstalling_IU, unit.getId())); + + ProvisioningAction beforeAction = new BeforeUninstallEventAction(); + ProvisioningAction afterAction = new AfterUninstallEventAction(); + + IInstallableUnit unit = currentOperand.first(); + Touchpoint touchpoint = getActionManager().getTouchpointPoint(unit.getTouchpointType()); + if (touchpoint != null) { + beforeAction.setTouchpoint(touchpoint); + afterAction.setTouchpoint(touchpoint); + } + + ArrayList actions = new ArrayList(); + actions.add(beforeAction); + + if (FragmentQuery.isFragment(unit)) { + actions.add(afterAction); + return actions; + } + + List parsedActions = getActions(unit, phaseId); + if (parsedActions != null) + actions.addAll(parsedActions); + actions.add(afterAction); + return actions; + } + + protected String getProblemMessage() { + return Messages.Phase_Uninstall_Error; + } + + protected IStatus initializeOperand(IProfile profile, InstallableUnitOperand operand, Map parameters, IProgressMonitor monitor) { + IInstallableUnit iu = operand.first(); + parameters.put(PARM_IU, iu); + + Collection artifacts = iu.getArtifacts(); + if (artifacts != null && artifacts.size() > 0) + parameters.put(PARM_ARTIFACT, artifacts.iterator().next()); + + return Status.OK_STATUS; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/BeginOperationEvent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/BeginOperationEvent.java deleted file mode 100644 index d9de82c07..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/BeginOperationEvent.java +++ /dev/null @@ -1,20 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -public class BeginOperationEvent extends TransactionEvent { - - private static final long serialVersionUID = 6389318375739324865L; - - public BeginOperationEvent(IProfile profile, PhaseSet phaseSet, Operand[] operands, IEngine engine) { - super(profile, phaseSet, operands, engine); - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/CertificateChecker.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/CertificateChecker.java deleted file mode 100644 index 8d049b9f9..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/CertificateChecker.java +++ /dev/null @@ -1,173 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.io.File; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.security.cert.Certificate; -import java.util.ArrayList; -import java.util.Iterator; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.engine.EngineActivator; -import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI; -import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI.TrustInfo; -import org.eclipse.osgi.service.security.TrustEngine; -import org.eclipse.osgi.signedcontent.*; -import org.eclipse.osgi.util.NLS; -import org.osgi.util.tracker.ServiceTracker; - -public class CertificateChecker { - private ArrayList artifacts; - private ServiceTracker trustEngineTracker; - - public CertificateChecker() { - artifacts = new ArrayList(); - trustEngineTracker = new ServiceTracker(EngineActivator.getContext(), TrustEngine.class.getName(), null); - trustEngineTracker.open(); - } - - public IStatus start() { - return checkCertificates(); - } - - private IStatus checkCertificates() { - SignedContentFactory verifierFactory = (SignedContentFactory) ServiceHelper.getService(EngineActivator.getContext(), SignedContentFactory.class.getName()); - IServiceUI serviceUI = (IServiceUI) ServiceHelper.getService(EngineActivator.getContext(), IServiceUI.class.getName()); - SignedContent content = null; - SignerInfo[] signerInfo = null; - ArrayList untrusted = new ArrayList(); - ArrayList unsigned = new ArrayList(); - ArrayList untrustedChain = new ArrayList(); - IStatus status = Status.OK_STATUS; - if (artifacts.size() == 0 || serviceUI == null) - return status; - TrustEngine trustEngine = (TrustEngine) trustEngineTracker.getService(); - for (Iterator it = artifacts.iterator(); it.hasNext();) { - File artifact = (File) it.next(); - try { - content = verifierFactory.getSignedContent(artifact); - if (!content.isSigned()) { - unsigned.add(artifact); - continue; - } - signerInfo = content.getSignerInfos(); - } catch (GeneralSecurityException e) { - return new Status(IStatus.ERROR, EngineActivator.ID, Messages.CertificateChecker_SignedContentError, e); - } catch (IOException e) { - return new Status(IStatus.ERROR, EngineActivator.ID, Messages.CertificateChecker_SignedContentIOError, e); - } - for (int i = 0; i < signerInfo.length; i++) { - Certificate[] certificateChain = signerInfo[i].getCertificateChain(); - try { - Certificate trustAnchor = trustEngine.findTrustAnchor(certificateChain); - if (trustAnchor == null) { - if (!untrusted.contains(certificateChain[0])) { - untrusted.add(certificateChain[0]); - untrustedChain.add(certificateChain); - } - } - } catch (IOException e) { - return new Status(IStatus.ERROR, EngineActivator.ID, Messages.CertificateChecker_KeystoreConnectionError, e); - } - } - } - String policy = getUnsignedContentPolicy(); - //if there is unsigned content and we should never allow it, then fail without further checking certificates - if (!unsigned.isEmpty() && EngineActivator.UNSIGNED_FAIL.equals(policy)) - return new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.CertificateChecker_UnsignedNotAllowed, unsigned)); - - String[] details; - // If we always allow unsigned content, or we don't have any, we don't prompt the user about it - if (EngineActivator.UNSIGNED_ALLOW.equals(policy) || unsigned.isEmpty()) - details = null; - else { - details = new String[unsigned.size()]; - for (int i = 0; i < details.length; i++) { - details[i] = unsigned.get(i).toString(); - } - } - Certificate[][] unTrustedCertificateChains; - if (untrusted.isEmpty()) { - unTrustedCertificateChains = null; - } else { - unTrustedCertificateChains = new Certificate[untrustedChain.size()][]; - for (int i = 0; i < untrustedChain.size(); i++) { - unTrustedCertificateChains[i] = (Certificate[]) untrustedChain.get(i); - } - } - - // If there was no unsigned content, and nothing untrusted, no need to prompt. - if (details == null && unTrustedCertificateChains == null) - return status; - - TrustInfo trustInfo = serviceUI.getTrustInfo(unTrustedCertificateChains, details); - - // If user doesn't trust unsigned content, cancel the operation - if (!trustInfo.trustUnsignedContent()) - return Status.CANCEL_STATUS; - - Certificate[] trustedCertificates = trustInfo.getTrustedCertificates(); - // If we had untrusted chains and nothing was trusted, cancel the operation - if (unTrustedCertificateChains != null && trustedCertificates == null) { - return new Status(IStatus.CANCEL, EngineActivator.ID, Messages.CertificateChecker_CertificateRejected); - } - // Anything that was trusted should be removed from the untrusted list - if (trustedCertificates != null) { - for (int i = 0; i < trustedCertificates.length; i++) { - untrusted.remove(trustedCertificates[i]); - } - } - - // If there is still untrusted content, cancel the operation - if (untrusted.size() > 0) - return new Status(IStatus.CANCEL, EngineActivator.ID, Messages.CertificateChecker_CertificateRejected); - // If we should persist the trusted certificates, add them to the trust engine - if (trustInfo.persistTrust()) { - for (int i = 0; i < trustedCertificates.length; i++) { - try { - trustEngine.addTrustAnchor(trustedCertificates[i], trustedCertificates[i].toString()); - } catch (IOException e) { - //just return an INFO so the user can proceed with the install - return new Status(IStatus.INFO, EngineActivator.ID, Messages.CertificateChecker_KeystoreConnectionError, e); - } catch (GeneralSecurityException e) { - return new Status(IStatus.INFO, EngineActivator.ID, Messages.CertificateChecker_CertificateError, e); - } - } - } - - return status; - } - - /** - * Return the policy on unsigned content. - */ - private String getUnsignedContentPolicy() { - String policy = EngineActivator.getContext().getProperty(EngineActivator.PROP_UNSIGNED_POLICY); - if (policy == null) - policy = EngineActivator.UNSIGNED_PROMPT; - return policy; - - } - - public void add(File toAdd) { - artifacts.add(toAdd); - } - - public void add(Object[] toAdd) { - for (int i = 0; i < toAdd.length; i++) { - if (toAdd[i] instanceof File) - add((File) toAdd[i]); - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/CommitOperationEvent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/CommitOperationEvent.java deleted file mode 100644 index 00f89a13d..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/CommitOperationEvent.java +++ /dev/null @@ -1,20 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -public class CommitOperationEvent extends TransactionEvent { - private static final long serialVersionUID = -523967775426133720L; - - public CommitOperationEvent(IProfile profile, PhaseSet phaseSet, Operand[] operands, IEngine engine) { - super(profile, phaseSet, operands, engine); - } - -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/DefaultPhaseSet.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/DefaultPhaseSet.java deleted file mode 100644 index 4842ad1f1..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/DefaultPhaseSet.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.util.ArrayList; -import org.eclipse.equinox.internal.p2.engine.EngineActivator; -import org.eclipse.equinox.internal.provisional.p2.engine.phases.*; - -public class DefaultPhaseSet extends PhaseSet { - - private static final boolean forcedUninstall = Boolean.valueOf(EngineActivator.getContext().getProperty("org.eclipse.equinox.p2.engine.forcedUninstall")).booleanValue(); //$NON-NLS-1$ - - public static int PHASE_CHECK_TRUST = 0x01; - public static int PHASE_COLLECT = 0x02; - public static int PHASE_CONFIGURE = 0x04; - public static int PHASE_INSTALL = 0x08; - public static int PHASE_PROPERTY = 0x10; - public static int PHASE_UNCONFIGURE = 0x20; - public static int PHASE_UNINSTALL = 0x40; - - public DefaultPhaseSet() { - this(new Phase[] {new Collect(100), new Unconfigure(10, forcedUninstall), new Uninstall(50, forcedUninstall), new Property(1), new CheckTrust(10), new Install(50), new Configure(10)}); - } - - private DefaultPhaseSet(Phase[] phases) { - super(phases); - } - - /** - * Creates a default phase set that covers all the provisioning operations. - * Phases can be specified for exclusion. - * - * @param exclude - A set of bit options that specify the phases to exclude. - * See {@link DefaultPhaseSet} for possible options - * @return the {@link PhaseSet} - */ - public static final PhaseSet createDefaultPhaseSet(int exclude) { - ArrayList phases = new ArrayList(); - if ((PHASE_COLLECT & exclude) != PHASE_COLLECT) - phases.add(new Collect(100)); - if ((PHASE_UNCONFIGURE & exclude) != PHASE_UNCONFIGURE) - phases.add(new Unconfigure(10, forcedUninstall)); - if ((PHASE_UNINSTALL & exclude) != PHASE_UNINSTALL) - phases.add(new Uninstall(50, forcedUninstall)); - if ((PHASE_PROPERTY & exclude) != PHASE_PROPERTY) - phases.add(new Property(1)); - if ((PHASE_CHECK_TRUST & exclude) != PHASE_CHECK_TRUST) - phases.add(new CheckTrust(10)); - if ((PHASE_INSTALL & exclude) != PHASE_INSTALL) - phases.add(new Install(50)); - if ((PHASE_CONFIGURE & exclude) != PHASE_CONFIGURE) - phases.add(new Configure(10)); - return new DefaultPhaseSet((Phase[]) phases.toArray(new Phase[phases.size()])); - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Engine.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Engine.java deleted file mode 100644 index 0ff2d0f12..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Engine.java +++ /dev/null @@ -1,121 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.io.File; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; - -/** - * TODO Move concrete class to non-API package - */ -public class Engine implements IEngine { - private static final String ENGINE = "engine"; //$NON-NLS-1$ - - private ActionManager actionManager; - private final IProvisioningEventBus eventBus; - - private SimpleProfileRegistry profileRegistry; - - public Engine(IProvisioningEventBus eventBus) { - this.eventBus = eventBus; - this.actionManager = new ActionManager(); - } - - private void checkArguments(IProfile iprofile, PhaseSet phaseSet, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) { - if (iprofile == null) - throw new IllegalArgumentException(Messages.null_profile); - - if (phaseSet == null) - throw new IllegalArgumentException(Messages.null_phaseset); - - if (operands == null) - throw new IllegalArgumentException(Messages.null_operands); - } - - public IStatus perform(IProfile iprofile, PhaseSet phaseSet, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) { - checkArguments(iprofile, phaseSet, operands, context, monitor); - - if (context == null) - context = new ProvisioningContext(); - - if (monitor == null) - monitor = new NullProgressMonitor(); - - Profile profile = profileRegistry.validate(iprofile); - - profileRegistry.lockProfile(profile); - try { - eventBus.publishEvent(new BeginOperationEvent(profile, phaseSet, operands, this)); - if (DebugHelper.DEBUG_ENGINE) - DebugHelper.debug(ENGINE, "Beginning engine operation for profile=" + profile.getProfileId() + " [" + profile.getTimestamp() + "]:" + DebugHelper.LINE_SEPARATOR + DebugHelper.formatOperation(phaseSet, operands, context)); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ - - File profileDataDirectory = profileRegistry.getProfileDataDirectory(profile.getProfileId()); - - EngineSession session = new EngineSession(profile, profileDataDirectory, context); - - MultiStatus result = phaseSet.perform(actionManager, session, profile, operands, context, monitor); - if (result.isOK() || result.matches(IStatus.INFO | IStatus.WARNING)) { - if (DebugHelper.DEBUG_ENGINE) - DebugHelper.debug(ENGINE, "Preparing to commit engine operation for profile=" + profile.getProfileId()); //$NON-NLS-1$ - result.merge(session.prepare(monitor)); - } - if (result.matches(IStatus.ERROR | IStatus.CANCEL)) { - if (DebugHelper.DEBUG_ENGINE) - DebugHelper.debug(ENGINE, "Rolling back engine operation for profile=" + profile.getProfileId() + ". Reason was: " + result.toString()); //$NON-NLS-1$ //$NON-NLS-2$ - IStatus status = session.rollback(actionManager, monitor, result.getSeverity()); - if (status.matches(IStatus.ERROR)) - LogHelper.log(status); - eventBus.publishEvent(new RollbackOperationEvent(profile, phaseSet, operands, this, result)); - } else { - if (DebugHelper.DEBUG_ENGINE) - DebugHelper.debug(ENGINE, "Committing engine operation for profile=" + profile.getProfileId()); //$NON-NLS-1$ - if (profile.isChanged()) - profileRegistry.updateProfile(profile); - IStatus status = session.commit(monitor); - if (status.matches(IStatus.ERROR)) - LogHelper.log(status); - eventBus.publishEvent(new CommitOperationEvent(profile, phaseSet, operands, this)); - } - //if there is only one child status, return that status instead because it will have more context - IStatus[] children = result.getChildren(); - return children.length == 1 ? children[0] : result; - } finally { - profileRegistry.unlockProfile(profile); - profile.setChanged(false); - } - } - - public void setProfileRegistry(IProfileRegistry registry) { - //we can only work with our own registry implementation - if (registry instanceof SimpleProfileRegistry) - this.profileRegistry = (SimpleProfileRegistry) registry; - } - - public void unsetProfileRegistry(IProfileRegistry registry) { - if (this.profileRegistry == registry) - this.profileRegistry = null; - } - - public IStatus validate(IProfile iprofile, PhaseSet phaseSet, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) { - checkArguments(iprofile, phaseSet, operands, context, monitor); - - if (context == null) - context = new ProvisioningContext(); - - if (monitor == null) - monitor = new NullProgressMonitor(); - - return phaseSet.validate(actionManager, iprofile, operands, context, monitor); - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/EngineSession.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/EngineSession.java deleted file mode 100644 index cfc97cb88..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/EngineSession.java +++ /dev/null @@ -1,367 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.io.File; -import java.util.*; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.engine.*; -import org.eclipse.osgi.util.NLS; - -public class EngineSession { - private static final String ENGINE_SESSION = "enginesession"; //$NON-NLS-1$ - - private static final String EMPTY_STRING = ""; //$NON-NLS-1$ - - private static class ActionsRecord { - Operand operand; - List actions = new ArrayList(); - - ActionsRecord(Operand operand) { - this.operand = operand; - } - } - - private List phaseActionRecordsPairs = new ArrayList(); - - private Phase currentPhase; - boolean currentPhaseActive; - - private List currentActionRecords; - private ActionsRecord currentRecord; - - private IProfile profile; - - private File profileDataDirectory; - - private ProvisioningContext context; - - private Set touchpoints = new HashSet(); - - public EngineSession(IProfile profile, File profileDataDirectory, ProvisioningContext context) { - this.profile = profile; - this.profileDataDirectory = profileDataDirectory; - this.context = context; - } - - public File getProfileDataDirectory() { - return profileDataDirectory; - } - - IStatus prepare(IProgressMonitor monitor) { - monitor.subTask(Messages.preparing); - MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); - for (Iterator iterator = touchpoints.iterator(); iterator.hasNext();) { - Touchpoint touchpoint = (Touchpoint) iterator.next(); - try { - status.add(touchpoint.prepare(profile)); - } catch (RuntimeException e) { - // "touchpoint.prepare" calls user code and might throw an unchecked exception - // we catch the error here to gather information on where the problem occurred. - status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.touchpoint_prepare_error, touchpoint.getClass().getName()), e)); - } catch (LinkageError e) { - // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) - status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.touchpoint_prepare_error, touchpoint.getClass().getName()), e)); - } - } - - if (status.matches(IStatus.ERROR)) { - MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.ERROR, NLS.bind(Messages.session_prepare_error, profile.getProfileId()), null); - result.merge(status); - return result; - } - return status; - } - - IStatus commit(IProgressMonitor monitor) { - monitor.subTask(Messages.committing); - MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); - phaseActionRecordsPairs.clear(); - for (Iterator iterator = touchpoints.iterator(); iterator.hasNext();) { - Touchpoint touchpoint = (Touchpoint) iterator.next(); - try { - IStatus result = touchpoint.commit(profile); - if (!result.isOK()) - status.add(result); - } catch (RuntimeException e) { - // "touchpoint.commit" calls user code and might throw an unchecked exception - // we catch the error here to gather information on where the problem occurred. - status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.touchpoint_commit_error, touchpoint.getClass().getName()), e)); - } catch (LinkageError e) { - // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) - status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.touchpoint_commit_error, touchpoint.getClass().getName()), e)); - } - } - - if (status.matches(IStatus.ERROR)) { - MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.ERROR, NLS.bind(Messages.session_commit_error, profile.getProfileId()), null); - result.merge(status); - return result; - } - return status; - } - - IStatus rollback(ActionManager actionManager, IProgressMonitor monitor, int severity) { - if (severity == IStatus.CANCEL) - monitor.subTask(Messages.rollingback_cancel); - - if (severity == IStatus.ERROR) - monitor.subTask(Messages.rollingback_error); - - MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); - - if (currentPhaseActive) { - try { - IStatus result = rollBackPhase(currentPhase, currentActionRecords, actionManager); - if (!result.isOK()) - status.add(result); - } catch (RuntimeException e) { - // "phase.prePerform and phase.postPerform" calls user code and might throw an unchecked exception - // we catch the error here to gather information on where the problem occurred. - status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.phase_undo_error, currentPhase.getClass().getName()), e)); - } catch (LinkageError e) { - // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) - status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.phase_undo_error, currentPhase.getClass().getName()), e)); - } - currentPhaseActive = false; - currentActionRecords = null; - currentRecord = null; - } - currentPhase = null; - - for (ListIterator it = phaseActionRecordsPairs.listIterator(phaseActionRecordsPairs.size()); it.hasPrevious();) { - Object[] pair = (Object[]) it.previous(); - Phase phase = (Phase) pair[0]; - List actionRecords = (List) pair[1]; - try { - final IStatus result = rollBackPhase(phase, actionRecords, actionManager); - if (!result.isOK()) - status.add(result); - } catch (RuntimeException e) { - // "phase.prePerform and phase.postPerform" calls user code and might throw an unchecked exception - // we catch the error here to gather information on where the problem occurred. - status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.phase_undo_error, phase.getClass().getName()), e)); - } catch (LinkageError e) { - // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) - status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.phase_undo_error, phase.getClass().getName()), e)); - } - } - - phaseActionRecordsPairs.clear(); - for (Iterator iterator = touchpoints.iterator(); iterator.hasNext();) { - Touchpoint touchpoint = (Touchpoint) iterator.next(); - try { - IStatus result = touchpoint.rollback(profile); - if (!result.isOK()) - status.add(result); - } catch (RuntimeException e) { - // "touchpoint.rollback" calls user code and might throw an unchecked exception - // we catch the error here to gather information on where the problem occurred. - status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.touchpoint_rollback_error, touchpoint.getClass().getName()), e)); - } catch (LinkageError e) { - // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) - status.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.touchpoint_rollback_error, touchpoint.getClass().getName()), e)); - } - } - - if (status.matches(IStatus.ERROR)) { - MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.ERROR, NLS.bind(Messages.session_commit_error, profile.getProfileId()), null); - result.merge(status); - return result; - } - return status; - } - - private IStatus rollBackPhase(Phase phase, List actionRecords, ActionManager actionManager) { - MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); - try { - phase.actionManager = actionManager; - - if (!currentPhaseActive) - phase.prePerform(result, this, profile, context, new NullProgressMonitor()); - - for (ListIterator it = actionRecords.listIterator(actionRecords.size()); it.hasPrevious();) { - ActionsRecord record = (ActionsRecord) it.previous(); - ProvisioningAction[] actions = (ProvisioningAction[]) record.actions.toArray(new ProvisioningAction[record.actions.size()]); - try { - phase.undo(result, this, profile, record.operand, actions, context); - } catch (RuntimeException e) { - // "phase.undo" calls user code and might throw an unchecked exception - // we catch the error here to gather information on where the problem occurred. - result.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.phase_undo_operand_error, phase.getClass().getName(), record.operand), e)); - } catch (LinkageError e) { - // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) - result.add(new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.phase_undo_operand_error, phase.getClass().getName(), record.operand), e)); - } - } - phase.postPerform(result, profile, context, new NullProgressMonitor()); - } finally { - phase.actionManager = null; - } - return result; - } - - void recordPhaseEnter(Phase phase) { - if (phase == null) - throw new IllegalArgumentException(Messages.null_phase); - - if (currentPhase != null) - throw new IllegalStateException(Messages.phase_started); - - currentPhase = phase; - - if (DebugHelper.DEBUG_ENGINE_SESSION) - debugPhaseEnter(phase); - } - - void recordPhaseStart(Phase phase) { - if (phase == null) - throw new IllegalArgumentException(Messages.null_phase); - - if (currentPhase != phase) - throw new IllegalArgumentException(Messages.not_current_phase); - - currentPhaseActive = true; - currentActionRecords = new ArrayList(); - } - - void recordPhaseEnd(Phase phase) { - if (currentPhase == null) - throw new IllegalStateException(Messages.phase_not_started); - - if (currentPhase != phase) - throw new IllegalArgumentException(Messages.not_current_phase); - - phaseActionRecordsPairs.add(new Object[] {currentPhase, currentActionRecords}); - currentActionRecords = null; - currentPhaseActive = false; - } - - void recordPhaseExit(Phase phase) { - if (currentPhase == null) - throw new IllegalStateException(Messages.phase_not_started); - - if (currentPhase != phase) - throw new IllegalArgumentException(Messages.not_current_phase); - - currentPhase = null; - if (DebugHelper.DEBUG_ENGINE_SESSION) - debugPhaseExit(phase); - } - - void recordOperandStart(Operand operand) { - if (operand == null) - throw new IllegalArgumentException(Messages.null_operand); - - if (currentRecord != null) - throw new IllegalStateException(Messages.operand_started); - - currentRecord = new ActionsRecord(operand); - currentActionRecords.add(currentRecord); - - if (DebugHelper.DEBUG_ENGINE_SESSION) - debugOperandStart(operand); - } - - void recordOperandEnd(Operand operand) { - if (currentRecord == null) - throw new IllegalStateException(Messages.operand_not_started); - - if (currentRecord.operand != operand) - throw new IllegalArgumentException(Messages.not_current_operand); - - currentRecord = null; - - if (DebugHelper.DEBUG_ENGINE_SESSION) - debugOperandEnd(operand); - } - - void recordActionExecute(ProvisioningAction action, Map parameters) { - if (action == null) - throw new IllegalArgumentException(Messages.null_action); - - currentRecord.actions.add(action); - - Touchpoint touchpoint = action.getTouchpoint(); - if (touchpoint != null) - touchpoints.add(touchpoint); - - if (DebugHelper.DEBUG_ENGINE_SESSION) - debugActionExecute(action, parameters); - } - - public void recordActionUndo(ProvisioningAction action, Map parameters) { - if (DebugHelper.DEBUG_ENGINE_SESSION) - debugActionUndo(action, parameters); - } - - public String getContextString(Phase phase, Operand operand, ProvisioningAction action) { - if (action instanceof ParameterizedProvisioningAction) { - ParameterizedProvisioningAction parameterizedAction = (ParameterizedProvisioningAction) action; - action = parameterizedAction.getAction(); - } - String message = NLS.bind(Messages.session_context, new Object[] {profile.getProfileId(), phase.getClass().getName(), operand.toString(), getCurrentActionId()}); - return message; - } - - public String getContextString() { - String message = NLS.bind(Messages.session_context, new Object[] {profile.getProfileId(), getCurrentPhaseId(), getCurrentOperandId(), getCurrentActionId()}); - return message; - } - - private Object getCurrentActionId() { - if (currentRecord == null || currentRecord.actions.isEmpty()) - return EMPTY_STRING; - - Object currentAction = currentRecord.actions.get(currentRecord.actions.size() - 1); - if (currentAction instanceof ParameterizedProvisioningAction) { - ParameterizedProvisioningAction parameterizedAction = (ParameterizedProvisioningAction) currentAction; - currentAction = parameterizedAction.getAction(); - } - return currentAction.getClass().getName(); - } - - private String getCurrentPhaseId() { - if (currentPhase == null) - return EMPTY_STRING; - return currentPhase.getClass().getName(); - } - - private String getCurrentOperandId() { - if (currentRecord == null) - return EMPTY_STRING; - return currentRecord.operand.toString(); - } - - private static void debugPhaseEnter(Phase phase) { - DebugHelper.debug(ENGINE_SESSION, "Entering phase: " + phase.getClass().getName()); //$NON-NLS-1$ - } - - private static void debugPhaseExit(Phase phase) { - DebugHelper.debug(ENGINE_SESSION, "Exiting phase: " + phase.getClass().getName()); //$NON-NLS-1$ - } - - private static void debugOperandStart(Operand operand) { - DebugHelper.debug(ENGINE_SESSION, "Starting processing of operand: " + operand.toString()); //$NON-NLS-1$ - } - - private static void debugOperandEnd(Operand operand) { - DebugHelper.debug(ENGINE_SESSION, "Ending processing of operand: " + operand.toString()); //$NON-NLS-1$ - } - - private static void debugActionExecute(ProvisioningAction action, Map parameters) { - DebugHelper.debug(ENGINE_SESSION, "Executing action: " + DebugHelper.formatAction(action, parameters)); //$NON-NLS-1$ - } - - private static void debugActionUndo(ProvisioningAction action, Map parameters) { - DebugHelper.debug(ENGINE_SESSION, "Undoing action: " + DebugHelper.formatAction(action, parameters)); //$NON-NLS-1$ - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IEngine.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IEngine.java deleted file mode 100644 index 16db9b281..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IEngine.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 Band XI International, LLC and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Band XI - initial API and implementation - * IBM - ongoing development - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; - -public interface IEngine { - /** - * Service name constant for the engine service. - */ - public static final String SERVICE_NAME = IEngine.class.getName(); - - public IStatus perform(IProfile profile, PhaseSet phaseSet, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor); - - public IStatus validate(IProfile iprofile, PhaseSet phaseSet, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor); -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IProfile.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IProfile.java deleted file mode 100644 index 686f36ac5..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IProfile.java +++ /dev/null @@ -1,131 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.util.Map; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; - -public interface IProfile extends IQueryable { - - /** - * Profile property constant indicating the flavor for the profile. - */ - public static final String PROP_FLAVOR = "org.eclipse.equinox.p2.flavor"; //$NON-NLS-1$ - /** - * Profile property constant indicating the install folder for the profile. - */ - public static final String PROP_INSTALL_FOLDER = "org.eclipse.equinox.p2.installFolder"; //$NON-NLS-1$ - /** - * Profile property constant indicating the configuration folder for the profile. - */ - public static final String PROP_CONFIGURATION_FOLDER = "org.eclipse.equinox.p2.configurationFolder"; //$NON-NLS-1$ - /** - * Profile property constant indicating the location of the launcher configuration file for the profile. - */ - public static final String PROP_LAUNCHER_CONFIGURATION = "org.eclipse.equinox.p2.launcherConfiguration"; //$NON-NLS-1$ - - /** - * Profile property constant indicating the installed language(s) for the profile. - */ - public static final String PROP_NL = "org.eclipse.equinox.p2.nl"; //$NON-NLS-1$ - /** - * Profile property constant for a string property indicating a user visible short - * textual description of this profile. May be empty or null, and - * generally will be for non-top level install contexts. - */ - public static final String PROP_DESCRIPTION = "org.eclipse.equinox.p2.description"; //$NON-NLS-1$ - /** - * Profile property constant for a string property indicating a user visible name of this profile. - * May be empty or null, and generally will be for non-top level - * install contexts. - */ - public static final String PROP_NAME = "org.eclipse.equinox.p2.name"; //$NON-NLS-1$ - /** - * Profile property constant indicating the list of environments - * (e.g., OS, WS, ...) in which a profile can operate. The value of the property - * is a comma-delimited string of key/value pairs. - */ - public static final String PROP_ENVIRONMENTS = "org.eclipse.equinox.p2.environments"; //$NON-NLS-1$ - /** - * Profile property constant for a boolean property indicating if the profiling - * is roaming. A roaming profile is one whose physical install location varies - * and is updated whenever it runs. - */ - public static final String PROP_ROAMING = "org.eclipse.equinox.p2.roaming"; //$NON-NLS-1$ - /** - * Profile property constant indicating the bundle pool cache location. - */ - public static final String PROP_CACHE = "org.eclipse.equinox.p2.cache"; //$NON-NLS-1$ - - /** - * Profile property constant indicating a shared read-only bundle pool cache location. - */ - public static final String PROP_SHARED_CACHE = "org.eclipse.equinox.p2.cache.shared"; //$NON-NLS-1$ - - /** - * Profile property constant for a boolean property indicating if update features should - * be installed in this profile - */ - public static final String PROP_INSTALL_FEATURES = "org.eclipse.update.install.features"; //$NON-NLS-1$ - - public String getProfileId(); - - public IProfile getParentProfile(); - - /* - * A profile is a root profile if it is not a sub-profile - * of another profile. - */ - public boolean isRootProfile(); - - public boolean hasSubProfiles(); - - public String[] getSubProfileIds(); - - /** - * Get the stored value associated with the given key. - * If the profile is a sub-profile and there is no value - * locally associated with the key, then the chain - * of parent profiles will be traversed to get an associated - * value from the nearest ancestor. - * - * null is return if none of this profile - * or its ancestors associates a value with the key. - */ - public String getProperty(String key); - - /** - * Get the stored value associated with the given key in this profile. - * No traversal of the ancestor hierarchy is done for sub-profiles. - */ - public String getLocalProperty(String key); - - public String getInstallableUnitProperty(IInstallableUnit iu, String key); - - /** - * Get an unmodifiable copy of the local properties - * associated with the profile. - * - * @return an unmodifiable copy of the Profile properties. - */ - public Map getLocalProperties(); - - public Map getProperties(); - - public Map getInstallableUnitProperties(IInstallableUnit iu); - - public long getTimestamp(); - - public Collector available(Query query, Collector collector, IProgressMonitor monitor); - -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IProfileRegistry.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IProfileRegistry.java deleted file mode 100644 index 2b7cace00..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IProfileRegistry.java +++ /dev/null @@ -1,132 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.util.Map; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; - -/** - * This encapsulates the access to the profile registry. - * It deals with persistence in a transparent way. - */ -public interface IProfileRegistry { - public static final String SELF = "_SELF_"; //$NON-NLS-1$ - /** - * Service name constant for the profile registry service. - */ - public static final String SERVICE_NAME = IProfileRegistry.class.getName(); - - /** - * Return the profile in the registry that has the given id. If it does not exist, - * then return null. - * - * @param id the profile identifier - * @return the profile or null - */ - IProfile getProfile(String id); - - /** - * Return the profile in the registry that has the given id and timestamp. If it does not exist, - * then return null. - * - * @param id the profile identifier - * @param timestamp the profile's timestamp - - * @return the profile or null - */ - IProfile getProfile(String id, long timestamp); - - /** - * Return an array of timestamps in ascending order for the profile in question. If there are none, then - * return an empty array. - * - * @return the array of timestamps - */ - long[] listProfileTimestamps(String id); - - /** - * Return an array of profiles known to this registry. If there are none, then - * return an empty array. - * - * @return the array of profiles - */ - IProfile[] getProfiles(); - - /** - * Add the given profile to this profile registry. - * - * @param id the profile id - * - * @throws ProvisionException if a profile - * with the same id is already present in the registry. - */ - IProfile addProfile(String id) throws ProvisionException; - - /** - * Add the given profile to this profile registry. - * - * @param id the profile id - * @param properties the profile properties - * - * @throws ProvisionException if a profile - * with the same id is already present in the registry. - */ - IProfile addProfile(String id, Map properties) throws ProvisionException; - - /** - * Add the given profile to this profile registry. - * - * @param id the profile id - * @param properties the profile properties - * @param parentId the id of a parent profile - * - * @throws ProvisionException if a profile - * with the same id is already present in the registry or the parentId is not a registered Profile. - */ - IProfile addProfile(String id, Map properties, String parentId) throws ProvisionException; - - /** - * Returns whether this profile registry contains a profile with the given id. - * - * @param profileId The id of the profile to search for - * @return true if this registry contains a profile with the given id, - * and false otherwise. - */ - public boolean containsProfile(String profileId); - - /** - * Remove the given profile snapshot from this profile registry. This method has no effect - * if this registry does not contain a profile with the given id and timestamp. - * The current profile cannot be removed using this method. - * - * @param id the profile to remove - * @param timestamp the timestamp of the profile to remove - * - * @throws ProvisionException if the profile with the specified id and timestamp is the current profile. - */ - void removeProfile(String id, long timestamp) throws ProvisionException; - - /** - * Remove the given profile from this profile registry. This method has no effect - * if this registry does not contain a profile with the given id. - * - * @param id the profile to remove - */ - void removeProfile(String id); - - /** - * Check if the given profile from this profile registry is up-to-date. - * - * @param profile the profile to check - * @return boolean true if the profile is current; false otherwise. - */ - public boolean isCurrent(IProfile profile); -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ISurrogateProfileHandler.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ISurrogateProfileHandler.java deleted file mode 100644 index 55f79aa71..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ISurrogateProfileHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; - -public interface ISurrogateProfileHandler { - - public abstract IProfile createProfile(String id); - - public abstract boolean isSurrogate(IProfile profile); - - public abstract Collector queryProfile(IProfile profile, Query query, Collector collector, IProgressMonitor monitor); - - public abstract boolean updateProfile(IProfile selfProfile); - -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IUProfilePropertyQuery.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IUProfilePropertyQuery.java deleted file mode 100644 index 22afdac26..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/IUProfilePropertyQuery.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IUPropertyQuery; - -/** - * A query that searches for {@link IInstallableUnit} instances that have - * a property associated with the specified profile, whose value matches the provided value. - */ -public class IUProfilePropertyQuery extends IUPropertyQuery { - private IProfile profile; - - public void setProfile(IProfile profile) { - this.profile = profile; - } - - /** - * Creates a new query on the given property name and value. - * Because the queryable for this query is typically the profile - * instance, we use a reference to the profile rather than the - * profile id for performance reasons. - */ - public IUProfilePropertyQuery(String propertyName, String propertyValue) { - super(propertyName, propertyValue); - } - - protected String getProperty(IInstallableUnit iu, String name) { - if (profile == null) - return null; - return profile.getInstallableUnitProperty(iu, name); - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitEvent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitEvent.java deleted file mode 100644 index 13f988922..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitEvent.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.util.EventObject; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; - -public class InstallableUnitEvent extends EventObject { - public static final int UNINSTALL = 0; - public static final int INSTALL = 1; - private static final long serialVersionUID = 3318712818811459886L; - - private String phaseId; - private boolean prePhase; - - private IProfile profile; - private InstallableUnitOperand operand; - private Touchpoint touchpoint; - private IStatus result; - private int type; - - public InstallableUnitEvent(String phaseId, boolean prePhase, IProfile profile, InstallableUnitOperand operand, int type, Touchpoint touchpoint) { - this(phaseId, prePhase, profile, operand, type, touchpoint, null); - } - - public InstallableUnitEvent(String phaseId, boolean prePhase, IProfile profile, InstallableUnitOperand operand, int type, Touchpoint touchpoint, IStatus result) { - super(profile); - this.phaseId = phaseId; - this.prePhase = prePhase; - this.profile = profile; - this.operand = operand; - if (type != UNINSTALL && type != INSTALL) - throw new IllegalArgumentException(Messages.InstallableUnitEvent_type_not_install_or_uninstall); - this.type = type; - this.result = result; - this.touchpoint = touchpoint; - - } - - public Touchpoint getTouchpoint() { - return touchpoint; - } - - public IProfile getProfile() { - return profile; - } - - public InstallableUnitOperand getOperand() { - return operand; - } - - public String getPhase() { - return phaseId; - } - - public boolean isPre() { - return prePhase; - } - - public boolean isPost() { - return !prePhase; - } - - public IStatus getResult() { - return (result != null ? result : Status.OK_STATUS); - } - - public boolean isInstall() { - return type == INSTALL; - } - - public boolean isUninstall() { - return type == UNINSTALL; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitOperand.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitOperand.java deleted file mode 100644 index f469d4810..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitOperand.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; - -public class InstallableUnitOperand extends Operand { - private final IInstallableUnit first; - private final IInstallableUnit second; - - /** - * Creates a new operand that represents replacing an installable unit - * with another. At least one of the provided installable units must be - * non-null. - * - * @param first The installable unit being removed, or null - * @param second The installable unit being added, or null - */ - public InstallableUnitOperand(IInstallableUnit first, IInstallableUnit second) { - //the operand must have at least one non-null units - Assert.isTrue(first != null || second != null); - this.first = first; - this.second = second; - } - - public IInstallableUnit first() { - return first; - } - - public IInstallableUnit second() { - return second; - } - - public String toString() { - return first + " --> " + second; //$NON-NLS-1$ - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitPhase.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitPhase.java deleted file mode 100644 index 8766ffdc0..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitPhase.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * WindRiver - https://bugs.eclipse.org/bugs/show_bug.cgi?id=227372 - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.util.*; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.engine.EngineActivator; -import org.eclipse.equinox.internal.p2.engine.InstructionParser; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; - -public abstract class InstallableUnitPhase extends Phase { - public static final String PARM_ARTIFACT = "artifact"; //$NON-NLS-1$ - public static final String PARM_IU = "iu"; //$NON-NLS-1$ - public static final String PARM_INSTALL_FOLDER = "installFolder"; //$NON-NLS-1$ - - protected InstallableUnitPhase(String phaseId, int weight, boolean forced) { - super(phaseId, weight, forced); - } - - protected InstallableUnitPhase(String phaseId, int weight) { - this(phaseId, weight, false); - } - - protected IStatus initializePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { - parameters.put(PARM_INSTALL_FOLDER, profile.getProperty(IProfile.PROP_INSTALL_FOLDER)); - return super.initializePhase(monitor, profile, parameters); - } - - protected IStatus initializeOperand(IProfile profile, Operand operand, Map parameters, IProgressMonitor monitor) { - InstallableUnitOperand iuOperand = (InstallableUnitOperand) operand; - MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); - mergeStatus(status, initializeOperand(profile, iuOperand, parameters, monitor)); - IInstallableUnit unit = (IInstallableUnit) parameters.get(PARM_IU); - if (unit != null) { - Touchpoint touchpoint = getActionManager().getTouchpointPoint(unit.getTouchpointType()); - if (touchpoint != null) { - parameters.put(PARM_TOUCHPOINT, touchpoint); - } - } - mergeStatus(status, super.initializeOperand(profile, operand, parameters, monitor)); - return status; - } - - protected IStatus initializeOperand(IProfile profile, InstallableUnitOperand operand, Map parameters, IProgressMonitor monitor) { - return Status.OK_STATUS; - } - - protected IStatus completeOperand(IProfile profile, Operand operand, Map parameters, IProgressMonitor monitor) { - InstallableUnitOperand iuOperand = (InstallableUnitOperand) operand; - - MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); - mergeStatus(status, super.completeOperand(profile, iuOperand, parameters, monitor)); - mergeStatus(status, completeOperand(profile, iuOperand, parameters, monitor)); - return status; - } - - protected IStatus completeOperand(IProfile profile, InstallableUnitOperand operand, Map parameters, IProgressMonitor monitor) { - return Status.OK_STATUS; - } - - final protected ProvisioningAction[] getActions(Operand operand) { - if (!(operand instanceof InstallableUnitOperand)) - return null; - - InstallableUnitOperand iuOperand = (InstallableUnitOperand) operand; - return getActions(iuOperand); - } - - protected abstract ProvisioningAction[] getActions(InstallableUnitOperand operand); - - final public boolean isApplicable(Operand operand) { - if (!(operand instanceof InstallableUnitOperand)) - return false; - - InstallableUnitOperand iuOperand = (InstallableUnitOperand) operand; - return isApplicable(iuOperand); - } - - protected boolean isApplicable(InstallableUnitOperand operand) { - return true; - } - - protected final ProvisioningAction[] getActions(IInstallableUnit unit, String key) { - ITouchpointInstruction[] instructions = getInstructions(unit, key); - if (instructions == null || instructions.length == 0) - return null; - - List actions = new ArrayList(); - InstructionParser instructionParser = new InstructionParser(getActionManager()); - for (int i = 0; i < instructions.length; i++) { - actions.addAll(Arrays.asList(instructionParser.parseActions(instructions[i], unit.getTouchpointType()))); - } - return (ProvisioningAction[]) actions.toArray(new ProvisioningAction[actions.size()]); - } - - private final static ITouchpointInstruction[] getInstructions(IInstallableUnit unit, String key) { - ITouchpointData[] data = unit.getTouchpointData(); - if (data == null) - return null; - - ArrayList matches = new ArrayList(data.length); - for (int i = 0; i < data.length; i++) { - ITouchpointInstruction instructions = data[i].getInstruction(key); - if (instructions != null) - matches.add(instructions); - } - - ITouchpointInstruction[] result = (ITouchpointInstruction[]) matches.toArray(new ITouchpointInstruction[matches.size()]); - return result; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitPropertyOperand.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitPropertyOperand.java deleted file mode 100644 index 0e299f187..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/InstallableUnitPropertyOperand.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; - -public class InstallableUnitPropertyOperand extends PropertyOperand { - private final IInstallableUnit iu; - - /** - * Creates a new operand that represents replacing a property value associated - * with an IU with another. At least one of the provided property values must be - * non-null. - * - * @param iu The IInstallableUnit with which the property is associated - * @param key The key of the property being modified - * @param first The property value being removed, or null - * @param second The property value being added, or null - */ - public InstallableUnitPropertyOperand(IInstallableUnit iu, String key, Object first, Object second) { - super(key, first, second); - //the iu must be specified. - Assert.isTrue(iu != null); - this.iu = iu; - } - - public IInstallableUnit getInstallableUnit() { - return iu; - } - - public String toString() { - return "[IInstallableUnit property for " + iu.toString() + "] " + super.toString(); //$NON-NLS-1$ //$NON-NLS-2$ - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Memento.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Memento.java deleted file mode 100644 index eb4c15330..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Memento.java +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.util.*; - -public class Memento { - private static final long serialVersionUID = 3257399736837461585L; - private static final Collection simples = Arrays.asList(new Class[] {String.class, Integer.class, Long.class, Float.class, Double.class, Byte.class, Short.class, Character.class, Boolean.class}); - private static final Collection simpleArrays = Arrays.asList(new Class[] {String[].class, Integer[].class, Long[].class, Float[].class, Double[].class, Byte[].class, Short[].class, Character[].class, Boolean[].class}); - private static final Collection primitiveArrays = Arrays.asList(new Class[] {long[].class, int[].class, short[].class, char[].class, byte[].class, double[].class, float[].class, boolean[].class}); - - Map mementoMap = new HashMap(); - - public Object remove(String key) { - if (key == null) - throw new NullPointerException(); - - // TODO: persist change - return mementoMap.remove(key); - } - - public Object put(String key, Object value) { - if (key == null) - throw new NullPointerException(); - - validateValue(value); - - // TODO: persist change - return mementoMap.put(key, value); - } - - public Object get(String key) { - if (key == null) - throw new NullPointerException(); - - return mementoMap.get(key); - } - - public Enumeration getKeys() { - return new Enumeration() { - Iterator keysIterator = mementoMap.keySet().iterator(); - - public boolean hasMoreElements() { - return keysIterator.hasNext(); - } - - public Object nextElement() { - return keysIterator.next(); - } - }; - } - - private static void validateValue(Object value) { - if (value == null) - return; - - Class clazz = value.getClass(); - - if (simples.contains(clazz)) - return; - - if (simpleArrays.contains(clazz) || primitiveArrays.contains(clazz)) - return; - - throw new IllegalArgumentException(clazz.getName()); - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Messages.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Messages.java deleted file mode 100644 index b4aef5af8..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Messages.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import org.eclipse.osgi.util.NLS; - -//TODO Shouldn't have messages class in API package -public class Messages extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.equinox.internal.provisional.p2.engine.messages"; //$NON-NLS-1$ - public static String CertificateChecker_CertificateError; - public static String CertificateChecker_CertificateRejected; - public static String CertificateChecker_KeystoreConnectionError; - public static String CertificateChecker_SignedContentIOError; - public static String CertificateChecker_SignedContentError; - public static String CertificateChecker_UnsignedNotAllowed; - public static String not_current_phase; - public static String null_operands; - public static String null_phase; - public static String null_phases; - public static String null_phaseset; - public static String null_profile; - public static String phase_error; - public static String phase_not_started; - public static String phase_started; - public static String phaseid_not_positive; - public static String phaseid_not_set; - public static String Engine_Operation_Canceled_By_User; - public static String InstallableUnitEvent_type_not_install_or_uninstall; - public static String touchpoint_prepare_error; - public static String touchpoint_commit_error; - public static String touchpoint_rollback_error; - public static String phase_undo_error; - public static String phase_undo_operand_error; - public static String session_prepare_error; - public static String session_commit_error; - public static String null_operand; - public static String operand_started; - public static String operand_not_started; - public static String not_current_operand; - public static String null_action; - public static String session_context; - public static String action_not_found; - public static String actions_not_found; - public static String preparing; - public static String committing; - public static String rollingback_cancel; - public static String rollingback_error; - public static String action_undo_error; - public static String forced_action_execute_error; - - static { - // initialize resource bundle - NLS.initializeMessages(BUNDLE_NAME, Messages.class); - } - - private Messages() { - // - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/MissingAction.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/MissingAction.java deleted file mode 100644 index b8bfe06b9..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/MissingAction.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - -import java.util.Map; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.osgi.util.NLS; - -public class MissingAction extends ProvisioningAction { - - private String actionId; - private VersionRange versionRange; - - public MissingAction(String actionId, VersionRange versionRange) { - this.actionId = actionId; - this.versionRange = versionRange; - } - - public String getActionId() { - return actionId; - } - - public VersionRange getVersionRange() { - return versionRange; - } - - public IStatus execute(Map parameters) { - throw new IllegalArgumentException(NLS.bind(Messages.action_not_found, actionId + (versionRange == null ? "" : "/" + versionRange.toString()))); //$NON-NLS-1$ //$NON-NLS-2$ - } - - public IStatus undo(Map parameters) { - // do nothing as we want this action to undo successfully - return Status.OK_STATUS; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/MissingActionsException.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/MissingActionsException.java deleted file mode 100644 index 0c68603df..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/MissingActionsException.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.osgi.util.NLS; - -public class MissingActionsException extends ProvisionException { - - private static final long serialVersionUID = 8617693596359747490L; - private final MissingAction[] missingActions; - - public MissingActionsException(MissingAction[] missingActions) { - super(getMissingActionsMessage(missingActions)); - this.missingActions = missingActions; - } - - private static String getMissingActionsMessage(MissingAction[] missingActions) { - - if (missingActions.length == 0) - throw new IllegalArgumentException("Bad exception: No missing actions"); //$NON-NLS-1$ - - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < missingActions.length; i++) { - MissingAction missingAction = missingActions[i]; - buffer.append(missingAction.getActionId()); - if (missingAction.getVersionRange() != null) { - buffer.append("/"); //$NON-NLS-1$ - buffer.append(missingAction.getVersionRange().toString()); - } - if (i + 1 != missingActions.length) - buffer.append(", "); //$NON-NLS-1$ - } - - return NLS.bind(Messages.actions_not_found, buffer.toString()); - } - - public MissingAction[] getMissingActions() { - return missingActions; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Operand.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Operand.java deleted file mode 100644 index fa7b27807..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Operand.java +++ /dev/null @@ -1,20 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -/** - * The common base class for engine operands. - * - * @see IEngine#perform(IProfile, PhaseSet, Operand[], ProvisioningContext, org.eclipse.core.runtime.IProgressMonitor) - */ -public class Operand { - // marker class -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Phase.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Phase.java deleted file mode 100644 index 1262df290..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Phase.java +++ /dev/null @@ -1,318 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.util.*; -import java.util.Map.Entry; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.p2.engine.ActionManager; -import org.eclipse.equinox.internal.p2.engine.EngineActivator; -import org.eclipse.osgi.util.NLS; - -public abstract class Phase { - protected static final String PARM_OPERAND = "operand"; //$NON-NLS-1$ - protected static final String PARM_PHASE_ID = "phaseId"; //$NON-NLS-1$ - protected static final String PARM_PROFILE = "profile"; //$NON-NLS-1$ - protected static final String PARM_PROFILE_DATA_DIRECTORY = "profileDataDirectory"; //$NON-NLS-1$ - protected static final String PARM_CONTEXT = "context"; //$NON-NLS-1$ - protected static final String PARM_FORCED = "forced"; //$NON-NLS-1$ - protected static final String PARM_TOUCHPOINT = "touchpoint"; //$NON-NLS-1$ - - protected final String phaseId; - protected final int weight; - protected final boolean forced; - protected int prePerformWork = 1000; - protected int mainPerformWork = 10000; - protected int postPerformWork = 1000; - private Map operandParameters = null; - private Map phaseParameters = new HashMap(); - private Map touchpointToTouchpointPhaseParameters = new HashMap(); - private Map touchpointToTouchpointOperandParameters = new HashMap(); - ActionManager actionManager; // injected from phaseset - - protected Phase(String phaseId, int weight, boolean forced) { - if (phaseId == null || phaseId.length() == 0) - throw new IllegalArgumentException(Messages.phaseid_not_set); - if (weight <= 0) - throw new IllegalArgumentException(Messages.phaseid_not_positive); - this.weight = weight; - this.phaseId = phaseId; - this.forced = forced; - } - - protected Phase(String phaseId, int weight) { - this(phaseId, weight, false); - } - - final protected ActionManager getActionManager() { - return actionManager; - } - - public String toString() { - return getClass().getName() + " - " + this.weight; //$NON-NLS-1$ - } - - public final void perform(MultiStatus status, EngineSession session, IProfile profile, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) { - SubMonitor subMonitor = SubMonitor.convert(monitor, prePerformWork + mainPerformWork + postPerformWork); - session.recordPhaseEnter(this); - prePerform(status, session, profile, context, subMonitor.newChild(prePerformWork)); - if (status.matches(IStatus.ERROR | IStatus.CANCEL)) - return; - session.recordPhaseStart(this); - - subMonitor.setWorkRemaining(mainPerformWork + postPerformWork); - mainPerform(status, session, profile, operands, context, subMonitor.newChild(mainPerformWork)); - if (status.matches(IStatus.ERROR | IStatus.CANCEL)) - return; - - session.recordPhaseEnd(this); - subMonitor.setWorkRemaining(postPerformWork); - postPerform(status, profile, context, subMonitor.newChild(postPerformWork)); - phaseParameters.clear(); - if (status.matches(IStatus.ERROR | IStatus.CANCEL)) - return; - session.recordPhaseExit(this); - subMonitor.done(); - } - - void prePerform(MultiStatus status, EngineSession session, IProfile profile, ProvisioningContext context, IProgressMonitor monitor) { - phaseParameters.put(PARM_PROFILE, profile); - phaseParameters.put(PARM_PROFILE_DATA_DIRECTORY, session.getProfileDataDirectory()); - phaseParameters.put(PARM_CONTEXT, context); - phaseParameters.put(PARM_PHASE_ID, phaseId); - phaseParameters.put(PARM_FORCED, Boolean.toString(forced)); - mergeStatus(status, initializePhase(monitor, profile, phaseParameters)); - } - - private void mainPerform(MultiStatus status, EngineSession session, IProfile profile, Operand[] operands, ProvisioningContext context, SubMonitor subMonitor) { - subMonitor.beginTask("", operands.length); //$NON-NLS-1$ - for (int i = 0; i < operands.length; i++) { - subMonitor.setWorkRemaining(operands.length - i); - if (subMonitor.isCanceled()) - throw new OperationCanceledException(); - Operand operand = operands[i]; - if (!isApplicable(operand)) - continue; - - session.recordOperandStart(operand); - ProvisioningAction[] actions = getActions(operand); - operandParameters = new HashMap(phaseParameters); - operandParameters.put(PARM_OPERAND, operand); - mergeStatus(status, initializeOperand(profile, operand, operandParameters, subMonitor)); - if (status.matches(IStatus.ERROR | IStatus.CANCEL)) { - operandParameters = null; - return; - } - - Touchpoint operandTouchpoint = (Touchpoint) operandParameters.get(PARM_TOUCHPOINT); - if (operandTouchpoint != null) { - mergeStatus(status, initializeTouchpointParameters(profile, operand, operandTouchpoint, subMonitor)); - if (status.matches(IStatus.ERROR | IStatus.CANCEL)) - return; - - operandParameters = (Map) touchpointToTouchpointOperandParameters.get(operandTouchpoint); - } - - operandParameters = Collections.unmodifiableMap(operandParameters); - if (actions != null) { - for (int j = 0; j < actions.length; j++) { - ProvisioningAction action = actions[j]; - Map parameters = operandParameters; - Touchpoint touchpoint = action.getTouchpoint(); - if (touchpoint != null) { - mergeStatus(status, initializeTouchpointParameters(profile, operand, touchpoint, subMonitor)); - if (status.matches(IStatus.ERROR | IStatus.CANCEL)) - return; - - parameters = (Map) touchpointToTouchpointOperandParameters.get(touchpoint); - } - IStatus actionStatus = null; - try { - session.recordActionExecute(action, parameters); - actionStatus = action.execute(parameters); - } catch (RuntimeException e) { - if (!forced) - throw e; - // "action.execute" calls user code and might throw an unchecked exception - // we catch the error here to gather information on where the problem occurred. - actionStatus = new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.forced_action_execute_error, action.getClass().getName()), e); - } catch (LinkageError e) { - if (!forced) - throw e; - // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) - actionStatus = new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.forced_action_execute_error, action.getClass().getName()), e); - } - if (forced && actionStatus != null && actionStatus.matches(IStatus.ERROR)) { - MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.ERROR, getProblemMessage(), null); - result.add(new Status(IStatus.ERROR, EngineActivator.ID, session.getContextString(this, operand, action), null)); - LogHelper.log(result); - actionStatus = Status.OK_STATUS; - } - mergeStatus(status, actionStatus); - if (status.matches(IStatus.ERROR | IStatus.CANCEL)) - return; - } - } - mergeStatus(status, touchpointCompleteOperand(profile, operand, operandParameters, subMonitor)); - mergeStatus(status, completeOperand(profile, operand, operandParameters, subMonitor)); - if (status.matches(IStatus.ERROR | IStatus.CANCEL)) - return; - operandParameters = null; - session.recordOperandEnd(operand); - subMonitor.worked(1); - } - } - - private IStatus initializeTouchpointParameters(IProfile profile, Operand operand, Touchpoint touchpoint, IProgressMonitor monitor) { - if (touchpointToTouchpointOperandParameters.containsKey(touchpoint)) - return Status.OK_STATUS; - - Map touchpointPhaseParameters = (Map) touchpointToTouchpointPhaseParameters.get(touchpoint); - if (touchpointPhaseParameters == null) { - touchpointPhaseParameters = new HashMap(phaseParameters); - IStatus status = touchpoint.initializePhase(monitor, profile, phaseId, touchpointPhaseParameters); - if (status != null && status.matches(IStatus.ERROR | IStatus.CANCEL)) - return status; - touchpointToTouchpointPhaseParameters.put(touchpoint, touchpointPhaseParameters); - } - - Map touchpointOperandParameters = new HashMap(touchpointPhaseParameters); - touchpointOperandParameters.putAll(operandParameters); - IStatus status = touchpoint.initializeOperand(profile, operand, touchpointOperandParameters); - if (status != null && status.matches(IStatus.ERROR | IStatus.CANCEL)) - return status; - touchpointToTouchpointOperandParameters.put(touchpoint, touchpointOperandParameters); - return Status.OK_STATUS; - } - - /** - * Merges a given IStatus into a MultiStatus - */ - protected static void mergeStatus(MultiStatus multi, IStatus status) { - if (status != null && !status.isOK()) - multi.merge(status); - } - - void postPerform(MultiStatus status, IProfile profile, ProvisioningContext context, IProgressMonitor monitor) { - mergeStatus(status, touchpointCompletePhase(monitor, profile, phaseParameters)); - mergeStatus(status, completePhase(monitor, profile, phaseParameters)); - } - - void undo(MultiStatus status, EngineSession session, IProfile profile, Operand operand, ProvisioningAction[] actions, ProvisioningContext context) { - if (operandParameters == null) { - operandParameters = new HashMap(phaseParameters); - operandParameters.put(PARM_OPERAND, operand); - mergeStatus(status, initializeOperand(profile, operand, operandParameters, new NullProgressMonitor())); - Touchpoint operandTouchpoint = (Touchpoint) operandParameters.get(PARM_TOUCHPOINT); - if (operandTouchpoint != null) { - mergeStatus(status, initializeTouchpointParameters(profile, operand, operandTouchpoint, new NullProgressMonitor())); - if (status.matches(IStatus.ERROR | IStatus.CANCEL)) - return; - - operandParameters = (Map) touchpointToTouchpointOperandParameters.get(operandTouchpoint); - } - operandParameters = Collections.unmodifiableMap(operandParameters); - } - for (int j = 0; j < actions.length; j++) { - ProvisioningAction action = actions[j]; - Map parameters = operandParameters; - Touchpoint touchpoint = action.getTouchpoint(); - if (touchpoint != null) { - mergeStatus(status, initializeTouchpointParameters(profile, operand, touchpoint, new NullProgressMonitor())); - if (status.matches(IStatus.ERROR)) - return; - - parameters = (Map) touchpointToTouchpointOperandParameters.get(touchpoint); - } - IStatus actionStatus = null; - try { - session.recordActionUndo(action, parameters); - actionStatus = action.undo(parameters); - } catch (RuntimeException e) { - // "action.undo" calls user code and might throw an unchecked exception - // we catch the error here to gather information on where the problem occurred. - actionStatus = new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.action_undo_error, action.getClass().getName()), e); - } catch (LinkageError e) { - // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) - actionStatus = new Status(IStatus.ERROR, EngineActivator.ID, NLS.bind(Messages.action_undo_error, action.getClass().getName()), e); - } - if (actionStatus != null && actionStatus.matches(IStatus.ERROR)) { - MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.ERROR, getProblemMessage(), null); - result.add(new Status(IStatus.ERROR, EngineActivator.ID, session.getContextString(this, operand, action), null)); - result.merge(actionStatus); - } - } - mergeStatus(status, touchpointCompleteOperand(profile, operand, operandParameters, new NullProgressMonitor())); - mergeStatus(status, completeOperand(profile, operand, operandParameters, new NullProgressMonitor())); - operandParameters = null; - } - - public boolean isApplicable(Operand operand) { - return true; - } - - protected IStatus initializePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { - return Status.OK_STATUS; - } - - protected IStatus completePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { - return Status.OK_STATUS; - } - - IStatus touchpointCompletePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { - if (touchpointToTouchpointPhaseParameters.isEmpty()) - return Status.OK_STATUS; - - MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); - for (Iterator it = touchpointToTouchpointPhaseParameters.entrySet().iterator(); it.hasNext();) { - Entry entry = (Entry) it.next(); - Touchpoint touchpoint = (Touchpoint) entry.getKey(); - Map touchpointParameters = (Map) entry.getValue(); - mergeStatus(status, touchpoint.completePhase(monitor, profile, phaseId, touchpointParameters)); - } - touchpointToTouchpointPhaseParameters.clear(); - return status; - } - - protected IStatus completeOperand(IProfile profile, Operand operand, Map parameters, IProgressMonitor monitor) { - return Status.OK_STATUS; - } - - IStatus touchpointCompleteOperand(IProfile profile, Operand operand, Map parameters, IProgressMonitor monitor) { - if (touchpointToTouchpointOperandParameters.isEmpty()) - return Status.OK_STATUS; - - MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); - for (Iterator it = touchpointToTouchpointOperandParameters.entrySet().iterator(); it.hasNext();) { - Entry entry = (Entry) it.next(); - Touchpoint touchpoint = (Touchpoint) entry.getKey(); - Map touchpointParameters = (Map) entry.getValue(); - mergeStatus(status, touchpoint.completeOperand(profile, operand, touchpointParameters)); - } - touchpointToTouchpointOperandParameters.clear(); - return status; - } - - protected IStatus initializeOperand(IProfile profile, Operand operand, Map parameters, IProgressMonitor monitor) { - return Status.OK_STATUS; - } - - protected abstract ProvisioningAction[] getActions(Operand operand); - - /** - * Returns a human-readable message to be displayed in case of an error performing - * this phase. Subclasses should override. - */ - protected String getProblemMessage() { - return NLS.bind(Messages.phase_error, getClass().getName()); - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/PhaseSet.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/PhaseSet.java deleted file mode 100644 index 2c24a2fb0..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/PhaseSet.java +++ /dev/null @@ -1,151 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.util.HashSet; -import java.util.Set; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.engine.ActionManager; -import org.eclipse.equinox.internal.p2.engine.EngineActivator; -import org.eclipse.osgi.util.NLS; - -public abstract class PhaseSet { - private final Phase[] phases; - - public PhaseSet(Phase[] phases) { - if (phases == null) - throw new IllegalArgumentException(Messages.null_phases); - - this.phases = phases; - } - - public final MultiStatus perform(ActionManager actionManager, EngineSession session, IProfile profile, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) { - MultiStatus status = new MultiStatus(EngineActivator.ID, IStatus.OK, null, null); - int[] weights = getProgressWeights(operands); - int totalWork = getTotalWork(weights); - SubMonitor pm = SubMonitor.convert(monitor, totalWork); - try { - for (int i = 0; i < phases.length; i++) { - if (pm.isCanceled()) { - status.add(Status.CANCEL_STATUS); - return status; - } - Phase phase = phases[i]; - phase.actionManager = actionManager; - try { - phase.perform(status, session, profile, operands, context, pm.newChild(weights[i])); - } catch (OperationCanceledException e) { - // propagate operation cancellation - status.add(new Status(IStatus.CANCEL, EngineActivator.ID, e.getMessage(), e)); - } catch (RuntimeException e) { - // "perform" calls user code and might throw an unchecked exception - // we catch the error here to gather information on where the problem occurred. - status.add(new Status(IStatus.ERROR, EngineActivator.ID, e.getMessage(), e)); - } catch (LinkageError e) { - // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) - status.add(new Status(IStatus.ERROR, EngineActivator.ID, e.getMessage(), e)); - } finally { - phase.actionManager = null; - } - if (status.matches(IStatus.CANCEL)) { - MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.CANCEL, Messages.Engine_Operation_Canceled_By_User, null); - result.merge(status); - return result; - } else if (status.matches(IStatus.ERROR)) { - MultiStatus result = new MultiStatus(EngineActivator.ID, IStatus.ERROR, phase.getProblemMessage(), null); - result.add(new Status(IStatus.ERROR, EngineActivator.ID, session.getContextString(), null)); - result.merge(status); - return result; - } - } - } finally { - pm.done(); - } - return status; - } - - public final IStatus validate(ActionManager actionManager, IProfile profile, Operand[] operands, ProvisioningContext context, IProgressMonitor monitor) { - Set missingActions = new HashSet(); - for (int i = 0; i < phases.length; i++) { - Phase phase = phases[i]; - phase.actionManager = actionManager; - try { - for (int j = 0; j < operands.length; j++) { - Operand operand = operands[j]; - try { - if (!phase.isApplicable(operand)) - continue; - - ProvisioningAction[] actions = phase.getActions(operand); - if (actions == null) - continue; - for (int k = 0; k < actions.length; k++) { - ProvisioningAction action = actions[k]; - if (action instanceof MissingAction) - missingActions.add(action); - } - } catch (RuntimeException e) { - // "perform" calls user code and might throw an unchecked exception - // we catch the error here to gather information on where the problem occurred. - return new Status(IStatus.ERROR, EngineActivator.ID, e.getMessage() + " " + getContextString(profile, phase, operand), e); //$NON-NLS-1$ - } catch (LinkageError e) { - // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) - return new Status(IStatus.ERROR, EngineActivator.ID, e.getMessage() + " " + getContextString(profile, phase, operand), e); //$NON-NLS-1$ - } - } - } finally { - phase.actionManager = null; - } - } - if (!missingActions.isEmpty()) { - MissingAction[] missingActionsArray = (MissingAction[]) missingActions.toArray(new MissingAction[missingActions.size()]); - MissingActionsException exception = new MissingActionsException(missingActionsArray); - return (new Status(IStatus.ERROR, EngineActivator.ID, exception.getMessage(), exception)); - } - return Status.OK_STATUS; - } - - private String getContextString(IProfile profile, Phase phase, Operand operand) { - return NLS.bind(Messages.session_context, new Object[] {profile.getProfileId(), phase.getClass().getName(), operand.toString(), ""}); //$NON-NLS-1$ - } - - private int getTotalWork(int[] weights) { - int sum = 0; - for (int i = 0; i < weights.length; i++) - sum += weights[i]; - return sum; - } - - private int[] getProgressWeights(Operand[] operands) { - int[] weights = new int[phases.length]; - for (int i = 0; i < phases.length; i += 1) { - if (operands.length > 0) - //alter weights according to the number of operands applicable to that phase - weights[i] = (phases[i].weight * countApplicable(phases[i], operands) / operands.length); - else - weights[i] = phases[i].weight; - } - return weights; - } - - private int countApplicable(Phase phase, Operand[] operands) { - int count = 0; - for (int i = 0; i < operands.length; i++) { - if (phase.isApplicable(operands[i])) - count++; - } - return count; - } - - public Phase[] getPhases() { - return phases; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProfileEvent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProfileEvent.java deleted file mode 100644 index d96796f2f..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProfileEvent.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.util.EventObject; - -/** - * @noextend This class is not intended to be subclassed by clients. - */ -public class ProfileEvent extends EventObject { - private static final long serialVersionUID = 3082402920617281765L; - - public static final byte ADDED = 0; - public static final byte REMOVED = 1; - public static final byte CHANGED = 2; - - private byte reason; - - public ProfileEvent(String profileId, byte reason) { - super(profileId); - this.reason = reason; - } - - public byte getReason() { - return reason; - } - - public String getProfileId() { - return (String) getSource(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProfileScope.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProfileScope.java deleted file mode 100644 index 70d72d639..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProfileScope.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import org.eclipse.core.internal.preferences.PreferencesService; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.preferences.IEclipsePreferences; -import org.eclipse.core.runtime.preferences.IScopeContext; - -public final class ProfileScope implements IScopeContext { - - /* - * String constant (value of "profile") used for the - * scope name for this preference scope. - */ - public static final String SCOPE = "profile"; //$NON-NLS-1$ - - private String profileId; - - /* - * Create and return a new profile scope for the given profile. The given - * profile must not be null. - */ - public ProfileScope(String profileId) { - super(); - if (profileId == null) - throw new IllegalArgumentException(); - this.profileId = profileId; - } - - public IPath getLocation() { - // Null returned as the location should only be used when the profile is locked - return null; - } - - public String getName() { - return SCOPE; - } - - /* - * Default path hierarchy for profile nodes is /profile//. - * - * @see org.eclipse.core.runtime.preferences.IScopeContext#getNode(java.lang.String) - */ - public IEclipsePreferences getNode(String qualifier) { - if (qualifier == null) - throw new IllegalArgumentException(); - return (IEclipsePreferences) PreferencesService.getDefault().getRootNode().node(getName()).node(profileId).node(qualifier); - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (!(obj instanceof ProfileScope)) - return false; - ProfileScope other = (ProfileScope) obj; - return profileId.equals(other.profileId); - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - return super.hashCode() + profileId.hashCode(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/PropertyOperand.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/PropertyOperand.java deleted file mode 100644 index 24c536e66..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/PropertyOperand.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import org.eclipse.core.runtime.Assert; - -public class PropertyOperand extends Operand { - private final Object first; - private final Object second; - private final String key; - - /** - * Creates a new operand that represents replacing a property value - * with another. At least one of the provided property values must be - * non-null. - * - * @param key The key of the property being modified - * @param first The property value being removed, or null - * @param second The property value being added, or null - */ - public PropertyOperand(String key, Object first, Object second) { - //the operand must specify have a key and have at least one non-null value - Assert.isTrue(key != null && (first != null || second != null)); - this.first = first; - this.second = second; - this.key = key; - } - - public Object first() { - return first; - } - - public Object second() { - return second; - } - - public String getKey() { - return key; - } - - public String toString() { - return key + " = " + first + " --> " + second; //$NON-NLS-1$ //$NON-NLS-2$ - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProvisioningAction.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProvisioningAction.java deleted file mode 100644 index dc1b05224..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProvisioningAction.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.util.Map; -import org.eclipse.core.runtime.IStatus; - -public abstract class ProvisioningAction { - - private Memento memento = new Memento(); - private Touchpoint touchpoint; - - protected Memento getMemento() { - return memento; - } - - public abstract IStatus execute(Map parameters); - - public abstract IStatus undo(Map parameters); - - // TODO: these probably should not be visible - public void setTouchpoint(Touchpoint touchpoint) { - this.touchpoint = touchpoint; - } - - public Touchpoint getTouchpoint() { - return touchpoint; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProvisioningContext.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProvisioningContext.java deleted file mode 100644 index 5e021c3d6..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/ProvisioningContext.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * WindRiver - https://bugs.eclipse.org/bugs/show_bug.cgi?id=227372 - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.net.URI; -import java.util.*; - -public class ProvisioningContext { - private URI[] metadataRepositories; //metadata repositories to consult - private URI[] artifactRepositories; //artifact repositories to consult - private Properties properties = new Properties(); - private List extraIUs = new ArrayList(); - private Collection additionalRequirements; - - public ProvisioningContext() { - // null repos means look at them all - metadataRepositories = null; - artifactRepositories = null; - } - - public ProvisioningContext(URI[] metadataRepositories) { - this.metadataRepositories = metadataRepositories; - } - - /** - * Artifact repositories to consult when performing an operation. - * @param artifactRepositories array of URLs - */ - public void setArtifactRepositories(URI[] artifactRepositories) { - this.artifactRepositories = artifactRepositories; - } - - public URI[] getMetadataRepositories() { - return metadataRepositories; - } - - public URI[] getArtifactRepositories() { - return artifactRepositories; - } - - public String getProperty(String key) { - return properties.getProperty(key); - } - - public void setProperty(String key, String value) { - properties.setProperty(key, value); - } - - public Properties getProperties() { - return properties; - } - - public List getExtraIUs() { - return extraIUs; - } - - public void setExtraIUs(List extraIUs) { - this.extraIUs = extraIUs; - } - - public void setAdditionalRequirements(Collection requirements) { - additionalRequirements = requirements; - } - - public Collection getAdditionalRequirements() { - return additionalRequirements; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/RollbackOperationEvent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/RollbackOperationEvent.java deleted file mode 100644 index 4d0032cba..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/RollbackOperationEvent.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import org.eclipse.core.runtime.IStatus; - -public class RollbackOperationEvent extends TransactionEvent { - - private static final long serialVersionUID = -2076492953949691215L; - private IStatus cause; - - public RollbackOperationEvent(IProfile profile, PhaseSet phaseSet, Operand[] operands, IEngine engine, IStatus cause) { - super(profile, phaseSet, operands, engine); - this.cause = cause; - } - - public IStatus getStatus() { - return cause; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Touchpoint.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Touchpoint.java deleted file mode 100644 index 4cc43fbd7..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/Touchpoint.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.util.Map; -import org.eclipse.core.runtime.*; - -/** - * A touchpoint is responsible for executing a given phase for a given - * targeted system (eclipse, native). The order of phases is defined in the {@link PhaseSet}. - */ -public abstract class Touchpoint { - - /** NOT API -- this is for backwards compatibility only */ - public String qualifyAction(String actionId) { - return actionId; - } - - public IStatus initializePhase(IProgressMonitor monitor, IProfile profile, String phaseId, Map touchpointParameters) { - return Status.OK_STATUS; - } - - public IStatus completePhase(IProgressMonitor monitor, IProfile profile, String phaseId, Map touchpointParameters) { - return Status.OK_STATUS; - } - - public IStatus initializeOperand(IProfile profile, Operand operand, Map parameters) { - return Status.OK_STATUS; - } - - public IStatus completeOperand(IProfile profile, Operand operand, Map parameters) { - return Status.OK_STATUS; - } - - public IStatus prepare(IProfile profile) { - return Status.OK_STATUS; - } - - public IStatus commit(IProfile profile) { - return Status.OK_STATUS; - } - - public IStatus rollback(IProfile profile) { - return Status.OK_STATUS; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/TransactionEvent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/TransactionEvent.java deleted file mode 100644 index efb574f7d..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/TransactionEvent.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine; - -import java.util.EventObject; - -public abstract class TransactionEvent extends EventObject { - private static final long serialVersionUID = 6278706971855493984L; - protected IProfile profile; - protected PhaseSet phaseSet; - protected Operand[] operands; - - public TransactionEvent(IProfile profile, PhaseSet phaseSet, Operand[] operands, IEngine engine) { - super(engine); - this.profile = profile; - this.phaseSet = phaseSet; - this.operands = operands; - } - - public IProfile getProfile() { - return profile; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/messages.properties b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/messages.properties deleted file mode 100644 index 364307adc..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/messages.properties +++ /dev/null @@ -1,51 +0,0 @@ -############################################################################### -# Copyright (c) 2007, 2009 IBM Corporation and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# IBM Corporation - initial API and implementation -############################################################################### -action_not_found=No action found for: {0}. -action_undo_error=An error occurred while rolling back the engine operation while undoing the {0} action. -forced_action_execute_error=An error occurred while performing the engine operation while executing the {0} action in forced mode. The operation will continue. -actions_not_found=No actions found for: {0}. -not_current_phase=Current phase does not match argument. -null_operands=Operands must not be null. -null_phase=Phase must not be null. -null_phases=Phases must not be null -null_phaseset=PhaseSet must not be null. -null_profile=Profile must not be null. -touchpoint_prepare_error=An error occurred while preparing the engine operation for the {0} touchpoint. -touchpoint_commit_error=An error occurred while committing the engine operation for the {0} touchpoint. -touchpoint_rollback_error=An error occurred while rolling back the engine operation for the {0} touchpoint. -phase_error=An error occurred during the {0} phase. -phase_undo_error=An error occurred while undoing the {0} phase. -phase_undo_operand_error=An error occurred while undoing the {0} phase for operand {1}. -phase_not_started=There is no phase to end. -phase_started=A phase is already started. -phaseid_not_positive=Phase weight must be positive. -phaseid_not_set=Phase id must be set. -session_prepare_error=An error occurred while preparing the engine session for profile: {0}. -session_commit_error=An error occurred while committing the engine session for profile: {0}. -null_operand=Operand must not be null. -operand_started=An operand is already started. -operand_not_started=There is no operand to end. -not_current_operand=Current operand does not match argument. -null_action=Action must not be null -session_context=session context was:(profile={0}, phase={1}, operand={2}, action={3}). -preparing=Preparing to commit the provisioning operation. -committing=Committing the provisioning operation. -rollingback_error=An error was detected while performing the engine operation and the changes are being rolled back. See the log for details. -rollingback_cancel=The engine operation was cancelled and the changes are being rolled back. - -Engine_Operation_Canceled_By_User=Operation canceled by the user. -InstallableUnitEvent_type_not_install_or_uninstall=type must be either UNINSTALL(0) or INSTALL(1) -CertificateChecker_CertificateError=An invalid certificate was found. -CertificateChecker_CertificateRejected=One or more certificates rejected. Cannot proceed with installation. -CertificateChecker_KeystoreConnectionError=Cannot connect to keystore. -CertificateChecker_SignedContentError=Error with signed content. -CertificateChecker_SignedContentIOError=Error reading signed content. -CertificateChecker_UnsignedNotAllowed=Installing unsigned artifacts is not permitted: {0} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/CheckTrust.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/CheckTrust.java deleted file mode 100644 index 28445c322..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/CheckTrust.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine.phases; - -import java.util.*; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.ITouchpointType; - -/** - * An install phase that checks if the certificates used to sign the artifacts - * being installed are from a trusted source. - */ -public class CheckTrust extends InstallableUnitPhase { - - private static final String PHASE_ID = "checkTrust"; //$NON-NLS-1$ - public static final String PARM_ARTIFACT_FILES = "artifactFiles"; //$NON-NLS-1$ - - public CheckTrust(int weight) { - super(PHASE_ID, weight); - } - - protected boolean isApplicable(InstallableUnitOperand op) { - return (op.second() != null); - } - - protected IStatus completePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { - Collection artifactRequests = (Collection) parameters.get(PARM_ARTIFACT_FILES); - - // Instantiate a check trust manager - CertificateChecker certificateChecker = new CertificateChecker(); - certificateChecker.add(artifactRequests.toArray()); - IStatus status = certificateChecker.start(); - - return status; - } - - protected ProvisioningAction[] getActions(InstallableUnitOperand operand) { - IInstallableUnit unit = operand.second(); - ProvisioningAction[] parsedActions = getActions(unit, phaseId); - if (parsedActions != null) - return parsedActions; - - ITouchpointType type = unit.getTouchpointType(); - if (type == null || type == ITouchpointType.NONE) - return null; - - String actionId = getActionManager().getTouchpointQualifiedActionId(phaseId, type); - ProvisioningAction action = getActionManager().getAction(actionId, null); - if (action == null) { - return null; - } - return new ProvisioningAction[] {action}; - } - - protected IStatus initializeOperand(IProfile profile, InstallableUnitOperand operand, Map parameters, IProgressMonitor monitor) { - IInstallableUnit iu = operand.second(); - parameters.put(PARM_IU, iu); - - return super.initializeOperand(profile, operand, parameters, monitor); - } - - protected IStatus initializePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { - parameters.put(PARM_ARTIFACT_FILES, new ArrayList()); - return super.initializePhase(monitor, profile, parameters); - } - -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Collect.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Collect.java deleted file mode 100644 index c0fc59c5e..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Collect.java +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * WindRiver - https://bugs.eclipse.org/bugs/show_bug.cgi?id=227372 - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine.phases; - -import java.util.*; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.p2.engine.DownloadManager; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.ITouchpointType; - -/** - * The goal of the collect phase is to ask the touchpoints if the artifacts associated with an IU need to be downloaded. - */ -public class Collect extends InstallableUnitPhase { - private static final String PHASE_ID = "collect"; //$NON-NLS-1$ - public static final String PARM_ARTIFACT_REQUESTS = "artifactRequests"; //$NON-NLS-1$ - - public Collect(int weight) { - super(PHASE_ID, weight); - //re-balance work since postPerform will do almost all the time-consuming work - prePerformWork = 0; - mainPerformWork = 100; - postPerformWork = 1000; - } - - protected boolean isApplicable(InstallableUnitOperand op) { - return (op.second() != null && !op.second().equals(op.first())); - } - - protected ProvisioningAction[] getActions(InstallableUnitOperand operand) { - IInstallableUnit unit = operand.second(); - ProvisioningAction[] parsedActions = getActions(unit, phaseId); - if (parsedActions != null) - return parsedActions; - - ITouchpointType type = unit.getTouchpointType(); - if (type == null || type == ITouchpointType.NONE) - return null; - - String actionId = getActionManager().getTouchpointQualifiedActionId(phaseId, type); - ProvisioningAction action = getActionManager().getAction(actionId, null); - if (action == null) { - return null; - } - return new ProvisioningAction[] {action}; - } - - protected String getProblemMessage() { - return Messages.Phase_Collect_Error; - } - - protected IStatus completePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { - List artifactRequests = (List) parameters.get(PARM_ARTIFACT_REQUESTS); - ProvisioningContext context = (ProvisioningContext) parameters.get(PARM_CONTEXT); - - DownloadManager dm = new DownloadManager(context); - for (Iterator it = artifactRequests.iterator(); it.hasNext();) { - IArtifactRequest[] requests = (IArtifactRequest[]) it.next(); - dm.add(requests); - } - return dm.start(monitor); - } - - protected IStatus initializePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { - parameters.put(PARM_ARTIFACT_REQUESTS, new ArrayList()); - return null; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Configure.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Configure.java deleted file mode 100644 index 78e7f2529..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Configure.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine.phases; - -import java.util.Map; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.osgi.util.NLS; - -public class Configure extends InstallableUnitPhase { - - public Configure(int weight) { - super("configure", weight); //$NON-NLS-1$ - } - - protected boolean isApplicable(InstallableUnitOperand op) { - return (op.second() != null); - } - - protected ProvisioningAction[] getActions(InstallableUnitOperand currentOperand) { - IInstallableUnit unit = currentOperand.second(); - if (unit.isFragment()) - return null; - return getActions(unit, phaseId); - } - - protected String getProblemMessage() { - return Messages.Phase_Configure_Error; - } - - protected IStatus initializeOperand(IProfile profile, InstallableUnitOperand operand, Map parameters, IProgressMonitor monitor) { - IInstallableUnit iu = operand.second(); - monitor.subTask(NLS.bind(Messages.Phase_Configure_Task, iu.getId())); - parameters.put(PARM_IU, iu); - - IArtifactKey[] artifacts = iu.getArtifacts(); - if (artifacts != null && artifacts.length > 0) - parameters.put(PARM_ARTIFACT, artifacts[0]); - - return Status.OK_STATUS; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Install.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Install.java deleted file mode 100644 index e0e9c0f3a..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Install.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine.phases; - -import java.util.Map; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.engine.EngineActivator; -import org.eclipse.equinox.internal.p2.engine.Profile; -import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.osgi.util.NLS; - -public class Install extends InstallableUnitPhase { - - final static class BeforeInstallEventAction extends ProvisioningAction { - - public IStatus execute(Map parameters) { - IProfile profile = (IProfile) parameters.get(PARM_PROFILE); - String phaseId = (String) parameters.get(PARM_PHASE_ID); - InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); - ((IProvisioningEventBus) ServiceHelper.getService(EngineActivator.getContext(), IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, operand, InstallableUnitEvent.INSTALL, getTouchpoint())); - return null; - } - - public IStatus undo(Map parameters) { - Profile profile = (Profile) parameters.get(PARM_PROFILE); - String phaseId = (String) parameters.get(PARM_PHASE_ID); - InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); - IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU); - profile.removeInstallableUnit(iu); - ((IProvisioningEventBus) ServiceHelper.getService(EngineActivator.getContext(), IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, operand, InstallableUnitEvent.UNINSTALL, getTouchpoint())); - return null; - } - } - - final static class AfterInstallEventAction extends ProvisioningAction { - - public IStatus execute(Map parameters) { - Profile profile = (Profile) parameters.get(PARM_PROFILE); - String phaseId = (String) parameters.get(PARM_PHASE_ID); - InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); - IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU); - profile.addInstallableUnit(iu); - ((IProvisioningEventBus) ServiceHelper.getService(EngineActivator.getContext(), IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, operand, InstallableUnitEvent.INSTALL, getTouchpoint())); - return null; - } - - public IStatus undo(Map parameters) { - IProfile profile = (IProfile) parameters.get(PARM_PROFILE); - String phaseId = (String) parameters.get(PARM_PHASE_ID); - InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); - ((IProvisioningEventBus) ServiceHelper.getService(EngineActivator.getContext(), IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, operand, InstallableUnitEvent.UNINSTALL, getTouchpoint())); - return null; - } - } - - private static final String PHASE_ID = "install"; //$NON-NLS-1$ - - public Install(int weight) { - super(PHASE_ID, weight); - } - - protected boolean isApplicable(InstallableUnitOperand op) { - return (op.second() != null && !op.second().equals(op.first())); - } - - protected ProvisioningAction[] getActions(InstallableUnitOperand currentOperand) { - //TODO: monitor.subTask(NLS.bind(Messages.Engine_Installing_IU, unit.getId())); - - ProvisioningAction beforeAction = new BeforeInstallEventAction(); - ProvisioningAction afterAction = new AfterInstallEventAction(); - - IInstallableUnit unit = currentOperand.second(); - Touchpoint touchpoint = getActionManager().getTouchpointPoint(unit.getTouchpointType()); - if (touchpoint != null) { - beforeAction.setTouchpoint(touchpoint); - afterAction.setTouchpoint(touchpoint); - } - - if (unit.isFragment()) - return new ProvisioningAction[] {beforeAction, afterAction}; - - ProvisioningAction[] parsedActions = getActions(unit, phaseId); - if (parsedActions == null) - return new ProvisioningAction[] {beforeAction, afterAction}; - - ProvisioningAction[] actions = new ProvisioningAction[parsedActions.length + 2]; - actions[0] = beforeAction; - System.arraycopy(parsedActions, 0, actions, 1, parsedActions.length); - actions[actions.length - 1] = afterAction; - return actions; - } - - protected String getProblemMessage() { - return Messages.Phase_Install_Error; - } - - protected IStatus initializeOperand(IProfile profile, InstallableUnitOperand operand, Map parameters, IProgressMonitor monitor) { - IInstallableUnit iu = operand.second(); - monitor.subTask(NLS.bind(Messages.Phase_Install_Task, iu.getId())); - parameters.put(PARM_IU, iu); - - IArtifactKey[] artifacts = iu.getArtifacts(); - if (artifacts != null && artifacts.length > 0) - parameters.put(PARM_ARTIFACT, artifacts[0]); - - return Status.OK_STATUS; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Messages.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Messages.java deleted file mode 100644 index 081b6f233..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Messages.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine.phases; - -import org.eclipse.osgi.util.NLS; - -//TODO Shouldn't have messages class in API package -class Messages extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.equinox.internal.provisional.p2.engine.phases.messages"; //$NON-NLS-1$ - public static String Phase_Collect_Error; - public static String Phase_Install_Error; - public static String Phase_Configure_Error; - public static String Phase_Configure_Task; - public static String Phase_Install_Task; - public static String Phase_Sizing_Error; - public static String Phase_Sizing_Warning; - public static String Phase_Unconfigure_Error; - public static String Phase_Uninstall_Error; - - static { - // initialize resource bundles - NLS.initializeMessages(BUNDLE_NAME, Messages.class); - } - - private Messages() { - // Do not instantiate - } - -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Property.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Property.java deleted file mode 100644 index 7a2387170..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Property.java +++ /dev/null @@ -1,157 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine.phases; - -import java.util.Map; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.p2.engine.Profile; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; - -public class Property extends Phase { - - public class ProfilePropertyAction extends ProvisioningAction { - - public IStatus execute(Map parameters) { - Profile profile = (Profile) parameters.get(PARM_PROFILE); - PropertyOperand propertyOperand = (PropertyOperand) parameters.get(PARM_OPERAND); - - if (propertyOperand.second() == null) - removeProfileProperty(profile, propertyOperand); - else - setProfileProperty(profile, propertyOperand, false); - - return null; - } - - public IStatus undo(Map parameters) { - Profile profile = (Profile) parameters.get(PARM_PROFILE); - PropertyOperand propertyOperand = (PropertyOperand) parameters.get(PARM_OPERAND); - - if (propertyOperand.first() == null) - removeProfileProperty(profile, propertyOperand); - else - setProfileProperty(profile, propertyOperand, true); - - return null; - } - - private void setProfileProperty(Profile profile, PropertyOperand propertyOperand, boolean undo) { - - String value = (String) (undo ? propertyOperand.first() : propertyOperand.second()); - - if (propertyOperand instanceof InstallableUnitPropertyOperand) { - InstallableUnitPropertyOperand iuPropertyOperand = (InstallableUnitPropertyOperand) propertyOperand; - profile.setInstallableUnitProperty(iuPropertyOperand.getInstallableUnit(), iuPropertyOperand.getKey(), value); - } else { - profile.setProperty(propertyOperand.getKey(), value); - } - } - - private void removeProfileProperty(Profile profile, PropertyOperand propertyOperand) { - if (propertyOperand instanceof InstallableUnitPropertyOperand) { - InstallableUnitPropertyOperand iuPropertyOperand = (InstallableUnitPropertyOperand) propertyOperand; - profile.removeInstallableUnitProperty(iuPropertyOperand.getInstallableUnit(), iuPropertyOperand.getKey()); - } else { - profile.removeProperty(propertyOperand.getKey()); - } - } - } - - public class UpdateInstallableUnitProfilePropertiesAction extends ProvisioningAction { - - // we do not need to use a memento here since the profile is not persisted unless the operation is successful - Map originalSourceProperties; - Map originalTargetProperties; - - public IStatus execute(Map parameters) { - Profile profile = (Profile) parameters.get(PARM_PROFILE); - InstallableUnitOperand iuOperand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); - - IInstallableUnit source = iuOperand.first(); - originalSourceProperties = profile.getInstallableUnitProperties(source); - - IInstallableUnit target = iuOperand.second(); - originalTargetProperties = profile.getInstallableUnitProperties(target); - - profile.addInstallableUnitProperties(target, originalSourceProperties); - profile.clearInstallableUnitProperties(source); - - return null; - } - - public IStatus undo(Map parameters) { - Profile profile = (Profile) parameters.get(PARM_PROFILE); - InstallableUnitOperand iuOperand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); - - IInstallableUnit source = iuOperand.first(); - profile.clearInstallableUnitProperties(source); - profile.addInstallableUnitProperties(source, originalSourceProperties); - - IInstallableUnit target = iuOperand.second(); - profile.clearInstallableUnitProperties(target); - profile.addInstallableUnitProperties(target, originalTargetProperties); - - return null; - } - } - - public class RemoveInstallableUnitProfilePropertiesAction extends ProvisioningAction { - - // we do not need to use a memento here since the profile is not persisted unless the operation is successful - Map originalSourceProperties; - Map originalTargetProperties; - - public IStatus execute(Map parameters) { - Profile profile = (Profile) parameters.get(PARM_PROFILE); - InstallableUnitOperand iuOperand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); - - IInstallableUnit source = iuOperand.first(); - originalSourceProperties = profile.getInstallableUnitProperties(source); - profile.clearInstallableUnitProperties(source); - - return null; - } - - public IStatus undo(Map parameters) { - Profile profile = (Profile) parameters.get(PARM_PROFILE); - InstallableUnitOperand iuOperand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); - - IInstallableUnit source = iuOperand.first(); - profile.clearInstallableUnitProperties(source); - profile.addInstallableUnitProperties(source, originalSourceProperties); - - return null; - } - } - - private static final String PHASE_ID = "property"; //$NON-NLS-1$ - - public Property(int weight) { - super(PHASE_ID, weight); - } - - protected ProvisioningAction[] getActions(Operand operand) { - if (operand instanceof PropertyOperand) - return new ProvisioningAction[] {new ProfilePropertyAction()}; - - if (operand instanceof InstallableUnitOperand) { - InstallableUnitOperand iuOperand = (InstallableUnitOperand) operand; - if (iuOperand.first() != null) { - if (iuOperand.second() != null) { - return new ProvisioningAction[] {new UpdateInstallableUnitProfilePropertiesAction()}; - } - return new ProvisioningAction[] {new RemoveInstallableUnitProfilePropertiesAction()}; - } - } - return null; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Sizing.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Sizing.java deleted file mode 100644 index 1145fb79a..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Sizing.java +++ /dev/null @@ -1,135 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine.phases; - -import java.net.URI; -import java.util.*; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.engine.EngineActivator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.ITouchpointType; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; - -public class Sizing extends InstallableUnitPhase { - private static final String PHASE_ID = "sizing"; //$NON-NLS-1$ - private static final String COLLECT_PHASE_ID = "collect"; //$NON-NLS-1$ - - private long sizeOnDisk; - private long dlSize; - - public Sizing(int weight, String phaseName) { - super(PHASE_ID, weight); - } - - protected boolean isApplicable(InstallableUnitOperand op) { - return (op.second() != null && !op.second().equals(op.first())); - } - - public long getDiskSize() { - return sizeOnDisk; - } - - public long getDlSize() { - return dlSize; - } - - protected ProvisioningAction[] getActions(InstallableUnitOperand operand) { - IInstallableUnit unit = operand.second(); - ProvisioningAction[] parsedActions = getActions(unit, COLLECT_PHASE_ID); - if (parsedActions != null) - return parsedActions; - - ITouchpointType type = unit.getTouchpointType(); - if (type == null || type == ITouchpointType.NONE) - return null; - - String actionId = getActionManager().getTouchpointQualifiedActionId(COLLECT_PHASE_ID, type); - ProvisioningAction action = getActionManager().getAction(actionId, null); - if (action == null) { - return null; - } - return new ProvisioningAction[] {action}; - } - - protected String getProblemMessage() { - return Messages.Phase_Sizing_Error; - } - - protected IStatus completePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { - List artifactRequests = (List) parameters.get(Collect.PARM_ARTIFACT_REQUESTS); - ProvisioningContext context = (ProvisioningContext) parameters.get(PARM_CONTEXT); - int statusCode = 0; - - Set artifactsToObtain = new HashSet(artifactRequests.size()); - - for (Iterator it = artifactRequests.iterator(); it.hasNext();) { - IArtifactRequest[] requests = (IArtifactRequest[]) it.next(); - if (requests == null) - continue; - for (int i = 0; i < requests.length; i++) { - artifactsToObtain.add(requests[i]); - } - } - - if (monitor.isCanceled()) - return Status.CANCEL_STATUS; - - IArtifactRepositoryManager repoMgr = (IArtifactRepositoryManager) ServiceHelper.getService(EngineActivator.getContext(), IArtifactRepositoryManager.class.getName()); - URI[] repositories = null; - if (context == null || context.getArtifactRepositories() == null) - repositories = repoMgr.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); - else - repositories = context.getArtifactRepositories(); - - for (Iterator iterator = artifactsToObtain.iterator(); iterator.hasNext() && !monitor.isCanceled();) { - IArtifactRequest artifactRequest = (IArtifactRequest) iterator.next(); - boolean found = false; - for (int i = 0; i < repositories.length; i++) { - IArtifactRepository repo; - try { - repo = repoMgr.loadRepository(repositories[i], monitor); - } catch (ProvisionException e) { - continue;//skip unresponsive repositories - } - if (monitor.isCanceled()) - return Status.CANCEL_STATUS; - IArtifactDescriptor[] descriptors = repo.getArtifactDescriptors(artifactRequest.getArtifactKey()); - if (descriptors.length > 0) { - if (descriptors[0].getProperty(IArtifactDescriptor.ARTIFACT_SIZE) != null) - sizeOnDisk += Long.parseLong(descriptors[0].getProperty(IArtifactDescriptor.ARTIFACT_SIZE)); - else - statusCode = ProvisionException.ARTIFACT_INCOMPLETE_SIZING; - if (descriptors[0].getProperty(IArtifactDescriptor.DOWNLOAD_SIZE) != null) - dlSize += Long.parseLong(descriptors[0].getProperty(IArtifactDescriptor.DOWNLOAD_SIZE)); - else - statusCode = ProvisionException.ARTIFACT_INCOMPLETE_SIZING; - found = true; - break; - } - } - if (!found) - // The artifact wasn't present in any repository - return new Status(IStatus.ERROR, EngineActivator.ID, ProvisionException.ARTIFACT_NOT_FOUND, Messages.Phase_Sizing_Error, null); - } - if (statusCode != 0) - return new Status(IStatus.WARNING, EngineActivator.ID, statusCode, Messages.Phase_Sizing_Warning, null); - return null; - } - - protected IStatus initializePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { - parameters.put(Collect.PARM_ARTIFACT_REQUESTS, new ArrayList()); - return null; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Unconfigure.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Unconfigure.java deleted file mode 100644 index 2eb8eb458..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Unconfigure.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine.phases; - -import java.util.Map; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; - -public class Unconfigure extends InstallableUnitPhase { - - public Unconfigure(int weight, boolean forced) { - super("unconfigure", weight, forced); //$NON-NLS-1$ - } - - public Unconfigure(int weight) { - this(weight, false); - } - - protected boolean isApplicable(InstallableUnitOperand op) { - return (op.first() != null); - } - - protected ProvisioningAction[] getActions(InstallableUnitOperand currentOperand) { - //TODO: monitor.subTask(NLS.bind(Messages.Engine_Unconfiguring_IU, unit.getId())); - - IInstallableUnit unit = currentOperand.first(); - if (unit.isFragment()) - return null; - - return getActions(unit, phaseId); - } - - protected String getProblemMessage() { - return Messages.Phase_Unconfigure_Error; - } - - protected IStatus initializeOperand(IProfile profile, InstallableUnitOperand operand, Map parameters, IProgressMonitor monitor) { - IInstallableUnit iu = operand.first(); - parameters.put(PARM_IU, iu); - - IArtifactKey[] artifacts = iu.getArtifacts(); - if (artifacts != null && artifacts.length > 0) - parameters.put(PARM_ARTIFACT, artifacts[0]); - - return Status.OK_STATUS; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Uninstall.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Uninstall.java deleted file mode 100644 index 5b66522de..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/Uninstall.java +++ /dev/null @@ -1,119 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.engine.phases; - -import java.util.Map; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.engine.EngineActivator; -import org.eclipse.equinox.internal.p2.engine.Profile; -import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; - -public class Uninstall extends InstallableUnitPhase { - - final static class BeforeUninstallEventAction extends ProvisioningAction { - public IStatus execute(Map parameters) { - IProfile profile = (IProfile) parameters.get(PARM_PROFILE); - String phaseId = (String) parameters.get(PARM_PHASE_ID); - InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); - ((IProvisioningEventBus) ServiceHelper.getService(EngineActivator.getContext(), IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, operand, InstallableUnitEvent.UNINSTALL, getTouchpoint())); - return null; - } - - public IStatus undo(Map parameters) { - Profile profile = (Profile) parameters.get(PARM_PROFILE); - String phaseId = (String) parameters.get(PARM_PHASE_ID); - InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); - IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU); - profile.addInstallableUnit(iu); - ((IProvisioningEventBus) ServiceHelper.getService(EngineActivator.getContext(), IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, operand, InstallableUnitEvent.INSTALL, getTouchpoint())); - return null; - } - } - - final static class AfterUninstallEventAction extends ProvisioningAction { - public IStatus execute(Map parameters) { - Profile profile = (Profile) parameters.get(PARM_PROFILE); - String phaseId = (String) parameters.get(PARM_PHASE_ID); - InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); - IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU); - profile.removeInstallableUnit(iu); - ((IProvisioningEventBus) ServiceHelper.getService(EngineActivator.getContext(), IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, false, profile, operand, InstallableUnitEvent.UNINSTALL, getTouchpoint())); - return null; - } - - public IStatus undo(Map parameters) { - IProfile profile = (IProfile) parameters.get(PARM_PROFILE); - String phaseId = (String) parameters.get(PARM_PHASE_ID); - InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); - ((IProvisioningEventBus) ServiceHelper.getService(EngineActivator.getContext(), IProvisioningEventBus.SERVICE_NAME)).publishEvent(new InstallableUnitEvent(phaseId, true, profile, operand, InstallableUnitEvent.INSTALL, getTouchpoint())); - return null; - } - } - - private static final String PHASE_ID = "uninstall"; //$NON-NLS-1$ - - public Uninstall(int weight, boolean forced) { - super(PHASE_ID, weight, forced); - } - - public Uninstall(int weight) { - this(weight, false); - } - - protected boolean isApplicable(InstallableUnitOperand op) { - return (op.first() != null && !op.first().equals(op.second())); - } - - protected ProvisioningAction[] getActions(InstallableUnitOperand currentOperand) { - //TODO: monitor.subTask(NLS.bind(Messages.Engine_Uninstalling_IU, unit.getId())); - - ProvisioningAction beforeAction = new BeforeUninstallEventAction(); - ProvisioningAction afterAction = new AfterUninstallEventAction(); - - IInstallableUnit unit = currentOperand.first(); - Touchpoint touchpoint = getActionManager().getTouchpointPoint(unit.getTouchpointType()); - if (touchpoint != null) { - beforeAction.setTouchpoint(touchpoint); - afterAction.setTouchpoint(touchpoint); - } - - if (unit.isFragment()) - return new ProvisioningAction[] {beforeAction, afterAction}; - ProvisioningAction[] parsedActions = getActions(unit, phaseId); - if (parsedActions == null) - return new ProvisioningAction[] {beforeAction, afterAction}; - - ProvisioningAction[] actions = new ProvisioningAction[parsedActions.length + 2]; - actions[0] = beforeAction; - System.arraycopy(parsedActions, 0, actions, 1, parsedActions.length); - actions[actions.length - 1] = afterAction; - return actions; - } - - protected String getProblemMessage() { - return Messages.Phase_Uninstall_Error; - } - - protected IStatus initializeOperand(IProfile profile, InstallableUnitOperand operand, Map parameters, IProgressMonitor monitor) { - IInstallableUnit iu = operand.first(); - parameters.put(PARM_IU, iu); - - IArtifactKey[] artifacts = iu.getArtifacts(); - if (artifacts != null && artifacts.length > 0) - parameters.put(PARM_ARTIFACT, artifacts[0]); - - return Status.OK_STATUS; - } -} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/messages.properties b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/messages.properties deleted file mode 100644 index 58a0dd1e5..000000000 --- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/internal/provisional/p2/engine/phases/messages.properties +++ /dev/null @@ -1,20 +0,0 @@ -############################################################################### -# Copyright (c) 2007, 2009 IBM Corporation and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# IBM Corporation - initial API and implementation -############################################################################### - -Phase_Collect_Error=An error occurred while collecting items to be installed -Phase_Configure_Error=An error occurred while configuring the installed items -Phase_Configure_Task=Configuring {0} -Phase_Install_Error=An error occurred while installing the items -Phase_Install_Task=Installing {0} -Phase_Sizing_Error=Error computing the size. Some of the items to be installed could not be found. -Phase_Sizing_Warning=The size may not be accurate. Some of the items did not report a size. -Phase_Unconfigure_Error=An error occurred while unconfiguring the items to uninstall -Phase_Uninstall_Error=An error occurred while uninstalling diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/BeginOperationEvent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/BeginOperationEvent.java new file mode 100644 index 000000000..98576a326 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/BeginOperationEvent.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import org.eclipse.equinox.internal.p2.engine.PhaseSet; + +/** + * @since 2.0 + */ +public class BeginOperationEvent extends TransactionEvent { + + private static final long serialVersionUID = 6389318375739324865L; + + public BeginOperationEvent(IProfile profile, PhaseSet phaseSet, Operand[] operands, IEngine engine) { + super(profile, phaseSet, operands, engine); + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/CommitOperationEvent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/CommitOperationEvent.java new file mode 100644 index 000000000..5b993dc39 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/CommitOperationEvent.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import org.eclipse.equinox.internal.p2.engine.PhaseSet; + +/** + * @since 2.0 + */ +public class CommitOperationEvent extends TransactionEvent { + private static final long serialVersionUID = -523967775426133720L; + + public CommitOperationEvent(IProfile profile, PhaseSet phaseSet, Operand[] operands, IEngine engine) { + super(profile, phaseSet, operands, engine); + } + +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/DefaultPhaseSet.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/DefaultPhaseSet.java new file mode 100644 index 000000000..c6fe87bdf --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/DefaultPhaseSet.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import java.util.ArrayList; +import org.eclipse.equinox.internal.p2.engine.*; +import org.eclipse.equinox.internal.p2.engine.phases.*; + +/** + * @since 2.0 + */ +public class DefaultPhaseSet extends PhaseSet { + + private static final boolean forcedUninstall = Boolean.valueOf(EngineActivator.getContext().getProperty("org.eclipse.equinox.p2.engine.forcedUninstall")).booleanValue(); //$NON-NLS-1$ + + public static int PHASE_COLLECT = 0x02; + public static int PHASE_UNCONFIGURE = 0x20; + public static int PHASE_UNINSTALL = 0x40; + public static int PHASE_PROPERTY = 0x10; + public static int PHASE_CHECK_TRUST = 0x01; + public static int PHASE_INSTALL = 0x08; + public static int PHASE_CONFIGURE = 0x04; + + public DefaultPhaseSet() { + this(new Phase[] {new Collect(100), new Unconfigure(10, forcedUninstall), new Uninstall(50, forcedUninstall), new Property(1), new CheckTrust(10), new Install(50), new Configure(10)}); + } + + private DefaultPhaseSet(Phase[] phases) { + super(phases); + } + + /** + * Creates a default phase set that covers all the provisioning operations. + * Phases can be specified for exclusion. + * + * @param exclude - A set of bit options that specify the phases to exclude. + * See {@link DefaultPhaseSet} for possible options + * @return the {@link PhaseSet} + */ + public static final PhaseSet createDefaultPhaseSet(int exclude) { + ArrayList phases = new ArrayList(); + if ((PHASE_COLLECT & exclude) != PHASE_COLLECT) + phases.add(new Collect(100)); + if ((PHASE_UNCONFIGURE & exclude) != PHASE_UNCONFIGURE) + phases.add(new Unconfigure(10, forcedUninstall)); + if ((PHASE_UNINSTALL & exclude) != PHASE_UNINSTALL) + phases.add(new Uninstall(50, forcedUninstall)); + if ((PHASE_PROPERTY & exclude) != PHASE_PROPERTY) + phases.add(new Property(1)); + if ((PHASE_CHECK_TRUST & exclude) != PHASE_CHECK_TRUST) + phases.add(new CheckTrust(10)); + if ((PHASE_INSTALL & exclude) != PHASE_INSTALL) + phases.add(new Install(50)); + if ((PHASE_CONFIGURE & exclude) != PHASE_CONFIGURE) + phases.add(new Configure(10)); + return new DefaultPhaseSet(phases.toArray(new Phase[phases.size()])); + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IEngine.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IEngine.java new file mode 100644 index 000000000..67d0f8d28 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IEngine.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 Band XI International, LLC and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Band XI - initial API and implementation + * IBM - ongoing development + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; + +/** + * The engine is a service that naively performs a set of requested changes to a provisioned + * system. No attempt is made to determine whether the requested changes or the + * resulting system are valid or consistent. It is assumed that the engine client has + * crafted a valid provisioning plan for the engine to perform, typically by using a planner + * service. + *

+ * The engine operates by executing a series of installation phases. The client can + * customize the set of phases that are executed, or else the engine will execute + * a default set of phases. During each phase the changes described by the provisioning + * plan are performed against the profile being provisioned. + * + * @since 2.0 + */ +public interface IEngine { + /** + * Service name constant for the engine service. + */ + public static final String SERVICE_NAME = IEngine.class.getName(); + + /** + * Creates a customized provisioning plan describing a set of changes that have already been validated. + * This is an advanced method for clients that know they are creating changes that do + * not require validation by a planner. Most clients should instead obtain a validated plan + * from a planner. + * + * @param profile The profile to operate against + * @param operands The operands to perform + * @param context The provisioning context for the plan + * @return A provisioning plan + */ + public IProvisioningPlan createCustomPlan(IProfile profile, Operand[] operands, ProvisioningContext context); + + /** + * Creates a phase set with a default set of phases, excluding the specified phases. + * @param excludes The phases to exclude, or null to include + * all default phases. + * + * @return A new phase set + */ + public IPhaseSet createPhaseSetExcluding(String[] excludes); + + /** + * Creates and returns a phase set including only the specified phases. + * @param includes The phases to include + * @return A new phase set + */ + public IPhaseSet createPhaseSetIncluding(String[] includes); + + /** + * Executes a provisioning plan. + * + * @param plan The plan describing the changes to be made + * @param phaseSet The phases to run, or null to run default phases + * @param monitor A progress monitor, or null if progress reporting is not required + * @return The result of executing the plan + */ + public IStatus perform(IProvisioningPlan plan, IPhaseSet phaseSet, IProgressMonitor monitor); + + /** + * Executes a provisioning plan with a default phase set and context. + * + * @param plan The plan describing the changes to be made + * @param monitor A progress monitor, or null if progress reporting is not required + * @return The result of executing the plan + */ + public IStatus perform(IProvisioningPlan plan, IProgressMonitor monitor); +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IPhaseSet.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IPhaseSet.java new file mode 100644 index 000000000..4344c61d8 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IPhaseSet.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + + +/** + * Describes a set of provisioning phases to be performed by an {@link IEngine}. + * + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface IPhaseSet { + + /** + * A phase id (value "checkTrust") describing the certificate trust check phase. + * This phase examines the code signing certificates of the artifacts being installed + * to ensure they are signed and trusted by the running system. + */ + public static String PHASE_CHECK_TRUST = "checkTrust"; //$NON-NLS-1$ + /** + * A phase id (value "collect") describing the collect phase. + * This phase gathers all the artifacts to be installed, typically by copying them + * from some repository into a suitable local location for the application being installed. + */ + public static String PHASE_COLLECT = "collect"; //$NON-NLS-1$ + /** + * A phase id (value "configure") describing the configuration phase. + * This phase writes configuration data related to the software being provisioned. + * Until configuration occurs the end user of the software will be have access to + * the installed functionality. + */ + public static String PHASE_CONFIGURE = "configure"; //$NON-NLS-1$ + /** + * A phase id (value "install") describing the install phase. + * This phase performs any necessary transformations on the downloaded + * artifacts to put them in the correct shape for the running application, such + * as decompressing or moving content, setting file permissions, etc). + */ + public static String PHASE_INSTALL = "install"; //$NON-NLS-1$ + /** + * A phase id (value "property") describing the property modification phase. + * This phase performs changes to profile properties. + */ + public static String PHASE_PROPERTY = "property"; //$NON-NLS-1$ + /** + * A phase id (value "unconfigure") describing the unconfigure phase. + * This phase removes configuration data related to the software being removed. + * This phase is the inverse of the changes performed in the configure phase. + */ + public static String PHASE_UNCONFIGURE = "unconfigure"; //$NON-NLS-1$ + /** + * A phase id (value "uninstall") describing the uninstall phase. + * This phase removes artifacts from the system being provisioned that are + * no longer required in the new profile. + */ + public static String PHASE_UNINSTALL = "uninstall"; //$NON-NLS-1$ + + /** + * Returns the ids of the phases to be performed by this phase set. The order + * of the returned ids indicates the order in which the phases will be run. + * @return The phase ids. + */ + public String[] getPhaseIds(); +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IProfile.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IProfile.java new file mode 100644 index 000000000..3019f6917 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IProfile.java @@ -0,0 +1,133 @@ +/******************************************************************************* + * Copyright (c) 2005, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import java.util.Map; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.*; + +/** + * @since 2.0 + */ +public interface IProfile extends IQueryable { + + /** + * Constant used to indicate that an installable unit is not locked in anyway. + * @see #PROP_PROFILE_LOCKED_IU + */ + public static int LOCK_NONE = 0; + /** + * Constant used to indicate that an installable unit is locked so that it may + * not be uninstalled. + * @see #PROP_PROFILE_LOCKED_IU + */ + public static int LOCK_UNINSTALL = 1 << 0; + /** + * Constant used to indicate that an installable unit is locked so that it may + * not be updated. updates. + * @see #PROP_PROFILE_LOCKED_IU + */ + public static int LOCK_UPDATE = 1 << 1; + + /** + * A property key (value "org.eclipse.equinox.p2.type.lock") for an + * integer property indicating how an installable unit is locked in its profile. + * The integer is a bit-mask indicating the different locks defined on the installable + * unit. The property should be obtained from a profile using + * IProfile#getInstallableUnitProperty(IInstallableUnit, String). + * + * @see #LOCK_UNINSTALL + * @see #LOCK_UPDATE + * @see #LOCK_NONE + */ + public static final String PROP_PROFILE_LOCKED_IU = "org.eclipse.equinox.p2.type.lock"; //$NON-NLS-1$ + + //TODO Move to UI + public static final String PROP_PROFILE_ROOT_IU = "org.eclipse.equinox.p2.type.root"; //$NON-NLS-1$ + + /** + * Profile property constant indicating the install folder for the profile. + */ + public static final String PROP_INSTALL_FOLDER = "org.eclipse.equinox.p2.installFolder"; //$NON-NLS-1$ + /** + * Profile property constant indicating the configuration folder for the profile. + */ + public static final String PROP_CONFIGURATION_FOLDER = "org.eclipse.equinox.p2.configurationFolder"; //$NON-NLS-1$ + /** + * Profile property constant indicating the location of the launcher configuration file for the profile. + */ + public static final String PROP_LAUNCHER_CONFIGURATION = "org.eclipse.equinox.p2.launcherConfiguration"; //$NON-NLS-1$ + + /** + * Profile property constant indicating the installed language(s) for the profile. + */ + public static final String PROP_NL = "org.eclipse.equinox.p2.nl"; //$NON-NLS-1$ + /** + * Profile property constant for a string property indicating a user visible short + * textual description of this profile. May be empty or null, and + * generally will be for non-top level install contexts. + */ + public static final String PROP_DESCRIPTION = "org.eclipse.equinox.p2.description"; //$NON-NLS-1$ + /** + * Profile property constant for a string property indicating a user visible name of this profile. + * May be empty or null, and generally will be for non-top level + * install contexts. + */ + public static final String PROP_NAME = "org.eclipse.equinox.p2.name"; //$NON-NLS-1$ + /** + * Profile property constant indicating the list of environments + * (e.g., OS, WS, ...) in which a profile can operate. The value of the property + * is a comma-delimited string of key/value pairs. + */ + public static final String PROP_ENVIRONMENTS = "org.eclipse.equinox.p2.environments"; //$NON-NLS-1$ + /** + * Profile property constant for a boolean property indicating if the profiling + * is roaming. A roaming profile is one whose physical install location varies + * and is updated whenever it runs. + */ + public static final String PROP_ROAMING = "org.eclipse.equinox.p2.roaming"; //$NON-NLS-1$ + /** + * Profile property constant indicating the bundle pool cache location. + */ + public static final String PROP_CACHE = "org.eclipse.equinox.p2.cache"; //$NON-NLS-1$ + + /** + * Profile property constant indicating a shared read-only bundle pool cache location. + */ + public static final String PROP_SHARED_CACHE = "org.eclipse.equinox.p2.cache.shared"; //$NON-NLS-1$ + + /** + * Profile property constant for a boolean property indicating if update features should + * be installed in this profile + */ + public static final String PROP_INSTALL_FEATURES = "org.eclipse.update.install.features"; //$NON-NLS-1$ + + public String getProfileId(); + + /** + * Get the stored value associated with the given key. + * + * null is returned if this property is not present + */ + public String getProperty(String key); + + public String getInstallableUnitProperty(IInstallableUnit iu, String key); + + public Map getProperties(); + + public Map getInstallableUnitProperties(IInstallableUnit iu); + + public long getTimestamp(); + + public IQueryResult available(IQuery query, IProgressMonitor monitor); + +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IProfileRegistry.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IProfileRegistry.java new file mode 100644 index 000000000..adbd48360 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IProfileRegistry.java @@ -0,0 +1,121 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import java.util.Map; +import org.eclipse.equinox.p2.core.ProvisionException; + +/** + * This encapsulates the access to the profile registry. + * It deals with persistence in a transparent way. + * @since 2.0 + */ +public interface IProfileRegistry { + public static final String SELF = "_SELF_"; //$NON-NLS-1$ + /** + * Service name constant for the profile registry service. + */ + public static final String SERVICE_NAME = IProfileRegistry.class.getName(); + + /** + * Return the profile in the registry that has the given id. If it does not exist, + * then return null. + * + * @param id the profile identifier + * @return the profile or null + */ + IProfile getProfile(String id); + + /** + * Return the profile in the registry that has the given id and timestamp. If it does not exist, + * then return null. + * + * @param id the profile identifier + * @param timestamp the profile's timestamp + + * @return the profile or null + */ + IProfile getProfile(String id, long timestamp); + + /** + * Return an array of timestamps in ascending order for the profile in question. If there are none, then + * return an empty array. + * + * @return the array of timestamps + */ + long[] listProfileTimestamps(String id); + + /** + * Return an array of profiles known to this registry. If there are none, then + * return an empty array. + * + * @return the array of profiles + */ + IProfile[] getProfiles(); + + /** + * Add the given profile to this profile registry. + * + * @param id the profile id + * + * @throws ProvisionException if a profile + * with the same id is already present in the registry. + */ + IProfile addProfile(String id) throws ProvisionException; + + /** + * Add the given profile to this profile registry. + * + * @param id the profile id + * @param properties the profile properties + * + * @throws ProvisionException if a profile + * with the same id is already present in the registry. + */ + IProfile addProfile(String id, Map properties) throws ProvisionException; + + /** + * Returns whether this profile registry contains a profile with the given id. + * + * @param profileId The id of the profile to search for + * @return true if this registry contains a profile with the given id, + * and false otherwise. + */ + public boolean containsProfile(String profileId); + + /** + * Remove the given profile snapshot from this profile registry. This method has no effect + * if this registry does not contain a profile with the given id and timestamp. + * The current profile cannot be removed using this method. + * + * @param id the profile to remove + * @param timestamp the timestamp of the profile to remove + * + * @throws ProvisionException if the profile with the specified id and timestamp is the current profile. + */ + void removeProfile(String id, long timestamp) throws ProvisionException; + + /** + * Remove the given profile from this profile registry. This method has no effect + * if this registry does not contain a profile with the given id. + * + * @param id the profile to remove + */ + void removeProfile(String id); + + /** + * Check if the given profile from this profile registry is up-to-date. + * + * @param profile the profile to check + * @return boolean true if the profile is current; false otherwise. + */ + public boolean isCurrent(IProfile profile); +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IProvisioningPlan.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IProvisioningPlan.java new file mode 100644 index 000000000..0f24afff7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/IProvisioningPlan.java @@ -0,0 +1,117 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import java.util.Map; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQueryable; + +/** + * A provisioning plan describes a proposed set of changes to a profile. The + * proposed changes may represent a valid and consistent set of changes, or it + * may represent a set of changes that would cause errors if executed. In this + * case the plan contains information about the severity and explanation for the + * problems. + * + * @since 2.0 + */ +public interface IProvisioningPlan { + + /** + * Returns the proposed set of installable units to be added to the profile. + * + * @return The proposed profile additions + */ + public abstract IQueryable getAdditions(); + + /** + * Returns the provisioning context in which this plan was created. + * + * @return The plan's provisioning context + */ + public ProvisioningContext getContext(); + + /** + * Returns a plan describing the proposed set of changes to the provisioning infrastructure + * required by this plan. The installer changes must be performed before this plan + * can be successfully executed. + * + * @return The installer plan. + */ + public abstract IProvisioningPlan getInstallerPlan(); + + /** + * The operands to pass to the engine. + * @return the operands to be executed. This may be an empty array if the + * plan has errors or if there is nothing to do. + */ + public abstract Operand[] getOperands(); + + /** + * Returns the profile that this plan will operate on. + * + * @return The target profile for this plan + */ + public abstract IProfile getProfile(); + + /** + * Returns the proposed set of installable units to be removed from this profile. + * + * @return The proposed profile removals. + */ + public abstract IQueryable getRemovals(); + + /** + * Returns the problems associated with changes to the given installable unit + * in this plan. A status with severity {@link IStatus#OK} is returned if the unit + * can be provisioned successfully, or if this plan does not include changes to the + * given unit. + * + * @param iu The installable unit to return status for + * @return The status for the given unit in this plan + */ + public abstract IStatus getRequestStatus(IInstallableUnit iu); + + /** + * Returns a map of side-effects that will occur as a result of the plan being executed. + * Side-effects of an install may include: + *

    + *
  • Optional software being installed that will become satisfied once the plan + * is executed.
  • + *
  • Optional software currently in the profile that will be uninstalled as a result + * of the plan being executed. This occurs when the optional software has dependencies + * that are incompatible with the software being installed. + * This includes additional software that will be installed as a result of the change, + * or optional + * @return A map of {@link IInstallableUnit} to {@link IStatus} of the additional + * changes and their corresponding explanation. + */ + public abstract Map getSideEffectChanges(); + + /** + * Returns the overall plan status. The severity of this status indicates + * whether the plan can be successfully executed or not: + *
      + *
    • A status of {@link IStatus#OK} indicates that the plan can be executed successfully.
    • + *
    • A status of {@link IStatus#INFO} or {@link IStatus#WARNING} indicates + * that the plan can be executed but may cause problems.
    • + *
    • A status of {@link IStatus#ERROR} indicates that the plan cannot be executed + * successfully.
    • + *
    • A status of {@link IStatus#CANCEL} indicates that the plan computation was + * canceled and is incomplete. A canceled plan cannot be executed.
    • + *
    + * + * @return The overall plan status. + */ + public abstract IStatus getStatus(); + +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ISurrogateProfileHandler.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ISurrogateProfileHandler.java new file mode 100644 index 000000000..00faa2baf --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ISurrogateProfileHandler.java @@ -0,0 +1,31 @@ +/******************************************************************************* + * Copyright (c) 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.IQueryResult; + +/** + * @since 2.0 + */ +public interface ISurrogateProfileHandler { + + public abstract IProfile createProfile(String id); + + public abstract boolean isSurrogate(IProfile profile); + + public abstract IQueryResult queryProfile(IProfile profile, IQuery query, IProgressMonitor monitor); + + public abstract boolean updateProfile(IProfile selfProfile); + +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/InstallableUnitEvent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/InstallableUnitEvent.java new file mode 100644 index 000000000..80ca32abe --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/InstallableUnitEvent.java @@ -0,0 +1,89 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import java.util.EventObject; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.equinox.internal.p2.engine.Messages; +import org.eclipse.equinox.p2.engine.spi.Touchpoint; + +/** + * @since 2.0 + */ +public class InstallableUnitEvent extends EventObject { + public static final int UNINSTALL = 0; + public static final int INSTALL = 1; + private static final long serialVersionUID = 3318712818811459886L; + + private String phaseId; + private boolean prePhase; + + private IProfile profile; + private InstallableUnitOperand operand; + private Touchpoint touchpoint; + private IStatus result; + private int type; + + public InstallableUnitEvent(String phaseId, boolean prePhase, IProfile profile, InstallableUnitOperand operand, int type, Touchpoint touchpoint) { + this(phaseId, prePhase, profile, operand, type, touchpoint, null); + } + + public InstallableUnitEvent(String phaseId, boolean prePhase, IProfile profile, InstallableUnitOperand operand, int type, Touchpoint touchpoint, IStatus result) { + super(profile); + this.phaseId = phaseId; + this.prePhase = prePhase; + this.profile = profile; + this.operand = operand; + if (type != UNINSTALL && type != INSTALL) + throw new IllegalArgumentException(Messages.InstallableUnitEvent_type_not_install_or_uninstall); + this.type = type; + this.result = result; + this.touchpoint = touchpoint; + + } + + public Touchpoint getTouchpoint() { + return touchpoint; + } + + public IProfile getProfile() { + return profile; + } + + public InstallableUnitOperand getOperand() { + return operand; + } + + public String getPhase() { + return phaseId; + } + + public boolean isPre() { + return prePhase; + } + + public boolean isPost() { + return !prePhase; + } + + public IStatus getResult() { + return (result != null ? result : Status.OK_STATUS); + } + + public boolean isInstall() { + return type == INSTALL; + } + + public boolean isUninstall() { + return type == UNINSTALL; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/InstallableUnitOperand.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/InstallableUnitOperand.java new file mode 100644 index 000000000..edab40f53 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/InstallableUnitOperand.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import org.eclipse.core.runtime.Assert; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; + +/** + * @since 2.0 + */ +public class InstallableUnitOperand extends Operand { + private final IInstallableUnit first; + private final IInstallableUnit second; + + /** + * Creates a new operand that represents replacing an installable unit + * with another. At least one of the provided installable units must be + * non-null. + * + * @param first The installable unit being removed, or null + * @param second The installable unit being added, or null + */ + public InstallableUnitOperand(IInstallableUnit first, IInstallableUnit second) { + //the operand must have at least one non-null units + Assert.isTrue(first != null || second != null); + this.first = first; + this.second = second; + } + + public IInstallableUnit first() { + return first; + } + + public IInstallableUnit second() { + return second; + } + + public String toString() { + return first + " --> " + second; //$NON-NLS-1$ + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/InstallableUnitPropertyOperand.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/InstallableUnitPropertyOperand.java new file mode 100644 index 000000000..265da8d80 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/InstallableUnitPropertyOperand.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import org.eclipse.core.runtime.Assert; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; + +/** + * @since 2.0 + */ +public class InstallableUnitPropertyOperand extends PropertyOperand { + private final IInstallableUnit iu; + + /** + * Creates a new operand that represents replacing a property value associated + * with an IU with another. At least one of the provided property values must be + * non-null. + * + * @param iu The IInstallableUnit with which the property is associated + * @param key The key of the property being modified + * @param first The property value being removed, or null + * @param second The property value being added, or null + */ + public InstallableUnitPropertyOperand(IInstallableUnit iu, String key, Object first, Object second) { + super(key, first, second); + //the iu must be specified. + Assert.isTrue(iu != null); + this.iu = iu; + } + + public IInstallableUnit getInstallableUnit() { + return iu; + } + + public String toString() { + return "[IInstallableUnit property for " + iu.toString() + "] " + super.toString(); //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/MissingAction.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/MissingAction.java new file mode 100644 index 000000000..40115b1a7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/MissingAction.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import java.util.Map; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.equinox.internal.p2.engine.Messages; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.VersionRange; +import org.eclipse.osgi.util.NLS; + +/** + * @since 2.0 + */ +public class MissingAction extends ProvisioningAction { + + private String actionId; + private VersionRange versionRange; + + public MissingAction(String actionId, VersionRange versionRange) { + this.actionId = actionId; + this.versionRange = versionRange; + } + + public String getActionId() { + return actionId; + } + + public VersionRange getVersionRange() { + return versionRange; + } + + public IStatus execute(Map parameters) { + throw new IllegalArgumentException(NLS.bind(Messages.action_not_found, actionId + (versionRange == null ? "" : "/" + versionRange.toString()))); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public IStatus undo(Map parameters) { + // do nothing as we want this action to undo successfully + return Status.OK_STATUS; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/MissingActionsException.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/MissingActionsException.java new file mode 100644 index 000000000..2385e4609 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/MissingActionsException.java @@ -0,0 +1,53 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import org.eclipse.equinox.internal.p2.engine.Messages; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.osgi.util.NLS; + +/** + * @since 2.0 + */ +public class MissingActionsException extends ProvisionException { + + private static final long serialVersionUID = 8617693596359747490L; + private final MissingAction[] missingActions; + + public MissingActionsException(MissingAction[] missingActions) { + super(getMissingActionsMessage(missingActions)); + this.missingActions = missingActions; + } + + private static String getMissingActionsMessage(MissingAction[] missingActions) { + + if (missingActions.length == 0) + throw new IllegalArgumentException("Bad exception: No missing actions"); //$NON-NLS-1$ + + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < missingActions.length; i++) { + MissingAction missingAction = missingActions[i]; + buffer.append(missingAction.getActionId()); + if (missingAction.getVersionRange() != null) { + buffer.append("/"); //$NON-NLS-1$ + buffer.append(missingAction.getVersionRange().toString()); + } + if (i + 1 != missingActions.length) + buffer.append(", "); //$NON-NLS-1$ + } + + return NLS.bind(Messages.actions_not_found, buffer.toString()); + } + + public MissingAction[] getMissingActions() { + return missingActions; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/Operand.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/Operand.java new file mode 100644 index 000000000..7efeb9e88 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/Operand.java @@ -0,0 +1,21 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +/** + * The common base class for engine operands. + * + * @see IEngine#createCustomPlan(IProfile, Operand[], ProvisioningContext) + * @since 2.0 + */ +public class Operand { + // marker class +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProfileEvent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProfileEvent.java new file mode 100644 index 000000000..064717d1a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProfileEvent.java @@ -0,0 +1,40 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import java.util.EventObject; + +/** + * @noextend This class is not intended to be subclassed by clients. + * @since 2.0 + */ +public class ProfileEvent extends EventObject { + private static final long serialVersionUID = 3082402920617281765L; + + public static final byte ADDED = 0; + public static final byte REMOVED = 1; + public static final byte CHANGED = 2; + + private byte reason; + + public ProfileEvent(String profileId, byte reason) { + super(profileId); + this.reason = reason; + } + + public byte getReason() { + return reason; + } + + public String getProfileId() { + return (String) getSource(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProfileScope.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProfileScope.java new file mode 100644 index 000000000..e0ab51a1a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProfileScope.java @@ -0,0 +1,110 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import org.eclipse.core.internal.preferences.PreferencesService; +import org.eclipse.core.runtime.Assert; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.preferences.IEclipsePreferences; +import org.eclipse.core.runtime.preferences.IScopeContext; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.internal.p2.engine.EngineActivator; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.security.storage.EncodingUtils; + +/** + * A profile scope contains the preferences associated with a particular profile + * in a provisioned system. + * @see IProfile + * @since 2.0 + */ +public final class ProfileScope implements IScopeContext { + + /* + * String constant (value of "profile") used for the + * scope name for this preference scope. + */ + public static final String SCOPE = "profile"; //$NON-NLS-1$ + + private String profileId; + + private IAgentLocation location; + + /** + * Create and return a new profile scope for the given profile. The given + * profile id must not be null. The provisioning agent of the currently running + * system is used. + * @deprecated use {@link ProfileScope#ProfileScope(IAgentLocation, String)} instead + */ + public ProfileScope(String profileId) { + this(getDefaultAgent(), profileId); + } + + /** + * Creates and returns a profile scope for the given profile id and agent. + * @param agentLocation The location of the provisioning agent to obtain profile preferences for + * @param profileId The id of the profile to obtain preferences for + */ + public ProfileScope(IAgentLocation agentLocation, String profileId) { + super(); + Assert.isNotNull(agentLocation); + Assert.isNotNull(profileId); + this.profileId = profileId; + this.location = agentLocation; + } + + private static IAgentLocation getDefaultAgent() { + return (IAgentLocation) ServiceHelper.getService(EngineActivator.getContext(), IAgentLocation.SERVICE_NAME); + } + + public IPath getLocation() { + // Null returned as the location should only be used when the profile is locked + return null; + } + + public String getName() { + return SCOPE; + } + + /* + * Default path hierarchy for profile nodes is /profile//. + * + * @see org.eclipse.core.runtime.preferences.IScopeContext#getNode(java.lang.String) + */ + public IEclipsePreferences getNode(String qualifier) { + if (qualifier == null) + throw new IllegalArgumentException(); + String locationString = EncodingUtils.encodeSlashes(location.getRootLocation().toString()); + //format is /profile/{agentLocationURI}/{profileId}/qualifier + return (IEclipsePreferences) PreferencesService.getDefault().getRootNode().node(getName()).node(locationString).node(profileId).node(qualifier); + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (!(obj instanceof ProfileScope)) + return false; + ProfileScope other = (ProfileScope) obj; + return profileId.equals(other.profileId); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + public int hashCode() { + return super.hashCode() + profileId.hashCode(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/PropertyOperand.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/PropertyOperand.java new file mode 100644 index 000000000..3751abb39 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/PropertyOperand.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (c) 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import org.eclipse.core.runtime.Assert; + +/** + * @since 2.0 + */ +public class PropertyOperand extends Operand { + private final Object first; + private final Object second; + private final String key; + + /** + * Creates a new operand that represents replacing a property value + * with another. At least one of the provided property values must be + * non-null. + * + * @param key The key of the property being modified + * @param first The property value being removed, or null + * @param second The property value being added, or null + */ + public PropertyOperand(String key, Object first, Object second) { + //the operand must specify have a key and have at least one non-null value + Assert.isTrue(key != null && (first != null || second != null)); + this.first = first; + this.second = second; + this.key = key; + } + + public Object first() { + return first; + } + + public Object second() { + return second; + } + + public String getKey() { + return key; + } + + public String toString() { + return key + " = " + first + " --> " + second; //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningContext.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningContext.java new file mode 100644 index 000000000..bb08c51d9 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningContext.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * WindRiver - https://bugs.eclipse.org/bugs/show_bug.cgi?id=227372 + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import java.net.URI; +import java.util.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; + +/** + * @since 2.0 + */ +public class ProvisioningContext { + private URI[] metadataRepositories; //metadata repositories to consult + private URI[] artifactRepositories; //artifact repositories to consult + private Map properties = new HashMap(); + private List extraIUs = new ArrayList(); + private Collection additionalRequirements; + + public ProvisioningContext() { + // null repos means look at them all + metadataRepositories = null; + artifactRepositories = null; + } + + public ProvisioningContext(URI[] metadataRepositories) { + this.metadataRepositories = metadataRepositories; + } + + /** + * Artifact repositories to consult when performing an operation. + * @param artifactRepositories array of URLs + */ + public void setArtifactRepositories(URI[] artifactRepositories) { + this.artifactRepositories = artifactRepositories; + } + + public URI[] getMetadataRepositories() { + return metadataRepositories; + } + + public URI[] getArtifactRepositories() { + return artifactRepositories; + } + + public String getProperty(String key) { + return properties.get(key); + } + + public void setProperty(String key, String value) { + properties.put(key, value); + } + + public Map getProperties() { + return properties; + } + + public List getExtraIUs() { + return extraIUs; + } + + public void setExtraIUs(List extraIUs) { + this.extraIUs = extraIUs; + } + + public void setAdditionalRequirements(Collection requirements) { + additionalRequirements = requirements; + } + + public Collection getAdditionalRequirements() { + return additionalRequirements; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningPlan.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningPlan.java new file mode 100644 index 000000000..5ea81fb7b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningPlan.java @@ -0,0 +1,162 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.*; + +/** + * @since 2.0 + */ +public class ProvisioningPlan implements IProvisioningPlan { + IStatus status; + Operand[] operands; + Map actualChangeRequest; + Map sideEffectChanges; + IProvisioningPlan installerPlan; + IStatus globalRequestStatus; + IProfile profile; + IQueryable completeState; + private final ProvisioningContext context; + + public ProvisioningPlan(IProfile profile, Operand[] operands, ProvisioningContext context) { + this(Status.OK_STATUS, operands, null, Status.OK_STATUS, null, profile, null, context); + } + + public ProvisioningPlan(IStatus status, IProfile profile, IProvisioningPlan installerPlan, ProvisioningContext context) { + this(status, new Operand[0], null, null, installerPlan, profile, null, null); + } + + public ProvisioningPlan(IStatus status, Operand[] operands, Map[] actualChangeRequest, IStatus globalStatus, IProvisioningPlan installerPlan, IProfile profile, IQueryable futureState, ProvisioningContext context) { + this.status = status; + this.operands = operands; + if (actualChangeRequest != null) { + this.actualChangeRequest = actualChangeRequest[0]; + this.sideEffectChanges = actualChangeRequest[1]; + } + this.globalRequestStatus = globalStatus; + this.installerPlan = installerPlan; + this.profile = profile; + if (futureState == null) { + futureState = new IQueryable() { + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return Collector.emptyCollector(); + } + }; + } + completeState = futureState; + if (context == null) + context = new ProvisioningContext(); + this.context = context; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.engine.IProvisioningPlan#getStatus() + */ + public IStatus getStatus() { + return status; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.engine.IProvisioningPlan#getProfile() + */ + public IProfile getProfile() { + return profile; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.engine.IProvisioningPlan#getOperands() + */ + public Operand[] getOperands() { + return operands; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.engine.IProvisioningPlan#getRemovals() + */ + public IQueryable getRemovals() { + return new QueryablePlan(false); + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.engine.IProvisioningPlan#getAdditions() + */ + public IQueryable getAdditions() { + return new QueryablePlan(true); + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.engine.IProvisioningPlan#getRequestStatus(org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit) + */ + public IStatus getRequestStatus(IInstallableUnit iu) { + if (actualChangeRequest == null) + return null; + return actualChangeRequest.get(iu); + } + + public IStatus getRequestStatus() { + return globalRequestStatus; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.engine.IProvisioningPlan#getSideEffectChanges() + */ + public Map getSideEffectChanges() { + if (sideEffectChanges == null) + return CollectionUtils.emptyMap(); + return sideEffectChanges; + } + + private class QueryablePlan implements IQueryable { + private boolean addition; + + public QueryablePlan(boolean add) { + this.addition = add; + } + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + if (operands == null || status.getSeverity() == IStatus.ERROR) + return Collector.emptyCollector(); + Collection list = new ArrayList(); + for (int i = 0; i < operands.length; i++) { + if (!(operands[i] instanceof InstallableUnitOperand)) + continue; + InstallableUnitOperand op = ((InstallableUnitOperand) operands[i]); + IInstallableUnit iu = addition ? op.second() : op.first(); + if (iu != null) + list.add(iu); + } + return query.perform(list.iterator()); + } + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.engine.IProvisioningPlan#getInstallerPlan() + */ + public IProvisioningPlan getInstallerPlan() { + return installerPlan; + } + + public ProvisioningContext getContext() { + return context; + } + + public void setInstallerPlan(IProvisioningPlan p) { + installerPlan = p; + } + + public IQueryable getCompleteState() { + return completeState; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/RollbackOperationEvent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/RollbackOperationEvent.java new file mode 100644 index 000000000..e56813696 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/RollbackOperationEvent.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.engine.PhaseSet; + +/** + * @since 2.0 + */ +public class RollbackOperationEvent extends TransactionEvent { + + private static final long serialVersionUID = -2076492953949691215L; + private IStatus cause; + + public RollbackOperationEvent(IProfile profile, PhaseSet phaseSet, Operand[] operands, IEngine engine, IStatus cause) { + super(profile, phaseSet, operands, engine); + this.cause = cause; + } + + public IStatus getStatus() { + return cause; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/TransactionEvent.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/TransactionEvent.java new file mode 100644 index 000000000..2ce52a3b7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/TransactionEvent.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine; + +import java.util.EventObject; +import org.eclipse.equinox.internal.p2.engine.PhaseSet; + +/** + * @since 2.0 + */ +public abstract class TransactionEvent extends EventObject { + private static final long serialVersionUID = 6278706971855493984L; + protected IProfile profile; + protected PhaseSet phaseSet; + protected Operand[] operands; + + public TransactionEvent(IProfile profile, PhaseSet phaseSet, Operand[] operands, IEngine engine) { + super(engine); + this.profile = profile; + this.phaseSet = phaseSet; + this.operands = operands; + } + + public IProfile getProfile() { + return profile; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/package.html b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/package.html new file mode 100644 index 000000000..8cf851643 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/package.html @@ -0,0 +1,22 @@ + + + + + Package-level Javadoc + + +Provides support for interacting with the p2 provisioning engine +

    +Package Specification

    +

    +This package specifies API for interacting with the p2 provisioning engine. The engine +is a naive service that blindly performs a set of requested changes to a provisioned +system. No attempt is made to resolve dependencies or determine whether the +resulting system is valid or consistent. It is assumed that the engine client has +crafted a valid provisioning plan for the engine to perform, typically by using a planner +service. +

    +@since 2.0 +

    + + diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/query/IUProfilePropertyQuery.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/query/IUProfilePropertyQuery.java new file mode 100644 index 000000000..84437a6f6 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/query/IUProfilePropertyQuery.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine.query; + +import org.eclipse.equinox.internal.p2.metadata.query.IUPropertyQuery; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; + +/** + * A query that searches for {@link IInstallableUnit} instances that have + * a property associated with the specified profile, whose value matches the provided value. + * @since 2.0 + */ +public class IUProfilePropertyQuery extends IUPropertyQuery { + private IProfile profile; + + /** + * @noreference This method is not intended to be referenced by clients. + */ + public void setProfile(IProfile profile) { + this.profile = profile; + } + + /** + * Creates a new query on the given property name and value. + * Because the queryable for this query is typically the profile + * instance, we use a reference to the profile rather than the + * profile id for performance reasons. + */ + public IUProfilePropertyQuery(String propertyName, String propertyValue) { + super(propertyName, propertyValue); + } + + protected String getProperty(IInstallableUnit iu, String name) { + if (profile == null) + return null; + return profile.getInstallableUnitProperty(iu, name); + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/query/UserVisibleRootQuery.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/query/UserVisibleRootQuery.java new file mode 100644 index 000000000..20ea0d011 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/query/UserVisibleRootQuery.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine.query; + +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; + + +/** + * A query matching all the {@link IInstallableUnit}s that are marked visible to the user. + * @since 2.0 + */ +public class UserVisibleRootQuery extends IUProfilePropertyQuery { + + public UserVisibleRootQuery() { + super(IProfile.PROP_PROFILE_ROOT_IU, Boolean.TRUE.toString()); + } + + /** + * Test if the {@link IInstallableUnit}, in the context of a {@link IProfile} is visible to the user + * @param iu the element being tested. + * @param profile the context in which the iu is tested + * @return true if the element is visible to the user. + */ + public static boolean isUserVisible(IInstallableUnit iu, IProfile profile) { + String value = profile.getInstallableUnitProperty(iu, IProfile.PROP_PROFILE_ROOT_IU); + if (value != null && (value.equals(Boolean.TRUE.toString()))) + return true; + return false; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/spi/Memento.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/spi/Memento.java new file mode 100644 index 000000000..fdcb4dbb7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/spi/Memento.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine.spi; + +import java.util.*; + +/** + * @since 2.0 + */ +public class Memento { + private static final long serialVersionUID = 3257399736837461585L; + private static final Collection> simples = Arrays.> asList(String.class, Integer.class, Long.class, Float.class, Double.class, Byte.class, Short.class, Character.class, Boolean.class); + private static final Collection> simpleArrays = Arrays.> asList(String[].class, Integer[].class, Long[].class, Float[].class, Double[].class, Byte[].class, Short[].class, Character[].class, Boolean[].class); + private static final Collection> primitiveArrays = Arrays.> asList(long[].class, int[].class, short[].class, char[].class, byte[].class, double[].class, float[].class, boolean[].class); + + Map mementoMap = new HashMap(); + + public Object remove(String key) { + if (key == null) + throw new NullPointerException(); + + // TODO: persist change + return mementoMap.remove(key); + } + + public Object put(String key, Object value) { + if (key == null) + throw new NullPointerException(); + + validateValue(value); + + // TODO: persist change + return mementoMap.put(key, value); + } + + public Object get(String key) { + if (key == null) + throw new NullPointerException(); + + return mementoMap.get(key); + } + + public Enumeration getKeys() { + return new Enumeration() { + Iterator keysIterator = mementoMap.keySet().iterator(); + + public boolean hasMoreElements() { + return keysIterator.hasNext(); + } + + public String nextElement() { + return keysIterator.next(); + } + }; + } + + private static void validateValue(Object value) { + if (value == null) + return; + + Class clazz = value.getClass(); + + if (simples.contains(clazz)) + return; + + if (simpleArrays.contains(clazz) || primitiveArrays.contains(clazz)) + return; + + throw new IllegalArgumentException(clazz.getName()); + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/spi/ProvisioningAction.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/spi/ProvisioningAction.java new file mode 100644 index 000000000..2154abcc1 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/spi/ProvisioningAction.java @@ -0,0 +1,40 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine.spi; + +import java.util.Map; +import org.eclipse.core.runtime.IStatus; + +/** + * @since 2.0 + */ +public abstract class ProvisioningAction { + + private Memento memento = new Memento(); + private Touchpoint touchpoint; + + protected Memento getMemento() { + return memento; + } + + public abstract IStatus execute(Map parameters); + + public abstract IStatus undo(Map parameters); + + // TODO: these probably should not be visible + public void setTouchpoint(Touchpoint touchpoint) { + this.touchpoint = touchpoint; + } + + public Touchpoint getTouchpoint() { + return touchpoint; + } +} diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/spi/Touchpoint.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/spi/Touchpoint.java new file mode 100644 index 000000000..bbcc51b60 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/spi/Touchpoint.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.engine.spi; + +import java.util.Map; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.engine.PhaseSet; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.Operand; + +/** + * A touchpoint is responsible for executing a given phase for a given + * targeted system (eclipse, native). The order of phases is defined in the {@link PhaseSet}. + * @since 2.0 + */ +public abstract class Touchpoint { + + /** NOT API -- this is for backwards compatibility only */ + public String qualifyAction(String actionId) { + return actionId; + } + + public IStatus initializePhase(IProgressMonitor monitor, IProfile profile, String phaseId, Map touchpointParameters) { + return Status.OK_STATUS; + } + + public IStatus completePhase(IProgressMonitor monitor, IProfile profile, String phaseId, Map touchpointParameters) { + return Status.OK_STATUS; + } + + public IStatus initializeOperand(IProfile profile, Operand operand, Map parameters) { + return Status.OK_STATUS; + } + + public IStatus completeOperand(IProfile profile, Operand operand, Map parameters) { + return Status.OK_STATUS; + } + + public IStatus prepare(IProfile profile) { + return Status.OK_STATUS; + } + + public IStatus commit(IProfile profile) { + return Status.OK_STATUS; + } + + public IStatus rollback(IProfile profile) { + return Status.OK_STATUS; + } +} diff --git a/bundles/org.eclipse.equinox.p2.exemplarysetup/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.exemplarysetup/META-INF/MANIFEST.MF index be65c2321..9ec90fc16 100644 --- a/bundles/org.eclipse.equinox.p2.exemplarysetup/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.exemplarysetup/META-INF/MANIFEST.MF @@ -5,21 +5,18 @@ Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-Localization: plugin Bundle-Version: 1.0.100.qualifier -Import-Package: org.eclipse.equinox.internal.p2.core, - org.eclipse.equinox.internal.p2.core.helpers, - org.eclipse.equinox.internal.p2.director, - org.eclipse.equinox.internal.p2.engine, +Import-Package: org.eclipse.equinox.internal.p2.core.helpers, org.eclipse.equinox.internal.p2.garbagecollector, - org.eclipse.equinox.internal.p2.metadata.repository, - org.eclipse.equinox.internal.p2.repository.helpers, org.eclipse.equinox.internal.provisional.p2.core.eventbus, - org.eclipse.equinox.internal.provisional.p2.core.location, org.eclipse.equinox.internal.provisional.p2.director, - org.eclipse.equinox.internal.provisional.p2.engine, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.metadata, org.osgi.framework;version="1.3.0" Bundle-ActivationPolicy: lazy Bundle-Activator: org.eclipse.equinox.internal.p2.exemplarysetup.Activator Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, J2SE-1.4 Export-Package: org.eclipse.equinox.internal.p2.exemplarysetup;x-internal:=true +Require-Bundle: org.eclipse.equinox.common;bundle-version="3.5.100" diff --git a/bundles/org.eclipse.equinox.p2.exemplarysetup/src/org/eclipse/equinox/internal/p2/exemplarysetup/Activator.java b/bundles/org.eclipse.equinox.p2.exemplarysetup/src/org/eclipse/equinox/internal/p2/exemplarysetup/Activator.java index f35adaf57..8b45a8650 100644 --- a/bundles/org.eclipse.equinox.p2.exemplarysetup/src/org/eclipse/equinox/internal/p2/exemplarysetup/Activator.java +++ b/bundles/org.eclipse.equinox.p2.exemplarysetup/src/org/eclipse/equinox/internal/p2/exemplarysetup/Activator.java @@ -10,52 +10,96 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.exemplarysetup; -import org.eclipse.equinox.internal.p2.core.ProvisioningEventBus; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.director.SimpleDirector; -import org.eclipse.equinox.internal.p2.director.SimplePlanner; -import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.garbagecollector.GarbageCollector; -import org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; import org.eclipse.equinox.internal.provisional.p2.director.IDirector; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.*; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.osgi.framework.*; public class Activator implements BundleActivator { public static BundleContext context; + public static final String ID = "org.eclipse.equinox.p2.exemplarysetup"; //$NON-NLS-1$ + private IProvisioningAgent agent; private IProvisioningEventBus bus; - private ServiceRegistration registrationBus; + private ServiceRegistration registrationBus; private ServiceRegistration registrationDefaultManager; + private ServiceRegistration registrationDirector; + private ServiceRegistration registrationPlanner; + private ServiceRegistration registrationProfileRegistry; - // private ArtifactRepositoryManager artifactRepoManager; - // private ServiceRegistration registrationArtifactRepoManager; + /** + * Register the agent instance representing the currently running system. + * This will be the "default" agent for anyone not specifically trying to manipulate + * a different p2 agent location + */ + private void registerAgent() { + //currently location is defined by p2.core but will be defined by the agent in the future + //for now continue to treat it as a singleton + ServiceReference locationRef = context.getServiceReference(IAgentLocation.SERVICE_NAME); + if (locationRef == null) + throw new RuntimeException("Unable to instantiate p2 agent because agent location is not available"); //$NON-NLS-1$ + IAgentLocation location = (IAgentLocation) context.getService(locationRef); + if (location == null) + throw new RuntimeException("Unable to instantiate p2 agent because agent location is not available"); //$NON-NLS-1$ + + ServiceReference agentProviderRef = context.getServiceReference(IProvisioningAgentProvider.SERVICE_NAME); + IProvisioningAgentProvider provider = (IProvisioningAgentProvider) context.getService(agentProviderRef); + try { + agent = provider.createAgent(null); + } catch (Exception e) { + //we can't proceed without an agent, so fail early + final String msg = "Unable to instantiate p2 agent at location " + location.getRootLocation(); //$NON-NLS-1$ + LogHelper.log(new Status(IStatus.ERROR, ID, msg, e)); + throw new RuntimeException(msg); + } - private SimpleProfileRegistry profileRegistry; - private ServiceRegistration registrationProfileRegistry; + } - private IDirector director; - private ServiceRegistration registrationDirector; + private void registerDirector() { + IDirector director = (IDirector) agent.getService(IDirector.SERVICE_NAME); + registrationDirector = context.registerService(IDirector.SERVICE_NAME, director, null); + } - private IPlanner planner; - private ServiceRegistration registrationPlanner; + private void registerEventBus() { + bus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME); + registrationBus = context.registerService(IProvisioningEventBus.SERVICE_NAME, bus, null); + } - private AgentLocation agentLocation; + /** + * Returns a metadata repository manager, registering a service if there isn't + * one registered already. + */ + private void registerMetadataRepositoryManager() { + //make sure there isn't a repository manager already registered + if (context.getServiceReference(IMetadataRepositoryManager.SERVICE_NAME) == null) { + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME); + registrationDefaultManager = context.registerService(IMetadataRepositoryManager.SERVICE_NAME, manager, null); + } + } - private ServiceReference metadataRepositoryReference; + private void registerPlanner() { + IPlanner planner = (IPlanner) agent.getService(IPlanner.SERVICE_NAME); + registrationPlanner = context.registerService(IPlanner.SERVICE_NAME, planner, null); + } - private MetadataRepositoryManager metadataRepositoryManager; + private void registerProfileRegistry() { + IProfileRegistry profileRegistry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME); + registrationProfileRegistry = context.registerService(IProfileRegistry.SERVICE_NAME, profileRegistry, null); + } public void start(BundleContext aContext) throws Exception { //Need to do the configuration of all the bits and pieces: Activator.context = aContext; - registerAgentLocation(); + registerAgent(); registerEventBus(); //create the profile registry registerProfileRegistry(); @@ -71,12 +115,6 @@ public class Activator implements BundleActivator { // registerDefaultArtifactRepoManager(); } - private void registerAgentLocation() { - //currently this is defined by p2.core but will be defined by the agent in the future - //for now continue to treat it as a singleton - agentLocation = (AgentLocation) ServiceHelper.getService(context, AgentLocation.SERVICE_NAME); - } - private void startGarbageCollector() { new GarbageCollector(); } @@ -88,87 +126,49 @@ public class Activator implements BundleActivator { unregisterDefaultMetadataRepoManager(); unregisterProfileRegistry(); unregisterEventBus(); + unregisterAgent(); Activator.context = null; } - private void registerDirector() { - IEngine engine = (IEngine) ServiceHelper.getService(context, IEngine.SERVICE_NAME); - director = new SimpleDirector(engine, planner); - registrationDirector = context.registerService(IDirector.SERVICE_NAME, director, null); + private void unregisterAgent() { + if (agent != null) { + agent.stop(); + agent = null; + } + } + + private void unregisterDefaultMetadataRepoManager() { + //unregister the service if we registered it + if (registrationDefaultManager != null) { + registrationDefaultManager.unregister(); + registrationDefaultManager = null; + } } private void unregisterDirector() { registrationDirector.unregister(); registrationDirector = null; - director = null; } - private void registerPlanner() { - planner = new SimplePlanner(profileRegistry, metadataRepositoryManager); - registrationPlanner = context.registerService(IPlanner.SERVICE_NAME, planner, null); + private void unregisterEventBus() { + if (registrationBus != null) { + registrationBus.unregister(); + registrationBus = null; + } + if (bus != null) { + bus.close(); + bus = null; + } } private void unregisterPlanner() { registrationPlanner.unregister(); registrationPlanner = null; - planner = null; - } - - private void registerProfileRegistry() { - profileRegistry = new SimpleProfileRegistry(SimpleProfileRegistry.getDefaultRegistryDirectory(agentLocation)); - profileRegistry.setEventBus(bus); - registrationProfileRegistry = context.registerService(IProfileRegistry.class.getName(), profileRegistry, null); - Engine engine = (Engine) ServiceHelper.getService(context, IEngine.SERVICE_NAME); - if (engine != null) - engine.setProfileRegistry(profileRegistry); } private void unregisterProfileRegistry() { registrationProfileRegistry.unregister(); registrationProfileRegistry = null; - profileRegistry = null; - } - - /** - * Returns a metadata repository manager, registering a service if there isn't - * one registered already. - */ - private void registerMetadataRepositoryManager() { - //register a metadata repository manager if there isn't one already registered - metadataRepositoryReference = context.getServiceReference(IMetadataRepositoryManager.SERVICE_NAME); - if (metadataRepositoryReference == null) { - metadataRepositoryManager = new MetadataRepositoryManager(); - metadataRepositoryManager.setEventBus(bus); - registrationDefaultManager = context.registerService(IMetadataRepositoryManager.SERVICE_NAME, metadataRepositoryManager, null); - metadataRepositoryReference = registrationDefaultManager.getReference(); - } else { - metadataRepositoryManager = (MetadataRepositoryManager) context.getService(metadataRepositoryReference); - } - } - - private void unregisterDefaultMetadataRepoManager() { - //unget the service obtained for the metadata cache - if (metadataRepositoryReference != null) { - context.ungetService(metadataRepositoryReference); - metadataRepositoryReference = null; - } - - //unregister the service if we registered it - if (registrationDefaultManager != null) { - registrationDefaultManager.unregister(); - registrationDefaultManager = null; - } - } - - private void registerEventBus() { - bus = new ProvisioningEventBus(); - registrationBus = context.registerService(IProvisioningEventBus.SERVICE_NAME, bus, null); - } - - private void unregisterEventBus() { - registrationBus.unregister(); - registrationBus = null; - bus.close(); } } diff --git a/bundles/org.eclipse.equinox.p2.extensionlocation/.classpath b/bundles/org.eclipse.equinox.p2.extensionlocation/.classpath index 6f3b481ac..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.extensionlocation/.classpath +++ b/bundles/org.eclipse.equinox.p2.extensionlocation/.classpath @@ -1,6 +1,6 @@ - + diff --git a/bundles/org.eclipse.equinox.p2.extensionlocation/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.extensionlocation/.settings/org.eclipse.jdt.core.prefs index aceba4d02..e742b02fa 100644 --- a/bundles/org.eclipse.equinox.p2.extensionlocation/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.extensionlocation/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Thu Nov 20 12:57:22 PST 2008 +#Tue Dec 22 19:30:45 CET 2009 eclipse.preferences.version=1 instance/org.eclipse.core.net/org.eclipse.core.net.hasMigrated=true org.eclipse.jdt.core.builder.cleanOutputFolder=clean @@ -8,24 +8,24 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fieldHiding=warning org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning @@ -72,7 +72,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=en org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 diff --git a/bundles/org.eclipse.equinox.p2.extensionlocation/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.extensionlocation/META-INF/MANIFEST.MF index f553d5c19..c88a837bc 100644 --- a/bundles/org.eclipse.equinox.p2.extensionlocation/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.extensionlocation/META-INF/MANIFEST.MF @@ -6,24 +6,28 @@ Bundle-Localization: plugin Bundle-Version: 1.0.100.qualifier Bundle-SymbolicName: org.eclipse.equinox.p2.extensionlocation;singleton:=true Bundle-Activator: org.eclipse.equinox.internal.p2.extensionlocation.Activator -Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, - J2SE-1.4 +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 Export-Package: org.eclipse.equinox.internal.p2.extensionlocation;x-friends:="org.eclipse.equinox.p2.reconciler.dropins" -Import-Package: org.eclipse.equinox.internal.p2.core.helpers, +Import-Package: org.eclipse.equinox.internal.p2.artifact.repository.simple, + org.eclipse.equinox.internal.p2.core.helpers, + org.eclipse.equinox.internal.p2.metadata.repository, org.eclipse.equinox.internal.p2.publisher.eclipse, org.eclipse.equinox.internal.p2.touchpoint.eclipse, org.eclipse.equinox.internal.p2.update, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.directorywatcher, - org.eclipse.equinox.internal.provisional.p2.engine, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.p2.repository, - org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository, - org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.spi.p2.repository, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.engine, org.eclipse.equinox.p2.publisher.eclipse, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.artifact.spi, + org.eclipse.equinox.p2.repository.metadata, + org.eclipse.equinox.p2.repository.metadata.spi, + org.eclipse.equinox.p2.repository.spi, org.eclipse.osgi.service.datalocation;version="1.1.0", org.eclipse.osgi.service.resolver;version="1.2.0", org.eclipse.osgi.util, diff --git a/bundles/org.eclipse.equinox.p2.extensionlocation/build.properties b/bundles/org.eclipse.equinox.p2.extensionlocation/build.properties index 39459475f..668447566 100644 --- a/bundles/org.eclipse.equinox.p2.extensionlocation/build.properties +++ b/bundles/org.eclipse.equinox.p2.extensionlocation/build.properties @@ -17,3 +17,5 @@ bin.includes = META-INF/,\ about.html source.. = src/ src.includes = about.html +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/Activator.java b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/Activator.java index a6aa54387..e6011a608 100644 --- a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/Activator.java +++ b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/Activator.java @@ -17,9 +17,10 @@ import org.eclipse.core.runtime.URIUtil; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.core.helpers.URLUtil; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.osgi.service.datalocation.Location; import org.osgi.framework.*; @@ -63,7 +64,7 @@ public class Activator implements BundleActivator { } public static IProfile getCurrentProfile() { - ServiceReference reference = bundleContext.getServiceReference(IProfileRegistry.class.getName()); + ServiceReference reference = bundleContext.getServiceReference(IProfileRegistry.SERVICE_NAME); if (reference == null) return null; IProfileRegistry profileRegistry = (IProfileRegistry) bundleContext.getService(reference); @@ -74,21 +75,20 @@ public class Activator implements BundleActivator { } } - public static IFileArtifactRepository getBundlePoolRepository() { - ServiceReference reference = bundleContext.getServiceReference(IProfileRegistry.class.getName()); + public static IProvisioningAgent getCurrentAgent() { + ServiceReference reference = bundleContext.getServiceReference(IProvisioningAgent.class.getName()); if (reference == null) return null; - IProfileRegistry profileRegistry = (IProfileRegistry) bundleContext.getService(reference); - IProfile profile = null; - try { - profile = profileRegistry.getProfile(IProfileRegistry.SELF); - } finally { - bundleContext.ungetService(reference); - } - if (profile == null) + return (IProvisioningAgent) bundleContext.getService(reference); + } + + public static IFileArtifactRepository getBundlePoolRepository() { + IProfile profile = getCurrentProfile(); + IProvisioningAgent agent = getCurrentAgent(); + if (profile == null || agent == null) return null; - return Util.getAggregatedBundleRepository(profile, Util.AGGREGATE_CACHE | Util.AGGREGATE_SHARED_CACHE); + return Util.getAggregatedBundleRepository(agent, profile, Util.AGGREGATE_CACHE | Util.AGGREGATE_SHARED_CACHE); } /** diff --git a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/BundlePoolFilteredListener.java b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/BundlePoolFilteredListener.java index 6615f0072..c109aafb3 100644 --- a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/BundlePoolFilteredListener.java +++ b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/BundlePoolFilteredListener.java @@ -10,25 +10,28 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.extensionlocation; +import org.eclipse.equinox.p2.query.IQueryResult; + import java.io.File; -import java.util.HashSet; -import java.util.Set; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; +import java.util.*; import org.eclipse.equinox.internal.provisional.p2.directorywatcher.DirectoryChangeListener; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.ArtifactKeyQuery; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; public class BundlePoolFilteredListener extends DirectoryChangeListener { private DirectoryChangeListener delegate; - private Set bundlePoolFiles = new HashSet(); + private Set bundlePoolFiles = new HashSet(); public BundlePoolFilteredListener(DirectoryChangeListener listener) { delegate = listener; IFileArtifactRepository bundlePool = Activator.getBundlePoolRepository(); if (bundlePool != null) { - IArtifactKey[] keys = bundlePool.getArtifactKeys(); - for (int i = 0; i < keys.length; i++) { - File artifactFile = bundlePool.getArtifactFile(keys[i]); + IQueryResult keys = bundlePool.query(ArtifactKeyQuery.ALL_KEYS, null); + for (Iterator iterator = keys.iterator(); iterator.hasNext();) { + IArtifactKey key = iterator.next(); + File artifactFile = bundlePool.getArtifactFile(key); if (artifactFile != null) bundlePoolFiles.add(artifactFile); } diff --git a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationArtifactRepository.java b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationArtifactRepository.java index 0d67e3da8..6879cff7b 100644 --- a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationArtifactRepository.java +++ b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationArtifactRepository.java @@ -15,18 +15,19 @@ import java.io.*; import java.net.URI; import java.util.*; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.spi.p2.repository.AbstractRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.spi.AbstractRepository; import org.eclipse.osgi.util.NLS; import org.osgi.framework.BundleContext; -public class ExtensionLocationArtifactRepository extends AbstractRepository implements IFileArtifactRepository, Constants { +public class ExtensionLocationArtifactRepository extends AbstractRepository implements IFileArtifactRepository, Constants { public static final String TYPE = "org.eclipse.equinox.p2.extensionlocation.artifactRepository"; //$NON-NLS-1$ public static final Integer VERSION = new Integer(1); - public static final List STANDARD_P2_REPOSITORY_FILE_NAMES = Arrays.asList(new Object[] {"artifacts.xml", "content.xml", "compositeArtifacts.xml", "compositeContent.xml"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + public static final List STANDARD_P2_REPOSITORY_FILE_NAMES = Arrays.asList(new String[] {"artifacts.xml", "content.xml", "compositeArtifacts.xml", "compositeContent.xml"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ IFileArtifactRepository artifactRepository; private File base; @@ -186,11 +187,6 @@ public class ExtensionLocationArtifactRepository extends AbstractRepository impl return artifactRepository.getArtifactDescriptors(key); } - public IArtifactKey[] getArtifactKeys() { - ensureInitialized(); - return artifactRepository.getArtifactKeys(); - } - public IStatus getArtifacts(IArtifactRequest[] requests, IProgressMonitor monitor) { ensureInitialized(); return artifactRepository.getArtifacts(requests, monitor); @@ -211,7 +207,7 @@ public class ExtensionLocationArtifactRepository extends AbstractRepository impl return artifactRepository.getArtifactFile(descriptor); } - public Map getProperties() { + public Map getProperties() { ensureInitialized(); return artifactRepository.getProperties(); } @@ -229,4 +225,18 @@ public class ExtensionLocationArtifactRepository extends AbstractRepository impl ensureInitialized(); return oldValue; } + + public IArtifactDescriptor createArtifactDescriptor(IArtifactKey key) { + return artifactRepository.createArtifactDescriptor(key); + } + + public IQueryable descriptorQueryable() { + ensureInitialized(); + return artifactRepository.descriptorQueryable(); + } + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + ensureInitialized(); + return artifactRepository.query(query, monitor); + } } diff --git a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationArtifactRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationArtifactRepositoryFactory.java index 32a2bb9c3..9abf2f37e 100644 --- a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationArtifactRepositoryFactory.java +++ b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationArtifactRepositoryFactory.java @@ -13,12 +13,12 @@ package org.eclipse.equinox.internal.p2.extensionlocation; import java.net.URI; import java.util.Map; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.ArtifactRepositoryFactory; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.SimpleArtifactRepositoryFactory; +import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepositoryFactory; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactRepositoryFactory; import org.eclipse.osgi.util.NLS; public class ExtensionLocationArtifactRepositoryFactory extends ArtifactRepositoryFactory { @@ -26,7 +26,7 @@ public class ExtensionLocationArtifactRepositoryFactory extends ArtifactReposito /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.ArtifactRepositoryFactory#create(java.net.URL, java.lang.String, java.lang.String, java.util.Map) */ - public IArtifactRepository create(URI location, String name, String type, Map properties) throws ProvisionException { + public IArtifactRepository create(URI location, String name, String type, Map properties) throws ProvisionException { // TODO proper progress monitoring IStatus status = validate(location, null); if (!status.isOK()) @@ -38,8 +38,10 @@ public class ExtensionLocationArtifactRepositoryFactory extends ArtifactReposito // make sure that we aren't trying to create a repo at a location // where one already exists boolean failed = false; + final SimpleArtifactRepositoryFactory simpleFactory = new SimpleArtifactRepositoryFactory(); + simpleFactory.setAgent(getAgent()); try { - new SimpleArtifactRepositoryFactory().load(repoLocation, 0, null); + simpleFactory.load(repoLocation, 0, null); failed = true; } catch (ProvisionException e) { // expected @@ -48,7 +50,7 @@ public class ExtensionLocationArtifactRepositoryFactory extends ArtifactReposito String msg = NLS.bind(Messages.repo_already_exists, location); throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_EXISTS, msg, null)); } - IFileArtifactRepository repo = (IFileArtifactRepository) new SimpleArtifactRepositoryFactory().create(repoLocation, name, type, properties); + IFileArtifactRepository repo = (IFileArtifactRepository) simpleFactory.create(repoLocation, name, type, properties); return new ExtensionLocationArtifactRepository(location, repo, null); } @@ -71,7 +73,9 @@ public class ExtensionLocationArtifactRepositoryFactory extends ArtifactReposito throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, Messages.failed_create_local_artifact_repository)); // TODO proper progress monitoring try { - IFileArtifactRepository repo = (IFileArtifactRepository) new SimpleArtifactRepositoryFactory().load(repoLocation, flags, null); + final SimpleArtifactRepositoryFactory simpleFactory = new SimpleArtifactRepositoryFactory(); + simpleFactory.setAgent(getAgent()); + IFileArtifactRepository repo = (IFileArtifactRepository) simpleFactory.load(repoLocation, flags, null); return new ExtensionLocationArtifactRepository(location, repo, monitor); } catch (ProvisionException e) { return create(location, Activator.getRepositoryName(location), ExtensionLocationArtifactRepository.TYPE, null); diff --git a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationMetadataRepository.java b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationMetadataRepository.java index 64c7c2bb4..4db1830f2 100644 --- a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationMetadataRepository.java +++ b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationMetadataRepository.java @@ -16,12 +16,12 @@ import java.io.FilenameFilter; import java.net.URI; import java.util.*; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.AbstractMetadataRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.spi.AbstractMetadataRepository; import org.eclipse.osgi.util.NLS; import org.osgi.framework.BundleContext; @@ -96,16 +96,16 @@ public class ExtensionLocationMetadataRepository extends AbstractMetadataReposit /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository#removeInstallableUnits(org.eclipse.equinox.internal.provisional.p2.query.Query, org.eclipse.core.runtime.IProgressMonitor) */ - public boolean removeInstallableUnits(Query query, IProgressMonitor monitor) { + public boolean removeInstallableUnits(IInstallableUnit[] installableUnits, IProgressMonitor monitor) { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.query.IQueryable#query(org.eclipse.equinox.internal.provisional.p2.query.Query, org.eclipse.equinox.internal.provisional.p2.query.Collector, org.eclipse.core.runtime.IProgressMonitor) */ - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { + public IQueryResult query(IQuery query, IProgressMonitor monitor) { ensureInitialized(); - return metadataRepository.query(query, collector, monitor); + return metadataRepository.query(query, monitor); } public static void validate(URI location, IProgressMonitor monitor) throws ProvisionException { @@ -172,9 +172,9 @@ public class ExtensionLocationMetadataRepository extends AbstractMetadataReposit } /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.spi.p2.repository.AbstractRepository#getProperties() + * @see org.eclipse.equinox.p2.repository.spi.AbstractRepository#getProperties() */ - public Map getProperties() { + public Map getProperties() { ensureInitialized(); return metadataRepository.getProperties(); } diff --git a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationMetadataRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationMetadataRepositoryFactory.java index 06799588c..422a3a327 100644 --- a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationMetadataRepositoryFactory.java +++ b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/ExtensionLocationMetadataRepositoryFactory.java @@ -10,22 +10,25 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.extensionlocation; +import org.eclipse.equinox.internal.p2.metadata.repository.SimpleMetadataRepositoryFactory; + +import org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory; + +import org.eclipse.equinox.p2.core.ProvisionException; + import java.net.URI; import java.util.Map; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.SimpleMetadataRepositoryFactory; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.osgi.util.NLS; public class ExtensionLocationMetadataRepositoryFactory extends MetadataRepositoryFactory { /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory#create(java.net.URL, java.lang.String, java.lang.String, java.util.Map) + * @see org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory#create(java.net.URL, java.lang.String, java.lang.String, java.util.Map) */ - public IMetadataRepository create(URI location, String name, String type, Map properties) throws ProvisionException { + public IMetadataRepository create(URI location, String name, String type, Map properties) throws ProvisionException { // TODO proper progress monitoring IStatus status = validate(location, null); if (!status.isOK()) @@ -37,8 +40,10 @@ public class ExtensionLocationMetadataRepositoryFactory extends MetadataReposito // ensure that we aren't trying to create a repository at a location // where one already exists boolean failed = false; + final SimpleMetadataRepositoryFactory simpleFactory = new SimpleMetadataRepositoryFactory(); + simpleFactory.setAgent(getAgent()); try { - new SimpleMetadataRepositoryFactory().load(repoLocation, 0, null); + simpleFactory.load(repoLocation, 0, null); failed = true; } catch (ProvisionException e) { // expected @@ -47,12 +52,12 @@ public class ExtensionLocationMetadataRepositoryFactory extends MetadataReposito String msg = NLS.bind(Messages.repo_already_exists, location.toString()); throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_EXISTS, msg, null)); } - IMetadataRepository repository = new SimpleMetadataRepositoryFactory().create(repoLocation, name, null, properties); + IMetadataRepository repository = simpleFactory.create(repoLocation, name, null, properties); return new ExtensionLocationMetadataRepository(location, repository, null); } /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory#load(java.net.URL, org.eclipse.core.runtime.IProgressMonitor) + * @see org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory#load(java.net.URL, org.eclipse.core.runtime.IProgressMonitor) */ public IMetadataRepository load(URI location, int flags, IProgressMonitor monitor) throws ProvisionException { //return null if the caller wanted a modifiable repo @@ -70,7 +75,9 @@ public class ExtensionLocationMetadataRepositoryFactory extends MetadataReposito throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, Messages.failed_create_local_artifact_repository)); // TODO proper progress monitoring try { - IMetadataRepository repository = new SimpleMetadataRepositoryFactory().load(repoLocation, flags, null); + final SimpleMetadataRepositoryFactory simpleFactory = new SimpleMetadataRepositoryFactory(); + simpleFactory.setAgent(getAgent()); + IMetadataRepository repository = simpleFactory.load(repoLocation, flags, null); return new ExtensionLocationMetadataRepository(location, repository, monitor); } catch (ProvisionException e) { return create(location, Activator.getRepositoryName(location), ExtensionLocationMetadataRepository.TYPE, null); @@ -78,7 +85,7 @@ public class ExtensionLocationMetadataRepositoryFactory extends MetadataReposito } /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory#validate(java.net.URL, org.eclipse.core.runtime.IProgressMonitor) + * @see org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory#validate(java.net.URL, org.eclipse.core.runtime.IProgressMonitor) */ public IStatus validate(URI location, IProgressMonitor monitor) { try { diff --git a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/SiteListener.java b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/SiteListener.java index 05113e87b..4858af478 100644 --- a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/SiteListener.java +++ b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/SiteListener.java @@ -11,6 +11,8 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.extensionlocation; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.*; import java.net.URI; import java.net.URISyntaxException; @@ -19,7 +21,6 @@ import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.publisher.eclipse.FeatureParser; import org.eclipse.equinox.internal.p2.update.Site; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.directorywatcher.*; import org.eclipse.equinox.p2.publisher.eclipse.*; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -105,16 +106,16 @@ public class SiteListener extends DirectoryChangeListener { /* * Create a new site listener on the given site. */ - public SiteListener(Map properties, String url, DirectoryChangeListener delegate) { + public SiteListener(Map properties, String url, DirectoryChangeListener delegate) { this.siteLocation = url; this.delegate = delegate; - this.policy = (String) properties.get(SITE_POLICY); - Collection listCollection = new HashSet(); - String listString = (String) properties.get(SITE_LIST); + this.policy = properties.get(SITE_POLICY); + Collection listCollection = new HashSet(); + String listString = properties.get(SITE_LIST); if (listString != null) for (StringTokenizer tokenizer = new StringTokenizer(listString, ","); tokenizer.hasMoreTokens();) //$NON-NLS-1$ listCollection.add(tokenizer.nextToken()); - this.list = (String[]) listCollection.toArray(new String[listCollection.size()]); + this.list = listCollection.toArray(new String[listCollection.size()]); } /* (non-Javadoc) @@ -220,8 +221,8 @@ public class SiteListener extends DirectoryChangeListener { String urlString = siteLocation; if (urlString.endsWith(Constants.EXTENSION_LOCATION)) urlString = urlString.substring(0, urlString.length() - Constants.EXTENSION_LOCATION.length()); - List result = new ArrayList(); - for (Enumeration e = properties.elements(); e.hasMoreElements();) { + List result = new ArrayList(); + for (Enumeration e = properties.elements(); e.hasMoreElements();) { String line = (String) e.nextElement(); StringTokenizer tokenizer = new StringTokenizer(line, ";"); //$NON-NLS-1$ String targetSite = tokenizer.nextToken(); @@ -229,7 +230,7 @@ public class SiteListener extends DirectoryChangeListener { continue; result.add(tokenizer.nextToken()); } - toBeRemoved = (String[]) result.toArray(new String[result.size()]); + toBeRemoved = result.toArray(new String[result.size()]); return toBeRemoved; } @@ -241,7 +242,7 @@ public class SiteListener extends DirectoryChangeListener { private String[] getManagedFiles() { if (managedFiles != null) return managedFiles; - List result = new ArrayList(); + List result = new ArrayList(); File siteFile; try { siteFile = URIUtil.toFile(new URI(siteLocation)); @@ -249,24 +250,23 @@ public class SiteListener extends DirectoryChangeListener { LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "Unable to create a URL from site location: " + siteLocation, e)); //$NON-NLS-1$ return new String[0]; } - Map pluginCache = getPlugins(siteFile); - Map featureCache = getFeatures(siteFile); - for (Iterator iter = featureCache.keySet().iterator(); iter.hasNext();) { - File featureFile = (File) iter.next(); + Map pluginCache = getPlugins(siteFile); + Map featureCache = getFeatures(siteFile); + for (File featureFile : featureCache.keySet()) { // add the feature path result.add(featureFile.toString()); - Feature feature = (Feature) featureCache.get(featureFile); + Feature feature = featureCache.get(featureFile); FeatureEntry[] entries = feature.getEntries(); for (int inner = 0; inner < entries.length; inner++) { FeatureEntry entry = entries[inner]; // grab the right location from the plug-in cache String key = entry.getId() + '/' + entry.getVersion(); - File pluginLocation = (File) pluginCache.get(key); + File pluginLocation = pluginCache.get(key); if (pluginLocation != null) result.add(pluginLocation.toString()); } } - managedFiles = (String[]) result.toArray(new String[result.size()]); + managedFiles = result.toArray(new String[result.size()]); return managedFiles; } @@ -274,8 +274,8 @@ public class SiteListener extends DirectoryChangeListener { * Iterate over the feature directory and return a map of * File to Feature objects (from the generator bundle) */ - private Map getFeatures(File location) { - Map result = new HashMap(); + private Map getFeatures(File location) { + Map result = new HashMap(); File featureDir = new File(location, FEATURES); File[] children = featureDir.listFiles(); for (int i = 0; i < children.length; i++) { @@ -294,9 +294,9 @@ public class SiteListener extends DirectoryChangeListener { * Iterate over the plugins directory and return a map of * plug-in id/version to File locations. */ - private Map getPlugins(File location) { + private Map getPlugins(File location) { File[] plugins = new File(location, PLUGINS).listFiles(); - Map result = new HashMap(); + Map result = new HashMap(); for (int i = 0; plugins != null && i < plugins.length; i++) { File bundleLocation = plugins[i]; if (bundleLocation.isDirectory() || bundleLocation.getName().endsWith(".jar")) { //$NON-NLS-1$ diff --git a/bundles/org.eclipse.equinox.p2.garbagecollector/.classpath b/bundles/org.eclipse.equinox.p2.garbagecollector/.classpath index 7cdeb7319..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.garbagecollector/.classpath +++ b/bundles/org.eclipse.equinox.p2.garbagecollector/.classpath @@ -1,7 +1,7 @@ - - + + diff --git a/bundles/org.eclipse.equinox.p2.garbagecollector/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.garbagecollector/.settings/org.eclipse.jdt.core.prefs index 78523cd05..2d0c6c8fe 100644 --- a/bundles/org.eclipse.equinox.p2.garbagecollector/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.garbagecollector/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Thu Aug 16 11:00:59 EDT 2007 +#Tue Dec 29 18:58:34 CET 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.builder.cleanOutputFolder=clean org.eclipse.jdt.core.builder.duplicateResourceTask=warning @@ -7,24 +7,24 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fieldHiding=warning org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning @@ -62,7 +62,6 @@ org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unsafeTypeOperation=warning org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=enabled org.eclipse.jdt.core.compiler.problem.unusedImport=error @@ -72,7 +71,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=en org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 @@ -144,7 +143,6 @@ org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert diff --git a/bundles/org.eclipse.equinox.p2.garbagecollector/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.garbagecollector/META-INF/MANIFEST.MF index 74c92c083..3328c3aa7 100644 --- a/bundles/org.eclipse.equinox.p2.garbagecollector/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.garbagecollector/META-INF/MANIFEST.MF @@ -8,9 +8,14 @@ Bundle-Version: 1.0.100.qualifier Import-Package: org.eclipse.core.runtime.preferences, org.eclipse.equinox.app;version="1.0.0", org.eclipse.equinox.internal.p2.core.helpers, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, org.eclipse.equinox.internal.provisional.p2.core.eventbus, org.eclipse.equinox.internal.provisional.p2.metadata, + org.eclipse.equinox.internal.provisional.p2.repository, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository.artifact, org.eclipse.osgi.util;version="1.1.0", org.osgi.framework;version="1.4.0", org.osgi.service.prefs;version="1.1.0" @@ -20,5 +25,6 @@ Bundle-ActivationPolicy: lazy Require-Bundle: org.eclipse.equinox.p2.engine, org.eclipse.osgi;bundle-version="[3.4.0,4.0.0)", org.eclipse.equinox.registry;bundle-version="[3.4.0,4.0.0)" -Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, - J2SE-1.4 +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 diff --git a/bundles/org.eclipse.equinox.p2.garbagecollector/build.properties b/bundles/org.eclipse.equinox.p2.garbagecollector/build.properties index f84c26ec6..a8ad90604 100644 --- a/bundles/org.eclipse.equinox.p2.garbagecollector/build.properties +++ b/bundles/org.eclipse.equinox.p2.garbagecollector/build.properties @@ -17,3 +17,5 @@ bin.includes = META-INF/,\ about.html,\ plugin.properties src.includes = about.html +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/Application.java b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/Application.java index b4c63d7c6..4927b4513 100644 --- a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/Application.java +++ b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/Application.java @@ -14,8 +14,8 @@ import java.util.Map; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfileRegistry; /** * @since 1.0 @@ -29,7 +29,7 @@ public class Application implements IApplication { * Return the profile with the given id, or null if not found. */ private IProfile getProfile(String id) { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(GCActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(GCActivator.getContext(), IProfileRegistry.SERVICE_NAME); return profileRegistry == null ? null : profileRegistry.getProfile(id); } @@ -38,7 +38,7 @@ public class Application implements IApplication { */ public Object start(IApplicationContext context) throws Exception { // TODO - do we have to start exemplarySetup here? - Map allArgs = context.getArguments(); + Map allArgs = context.getArguments(); String[] args = (String[]) allArgs.get(IApplicationContext.APPLICATION_ARGS); processArguments(args); // if the user didn't give us a profile id, then use the default SDK one diff --git a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/CoreGarbageCollector.java b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/CoreGarbageCollector.java index cf0eb709a..5ee962271 100644 --- a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/CoreGarbageCollector.java +++ b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/CoreGarbageCollector.java @@ -10,9 +10,12 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.garbagecollector; +import java.util.*; import org.eclipse.equinox.internal.p2.core.helpers.Tracing; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.ArtifactKeyQuery; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; /** * Given a MarkSet, the CoreGarbageCollector removes any IArtifactDescriptors which @@ -30,20 +33,18 @@ public class CoreGarbageCollector { * in aRepository that are not mapped to by an IArtifactKey in markSet */ public synchronized void clean(IArtifactKey[] markSet, IArtifactRepository aRepository) { - IArtifactKey[] repositoryKeys = aRepository.getArtifactKeys(); - for (int j = 0; j < repositoryKeys.length; j++) { - boolean artifactIsActive = false; - for (int k = 0; k < markSet.length; k++) { - if (repositoryKeys[j].equals(markSet[k])) { - artifactIsActive = true; - break; - } + final Set set = new HashSet(Arrays.asList(markSet)); + ArtifactKeyQuery query = new ArtifactKeyQuery() { + public boolean isMatch(IArtifactKey candidate) { + return !set.contains(candidate); } - if (!artifactIsActive) { - aRepository.removeDescriptor(repositoryKeys[j]); - if (debugMode) { - Tracing.debug("Key removed:" + repositoryKeys[j]); //$NON-NLS-1$ - } + }; + IQueryResult inactive = aRepository.query(query, null); + for (Iterator iterator = inactive.iterator(); iterator.hasNext();) { + IArtifactKey key = iterator.next(); + aRepository.removeDescriptor(key); + if (debugMode) { + Tracing.debug("Key removed:" + key); //$NON-NLS-1$ } } } diff --git a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/GCActivator.java b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/GCActivator.java index 65ddf8bd9..ce225b593 100644 --- a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/GCActivator.java +++ b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/GCActivator.java @@ -10,6 +10,8 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.garbagecollector; +import org.eclipse.core.runtime.preferences.IEclipsePreferences; + import java.util.*; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; @@ -17,7 +19,7 @@ import org.eclipse.core.runtime.preferences.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.SynchronousProvisioningListener; -import org.eclipse.equinox.internal.provisional.p2.engine.*; +import org.eclipse.equinox.p2.engine.*; import org.eclipse.osgi.service.debug.DebugOptions; import org.osgi.framework.*; import org.osgi.service.prefs.Preferences; @@ -86,11 +88,11 @@ public class GCActivator implements BundleActivator { IPreferencesService prefService = (IPreferencesService) getService(context, IPreferencesService.class.getName()); if (prefService == null) return defaultValue; - List nodes = new ArrayList(); + List nodes = new ArrayList(); // todo we should look in the instance scope as well but have to be careful that the instance location has been set nodes.add(new ConfigurationScope().getNode(ID)); nodes.add(new DefaultScope().getNode(ID)); - return Boolean.valueOf(prefService.get(key, Boolean.toString(defaultValue), (Preferences[]) nodes.toArray(new Preferences[nodes.size()]))).booleanValue(); + return Boolean.valueOf(prefService.get(key, Boolean.toString(defaultValue), nodes.toArray(new Preferences[nodes.size()]))).booleanValue(); } private void unregisterGCTrigger() { diff --git a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/GarbageCollector.java b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/GarbageCollector.java index 4db8c4514..70b602ca7 100644 --- a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/GarbageCollector.java +++ b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/GarbageCollector.java @@ -13,10 +13,11 @@ package org.eclipse.equinox.internal.p2.garbagecollector; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; /** * The main control point for the p2 garbage collector. Takes a Profile and runs the CoreGarbageCollector with the @@ -36,10 +37,16 @@ public class GarbageCollector { /** * Maps IArtifactRepository objects to their respective "marked set" of IArtifactKeys */ - private Map markSet; + private Map> markSet; + final IProvisioningAgent agent; + + public GarbageCollector() { + // we need to use DS to create an Agent Listener here + agent = (IProvisioningAgent) GCActivator.getContext().getService(GCActivator.getContext().getServiceReference(IProvisioningAgent.class.getName())); + } public void runGC(IProfile profile) { - markSet = new HashMap(); + markSet = new HashMap>(); if (!traverseMainProfile(profile)) return; @@ -70,10 +77,8 @@ public class GarbageCollector { } private void invokeCoreGC() { - Iterator keyIterator = markSet.keySet().iterator(); - while (keyIterator.hasNext()) { - IArtifactRepository nextRepo = (IArtifactRepository) keyIterator.next(); - IArtifactKey[] keys = (IArtifactKey[]) ((Collection) markSet.get(nextRepo)).toArray(new IArtifactKey[0]); + for (IArtifactRepository nextRepo : markSet.keySet()) { + IArtifactKey[] keys = markSet.get(nextRepo).toArray(new IArtifactKey[0]); MarkSet aMarkSet = new MarkSet(keys, nextRepo); new CoreGarbageCollector().clean(aMarkSet.getKeys(), aMarkSet.getRepo()); } @@ -91,7 +96,7 @@ public class GarbageCollector { continue; } - IProfileRegistry profileRegistry = (IProfileRegistry) GCActivator.getService(GCActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = (IProfileRegistry) GCActivator.getService(GCActivator.getContext(), IProfileRegistry.SERVICE_NAME); if (profileRegistry == null) return; IProfile[] registeredProfiles = profileRegistry.getProfiles(); @@ -122,7 +127,7 @@ public class GarbageCollector { aProfileMarkSets = null; return; } - aProfileMarkSets = aMarkSetProvider.getMarkSets(aProfile); + aProfileMarkSets = aMarkSetProvider.getMarkSets(agent, aProfile); } public MarkSet[] getResult() { @@ -141,10 +146,10 @@ public class GarbageCollector { if (aProfileMarkSets[i] == null) { continue; } - Collection keys = (Collection) markSet.get(aProfileMarkSets[i].getRepo()); + Collection keys = markSet.get(aProfileMarkSets[i].getRepo()); if (keys == null) { if (addRepositories) { - keys = new HashSet(); + keys = new HashSet(); markSet.put(aProfileMarkSets[i].getRepo(), keys); addKeys(keys, aProfileMarkSets[i].getKeys()); } @@ -154,7 +159,7 @@ public class GarbageCollector { } } - private void addKeys(Collection keyList, IArtifactKey[] keyArray) { + private void addKeys(Collection keyList, IArtifactKey[] keyArray) { for (int i = 0; i < keyArray.length; i++) keyList.add(keyArray[i]); } diff --git a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/MarkSet.java b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/MarkSet.java index d8b2446c9..453e0d5e4 100644 --- a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/MarkSet.java +++ b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/MarkSet.java @@ -11,8 +11,8 @@ package org.eclipse.equinox.internal.p2.garbagecollector; import org.eclipse.core.runtime.Assert; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; /** * Wrapper class used to store an IArtifactRepository and its root set of IArtifactKeys. diff --git a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/MarkSetProvider.java b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/MarkSetProvider.java index edb21b3f5..f69716c8b 100644 --- a/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/MarkSetProvider.java +++ b/bundles/org.eclipse.equinox.p2.garbagecollector/src/org/eclipse/equinox/internal/p2/garbagecollector/MarkSetProvider.java @@ -10,8 +10,9 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.garbagecollector; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; /** * Any class which declares itself as an extension to the org.eclipse.equinox.p2.garbagecollector.marksetproviders @@ -28,13 +29,13 @@ public abstract class MarkSetProvider { * @param profile A profile whose ArtifactRepositories require a garbage collection * @return An array of MarkSet object(s) containing p's IArtifactRepository and its root set of IArtifactKeys */ - public abstract MarkSet[] getMarkSets(IProfile profile); + public abstract MarkSet[] getMarkSets(IProvisioningAgent agent, IProfile profile); /** * Returns the IArtifactRepository for which this MarkSetProvider provides a MarkSet. * @param p The Profile whose IArtifactRepository is required * @return The IArtifactRepository for which this MarkSetProvider provides a MarkSet. */ - public abstract IArtifactRepository getRepository(IProfile p); + public abstract IArtifactRepository getRepository(IProvisioningAgent agent, IProfile p); } diff --git a/bundles/org.eclipse.equinox.p2.installer/.classpath b/bundles/org.eclipse.equinox.p2.installer/.classpath index 7cdeb7319..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.installer/.classpath +++ b/bundles/org.eclipse.equinox.p2.installer/.classpath @@ -1,7 +1,7 @@ - - + + diff --git a/bundles/org.eclipse.equinox.p2.installer/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.installer/.settings/org.eclipse.jdt.core.prefs index 99a0b3dc6..a151b9a1f 100644 --- a/bundles/org.eclipse.equinox.p2.installer/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.installer/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Thu Oct 11 16:46:31 EDT 2007 +#Tue Dec 29 19:06:38 CET 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.builder.cleanOutputFolder=clean org.eclipse.jdt.core.builder.duplicateResourceTask=warning @@ -7,24 +7,24 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=warning @@ -69,7 +69,6 @@ org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unsafeTypeOperation=warning org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=enabled @@ -82,7 +81,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=en org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 @@ -154,7 +153,6 @@ org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert diff --git a/bundles/org.eclipse.equinox.p2.installer/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.installer/META-INF/MANIFEST.MF index 75cf0ac5d..5d60c8b4b 100644 --- a/bundles/org.eclipse.equinox.p2.installer/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.installer/META-INF/MANIFEST.MF @@ -19,8 +19,9 @@ Require-Bundle: org.eclipse.osgi, org.eclipse.swt, org.eclipse.core.net;bundle-version="1.1.0", org.eclipse.equinox.p2.repository;bundle-version="1.0.0" -Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, - J2SE-1.4 +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 Export-Package: org.eclipse.equinox.internal.p2.installer;x-internal:=true, org.eclipse.equinox.internal.p2.installer.ui;x-internal:=true, org.eclipse.equinox.internal.provisional.p2.installer;x-internal:=true diff --git a/bundles/org.eclipse.equinox.p2.installer/build.properties b/bundles/org.eclipse.equinox.p2.installer/build.properties index 973e370b6..f85c9d6ef 100644 --- a/bundles/org.eclipse.equinox.p2.installer/build.properties +++ b/bundles/org.eclipse.equinox.p2.installer/build.properties @@ -17,3 +17,5 @@ bin.includes = plugin.xml,\ about.html,\ plugin.properties src.includes = about.html +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallDescriptionParser.java b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallDescriptionParser.java index 008567ef3..989b2482e 100644 --- a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallDescriptionParser.java +++ b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallDescriptionParser.java @@ -11,16 +11,17 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.installer; -import org.eclipse.equinox.internal.provisional.p2.metadata.IVersionedId; +import org.eclipse.equinox.internal.p2.metadata.VersionedId; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.provisional.p2.installer.InstallDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionedId; +import org.eclipse.equinox.p2.metadata.IVersionedId; /** * This class is responsible for loading install descriptions from a stream. @@ -61,12 +62,10 @@ public class InstallDescriptionParser { throw new IllegalStateException("Can't find install description file: " + installerDescription); } } - in = propsURI.toURL().openStream(); - - Properties properties = new Properties(); + Map properties; try { - if (in != null) - properties.load(in); + in = propsURI.toURL().openStream(); + properties = CollectionUtils.loadProperties(in); } finally { safeClose(in); } @@ -77,7 +76,7 @@ public class InstallDescriptionParser { initializeProfileProperties(result, properties); // now override the properties from anything interesting in system properties - result = initialize(result, System.getProperties(), base); + result = initialize(result, CollectionUtils.toMap(System.getProperties()), base); return result; } @@ -93,43 +92,43 @@ public class InstallDescriptionParser { return URI.create(uriString.substring(0, slashIndex + 1)); } - private static InstallDescription initialize(InstallDescription description, Properties properties, URI base) { - String property = properties.getProperty(PROP_ARTIFACT_REPOSITORY); + private static InstallDescription initialize(InstallDescription description, Map properties, URI base) { + String property = properties.get(PROP_ARTIFACT_REPOSITORY); if (property != null) description.setArtifactRepositories(getURIs(property, base)); - property = properties.getProperty(PROP_METADATA_REPOSITORY); + property = properties.get(PROP_METADATA_REPOSITORY); if (property != null) description.setMetadataRepositories(getURIs(property, base)); - property = properties.getProperty(PROP_IS_AUTO_START); + property = properties.get(PROP_IS_AUTO_START); if (property != null) description.setAutoStart(Boolean.TRUE.toString().equalsIgnoreCase(property)); - property = properties.getProperty(PROP_LAUNCHER_NAME); + property = properties.get(PROP_LAUNCHER_NAME); if (property != null) description.setLauncherName(property); - property = properties.getProperty(PROP_INSTALL_LOCATION); + property = properties.get(PROP_INSTALL_LOCATION); if (property != null) description.setInstallLocation(new Path(property)); - property = properties.getProperty(PROP_AGENT_LOCATION); + property = properties.get(PROP_AGENT_LOCATION); if (property != null) description.setAgentLocation(new Path(property)); - property = properties.getProperty(PROP_BUNDLE_LOCATION); + property = properties.get(PROP_BUNDLE_LOCATION); if (property != null) description.setBundleLocation(new Path(property)); - property = properties.getProperty(PROP_PROFILE_NAME); + property = properties.get(PROP_PROFILE_NAME); if (property != null) description.setProductName(property); // Process the retro root id and rootVersion properties - String id = properties.getProperty(PROP_ROOT_ID); + String id = properties.get(PROP_ROOT_ID); if (id != null) { - String version = properties.getProperty(PROP_ROOT_VERSION); + String version = properties.get(PROP_ROOT_VERSION); try { description.setRoots(new IVersionedId[] {new VersionedId(id, version)}); } catch (IllegalArgumentException e) { @@ -137,10 +136,10 @@ public class InstallDescriptionParser { } } - String rootSpec = properties.getProperty(PROP_ROOTS); + String rootSpec = properties.get(PROP_ROOTS); if (rootSpec != null) { String[] rootList = getArrayFromString(rootSpec, ","); //$NON-NLS-1$ - ArrayList roots = new ArrayList(rootList.length); + ArrayList roots = new ArrayList(rootList.length); for (int i = 0; i < rootList.length; i++) { try { roots.add(VersionedId.parse(rootList[i])); @@ -149,7 +148,7 @@ public class InstallDescriptionParser { } } if (!roots.isEmpty()) - description.setRoots((IVersionedId[]) roots.toArray(new IVersionedId[roots.size()])); + description.setRoots(roots.toArray(new IVersionedId[roots.size()])); } return description; } @@ -161,9 +160,9 @@ public class InstallDescriptionParser { * @param description * @param properties */ - private static void initializeProfileProperties(InstallDescription description, Properties properties) { + private static void initializeProfileProperties(InstallDescription description, Map properties) { //any remaining properties are profile properties - Map profileProperties = new HashMap(properties); + Map profileProperties = new HashMap(properties); profileProperties.remove(PROP_PROFILE_NAME); profileProperties.remove(PROP_ARTIFACT_REPOSITORY); profileProperties.remove(PROP_METADATA_REPOSITORY); @@ -185,7 +184,7 @@ public class InstallDescriptionParser { */ private static URI[] getURIs(String spec, URI base) { String[] urlSpecs = getArrayFromString(spec, ","); //$NON-NLS-1$ - ArrayList result = new ArrayList(urlSpecs.length); + ArrayList result = new ArrayList(urlSpecs.length); for (int i = 0; i < urlSpecs.length; i++) { try { URI uri = URIUtil.fromString(urlSpecs[i]); @@ -197,7 +196,7 @@ public class InstallDescriptionParser { } if (result.isEmpty()) return null; - return (URI[]) result.toArray(new URI[result.size()]); + return result.toArray(new URI[result.size()]); } private static void safeClose(InputStream in) { @@ -216,13 +215,13 @@ public class InstallDescriptionParser { public static String[] getArrayFromString(String list, String separator) { if (list == null || list.trim().equals("")) //$NON-NLS-1$ return new String[0]; - List result = new ArrayList(); + List result = new ArrayList(); for (StringTokenizer tokens = new StringTokenizer(list, separator); tokens.hasMoreTokens();) { String token = tokens.nextToken().trim(); if (!token.equals("")) //$NON-NLS-1$ result.add(token); } - return (String[]) result.toArray(new String[result.size()]); + return result.toArray(new String[result.size()]); } } diff --git a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallUpdateProductOperation.java b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallUpdateProductOperation.java index 3a0ee1d5c..7461f5bd2 100644 --- a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallUpdateProductOperation.java +++ b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallUpdateProductOperation.java @@ -11,23 +11,27 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.installer; -import org.eclipse.equinox.internal.provisional.p2.metadata.IVersionedId; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.net.URI; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.director.IDirector; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; import org.eclipse.equinox.internal.provisional.p2.installer.IInstallOperation; import org.eclipse.equinox.internal.provisional.p2.installer.InstallDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IVersionedId; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.service.environment.EnvironmentInfo; import org.eclipse.osgi.util.NLS; import org.osgi.framework.BundleContext; @@ -47,7 +51,7 @@ public class InstallUpdateProductOperation implements IInstallOperation { private IProfileRegistry profileRegistry; private IStatus result; - private ArrayList serviceReferences = new ArrayList(); + private ArrayList serviceReferences = new ArrayList(); public InstallUpdateProductOperation(BundleContext context, InstallDescription description) { this.bundleContext = context; @@ -58,22 +62,22 @@ public class InstallUpdateProductOperation implements IInstallOperation { * Determine what top level installable units should be installed by the director */ private IInstallableUnit[] computeUnitsToInstall() throws CoreException { - ArrayList result = new ArrayList(); + ArrayList units = new ArrayList(); IVersionedId roots[] = installDescription.getRoots(); for (int i = 0; i < roots.length; i++) { IVersionedId root = roots[i]; IInstallableUnit iu = findUnit(root); if (iu != null) - result.add(iu); + units.add(iu); } - return (IInstallableUnit[]) result.toArray(new IInstallableUnit[result.size()]); + return units.toArray(new IInstallableUnit[units.size()]); } /** * This profile is being updated; return the units to uninstall from the profile. */ - private IInstallableUnit[] computeUnitsToUninstall(IProfile p) { - return (IInstallableUnit[]) p.query(InstallableUnitQuery.ANY, new Collector(), null).toArray(IInstallableUnit.class); + private IQueryResult computeUnitsToUninstall(IProfile p) { + return p.query(InstallableUnitQuery.ANY, null); } /** @@ -82,7 +86,7 @@ public class InstallUpdateProductOperation implements IInstallOperation { private IProfile createProfile() throws ProvisionException { IProfile profile = getProfile(); if (profile == null) { - Map properties = new HashMap(); + Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, installDescription.getInstallLocation().toString()); EnvironmentInfo info = (EnvironmentInfo) ServiceHelper.getService(InstallerActivator.getDefault().getContext(), EnvironmentInfo.class.getName()); String env = "osgi.os=" + info.getOS() + ",osgi.ws=" + info.getWS() + ",osgi.arch=" + info.getOSArch(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ @@ -115,7 +119,7 @@ public class InstallUpdateProductOperation implements IInstallOperation { s = director.provision(request, null, monitor.newChild(90)); } else { monitor.setTaskName(NLS.bind(Messages.Op_Updating, installDescription.getProductName())); - IInstallableUnit[] toUninstall = computeUnitsToUninstall(p); + IQueryResult toUninstall = computeUnitsToUninstall(p); request.removeInstallableUnits(toUninstall); request.addInstallableUnits(toInstall); s = director.provision(request, null, monitor.newChild(90)); @@ -150,13 +154,12 @@ public class InstallUpdateProductOperation implements IInstallOperation { VersionRange range = VersionRange.emptyRange; if (version != null && !version.equals(Version.emptyVersion)) range = new VersionRange(version, true, version, true); - Query query = new InstallableUnitQuery(id, range); - Collector collector = new Collector(); - Iterator matches = metadataRepoMan.query(query, collector, null).iterator(); + IQuery query = new InstallableUnitQuery(id, range); + Iterator matches = metadataRepoMan.query(query, null).iterator(); // pick the newest match IInstallableUnit newest = null; while (matches.hasNext()) { - IInstallableUnit candidate = (IInstallableUnit) matches.next(); + IInstallableUnit candidate = matches.next(); if (newest == null || (newest.getVersion().compareTo(candidate.getVersion()) < 0)) newest = candidate; } @@ -233,20 +236,18 @@ public class InstallUpdateProductOperation implements IInstallOperation { } private void postInstall() { - for (Iterator it = serviceReferences.iterator(); it.hasNext();) { - ServiceReference sr = (ServiceReference) it.next(); + for (ServiceReference sr : serviceReferences) bundleContext.ungetService(sr); - } serviceReferences.clear(); } private void preInstall() throws CoreException { //obtain required services serviceReferences.clear(); - director = (IDirector) getService(IDirector.class.getName()); - metadataRepoMan = (IMetadataRepositoryManager) getService(IMetadataRepositoryManager.class.getName()); - artifactRepoMan = (IArtifactRepositoryManager) getService(IArtifactRepositoryManager.class.getName()); - profileRegistry = (IProfileRegistry) getService(IProfileRegistry.class.getName()); + director = (IDirector) getService(IDirector.SERVICE_NAME); + metadataRepoMan = (IMetadataRepositoryManager) getService(IMetadataRepositoryManager.SERVICE_NAME); + artifactRepoMan = (IArtifactRepositoryManager) getService(IArtifactRepositoryManager.SERVICE_NAME); + profileRegistry = (IProfileRegistry) getService(IProfileRegistry.SERVICE_NAME); } private void prepareArtifactRepositories() throws ProvisionException { diff --git a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/Messages.java b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/Messages.java index 803a99c19..f0599e10d 100644 --- a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/Messages.java +++ b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/Messages.java @@ -61,7 +61,6 @@ public class Messages extends NLS { public static String ProxiesDialog_EmptyProtMessage; public static String ProxiesDialog_EmptyUserMessage; public static String ProxiesDialog_FailedToReadProxySettingsMessage; - public static String ProxiesDialog_FailedTorSetProxySettings; public static String ProxiesDialog_FailedToSetProxyMessage; public static String ProxiesDialog_HostLabel; public static String ProxiesDialog_InvalitHostMessage; diff --git a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/messages.properties b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/messages.properties index 67dc69364..9df951909 100644 --- a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/messages.properties +++ b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/messages.properties @@ -52,8 +52,7 @@ ProxiesDialog_EmptyPasswordMessage=Empty password ProxiesDialog_EmptyProtMessage=Empty port ProxiesDialog_EmptyUserMessage=Empty user ProxiesDialog_FailedToReadProxySettingsMessage=Failed to read proxy settings -ProxiesDialog_FailedTorSetProxySettings=Failed to set proxy settings. -ProxiesDialog_FailedToSetProxyMessage=Failed to set proxy +ProxiesDialog_FailedToSetProxyMessage=Failed to set proxy settings. ProxiesDialog_HostLabel=Host: ProxiesDialog_InvalitHostMessage=Invalid host ProxiesDialog_NegativValue=Proxy value can not be negativ diff --git a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/ui/InstallDialog.java b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/ui/InstallDialog.java index e744396cc..d78406a22 100644 --- a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/ui/InstallDialog.java +++ b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/ui/InstallDialog.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.installer.ui; -import org.eclipse.equinox.internal.p2.installer.Messages; - import org.eclipse.core.net.proxy.IProxyService; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.installer.*; diff --git a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/ui/ProxiesDialog.java b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/ui/ProxiesDialog.java index eaa0be727..91dc773c4 100644 --- a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/ui/ProxiesDialog.java +++ b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/ui/ProxiesDialog.java @@ -46,7 +46,7 @@ public final class ProxiesDialog { private Button cancelButton; private final IProxyService service; private Shell shell; - private List types; + private List types; private Label statuslabel; public ProxiesDialog(IProxyService service) { @@ -103,7 +103,7 @@ public final class ProxiesDialog { typeCombo.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 3, 1)); //Currently only these three proxy types are supported. for (int i = 0; i < types.size(); i++) { - typeCombo.add((String) types.get(i)); + typeCombo.add(types.get(i)); } typeCombo.addSelectionListener(new SelectionAdapter() { @@ -244,7 +244,7 @@ public final class ProxiesDialog { openMessage(Messages.ProxiesDialog_ServiceNotAvailableMessage, SWT.ICON_ERROR | SWT.OK); } } catch (Exception e) { - openMessage(Messages.ProxiesDialog_FailedTorSetProxySettings + e.getLocalizedMessage(), SWT.ICON_ERROR | SWT.OK); + openMessage(Messages.ProxiesDialog_FailedToSetProxyMessage + e.getLocalizedMessage(), SWT.ICON_ERROR | SWT.OK); } } @@ -304,7 +304,7 @@ public final class ProxiesDialog { } private void initTypes() { - types = new ArrayList(); + types = new ArrayList(); types.add(IProxyData.HTTP_PROXY_TYPE); types.add(IProxyData.HTTPS_PROXY_TYPE); types.add(IProxyData.SOCKS_PROXY_TYPE); diff --git a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/provisional/p2/installer/InstallDescription.java b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/provisional/p2/installer/InstallDescription.java index dc925e959..b8adcccc7 100644 --- a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/provisional/p2/installer/InstallDescription.java +++ b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/provisional/p2/installer/InstallDescription.java @@ -11,12 +11,11 @@ *******************************************************************************/ package org.eclipse.equinox.internal.provisional.p2.installer; -import org.eclipse.equinox.internal.provisional.p2.metadata.IVersionedId; - import java.net.URI; import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.IPath; +import org.eclipse.equinox.p2.metadata.IVersionedId; /** * An install information captures all the data needed to perform a product install. @@ -33,7 +32,7 @@ public class InstallDescription { private URI[] metadataRepos; private String productName; private IVersionedId[] roots; - private final Map profileProperties = new HashMap(); + private final Map profileProperties = new HashMap(); /** * Returns the p2 agent location, or null to indicate @@ -86,7 +85,7 @@ public class InstallDescription { /** * Returns the profile properties for this install. */ - public Map getProfileProperties() { + public Map getProfileProperties() { return profileProperties; } @@ -140,7 +139,7 @@ public class InstallDescription { * Supplies a set of profile properties to be added when the profile is created. * @param properties the profile properties to be added */ - public void setProfileProperties(Map properties) { + public void setProfileProperties(Map properties) { profileProperties.putAll(properties); } diff --git a/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/PackStep.java b/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/PackStep.java index 9258caf7b..3d519736d 100644 --- a/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/PackStep.java +++ b/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/PackStep.java @@ -12,11 +12,7 @@ package org.eclipse.equinox.internal.p2.jarprocessor; import java.io.File; import java.io.IOException; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.Set; +import java.util.*; public class PackStep extends CommandStep { diff --git a/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/Utils.java b/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/Utils.java index 9cf22bce9..d6bbc6a36 100644 --- a/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/Utils.java +++ b/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/Utils.java @@ -15,7 +15,6 @@ import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipException; - import org.eclipse.internal.provisional.equinox.p2.jarprocessor.JarProcessor; /** diff --git a/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/verifier/Verifier.java b/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/verifier/Verifier.java index 8aea9d172..322d77905 100644 --- a/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/verifier/Verifier.java +++ b/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/verifier/Verifier.java @@ -96,6 +96,7 @@ public class Verifier extends JarProcessorExecutor { return super.processJar(inputFile); } }; + verifier.setWorkingDirectory(workingDirectory.getAbsolutePath()); for (int i = 0; i < input.length; i++) { File inputFile = new File(input[i]); diff --git a/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/verifier/VerifyStep.java b/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/verifier/VerifyStep.java index 7e63698b8..f9b19351e 100644 --- a/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/verifier/VerifyStep.java +++ b/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/equinox/internal/p2/jarprocessor/verifier/VerifyStep.java @@ -13,7 +13,6 @@ import java.io.File; import java.io.IOException; import java.util.List; import java.util.Properties; - import org.eclipse.equinox.internal.p2.jarprocessor.CommandStep; import org.eclipse.equinox.internal.p2.jarprocessor.Utils; diff --git a/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/internal/provisional/equinox/p2/jarprocessor/JarProcessor.java b/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/internal/provisional/equinox/p2/jarprocessor/JarProcessor.java index 15811e275..b22bc8e9b 100644 --- a/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/internal/provisional/equinox/p2/jarprocessor/JarProcessor.java +++ b/bundles/org.eclipse.equinox.p2.jarprocessor/src/org/eclipse/internal/provisional/equinox/p2/jarprocessor/JarProcessor.java @@ -214,16 +214,17 @@ public class JarProcessor { extracted.setLastModified(entry.getTime()); //recurse - containingInfs.addFirst(inf); String dir = getWorkingDirectory(); - setWorkingDirectory(parentDir.getCanonicalPath()); - File result = processJar(extracted); - - newName = name.substring(0, name.length() - extracted.getName().length()) + result.getName(); - data.put(name, newName); - - setWorkingDirectory(dir); - containingInfs.removeFirst(); + try { + containingInfs.addFirst(inf); + setWorkingDirectory(parentDir.getCanonicalPath()); + File result = processJar(extracted); + newName = name.substring(0, name.length() - extracted.getName().length()) + result.getName(); + data.put(name, newName); + } finally { + setWorkingDirectory(dir); + containingInfs.removeFirst(); + } //delete the extracted item leaving the recursion result if (!name.equals(newName)) @@ -263,92 +264,93 @@ public class JarProcessor { } public File processJar(File input) throws IOException { + File tempDir = null; ++depth; - long lastModified = input.lastModified(); - File workingDir = new File(getWorkingDirectory()); - if (!workingDir.exists()) - workingDir.mkdirs(); - - boolean skip = Utils.shouldSkipJar(input, processAll, verbose); - if (depth == 0 && verbose) { - if (skip) - System.out.println("Skipping " + input.getPath()); //$NON-NLS-1$ - else { - System.out.print("Running "); //$NON-NLS-1$ - for (Iterator iter = steps.iterator(); iter.hasNext();) { - IProcessStep step = (IProcessStep) iter.next(); - System.out.print(step.getStepName() + " "); //$NON-NLS-1$ + try { + long lastModified = input.lastModified(); + File workingDir = new File(getWorkingDirectory()); + if (!workingDir.exists()) + workingDir.mkdirs(); + + boolean skip = Utils.shouldSkipJar(input, processAll, verbose); + if (depth == 0 && verbose) { + if (skip) + System.out.println("Skipping " + input.getPath()); //$NON-NLS-1$ + else { + System.out.print("Running "); //$NON-NLS-1$ + for (Iterator iter = steps.iterator(); iter.hasNext();) { + IProcessStep step = (IProcessStep) iter.next(); + System.out.print(step.getStepName() + " "); //$NON-NLS-1$ + } + System.out.println("on " + input.getPath()); //$NON-NLS-1$ } - System.out.println("on " + input.getPath()); //$NON-NLS-1$ } - } - if (skip) { - //This jar was not marked as conditioned, and we are only processing conditioned jars, so do nothing - --depth; - return input; - } - - //pre - File workingFile = preProcess(input, workingDir); + if (skip) { + //This jar was not marked as conditioned, and we are only processing conditioned jars, so do nothing + return input; + } - //Extract entries from jar and recurse on them - File tempDir = null; - if (depth == 0) { - tempDir = new File(workingDir, "temp." + workingFile.getName()); //$NON-NLS-1$ - } else { - File parent = workingDir.getParentFile(); - tempDir = new File(parent, "temp_" + depth + '_' + workingFile.getName()); //$NON-NLS-1$ - } + //pre + File workingFile = preProcess(input, workingDir); - JarFile jar = new JarFile(workingFile, false); - Map replacements = new HashMap(); - Properties inf = Utils.getEclipseInf(workingFile, verbose); - extractEntries(jar, tempDir, replacements, inf); - - if (inf != null) - adjustInf(workingFile, inf); - - //Recreate the jar with replacements. - //TODO: This is not strictly necessary if we didn't change the inf file and didn't change any content - File tempJar = null; - tempJar = new File(tempDir, workingFile.getName()); - File parent = tempJar.getParentFile(); - if (!parent.exists()) - parent.mkdirs(); - JarOutputStream jarOut = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(tempJar))); - recreateJar(jar, jarOut, replacements, tempDir, inf); - - jar.close(); - if (tempJar != null) { - if (!workingFile.equals(input)) { - workingFile.delete(); + //Extract entries from jar and recurse on them + if (depth == 0) { + tempDir = new File(workingDir, "temp." + workingFile.getName()); //$NON-NLS-1$ + } else { + File parent = workingDir.getParentFile(); + tempDir = new File(parent, "temp_" + depth + '_' + workingFile.getName()); //$NON-NLS-1$ } - workingFile = tempJar; - } - //post - File result = postProcess(workingFile, workingDir); + JarFile jar = new JarFile(workingFile, false); + Map replacements = new HashMap(); + Properties inf = Utils.getEclipseInf(workingFile, verbose); + extractEntries(jar, tempDir, replacements, inf); + + if (inf != null) + adjustInf(workingFile, inf); + + //Recreate the jar with replacements. + //TODO: This is not strictly necessary if we didn't change the inf file and didn't change any content + File tempJar = null; + tempJar = new File(tempDir, workingFile.getName()); + File parent = tempJar.getParentFile(); + if (!parent.exists()) + parent.mkdirs(); + JarOutputStream jarOut = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(tempJar))); + recreateJar(jar, jarOut, replacements, tempDir, inf); - //have to normalize after the post steps - normalize(result, workingDir); + jar.close(); + if (tempJar != null) { + if (!workingFile.equals(input)) { + workingFile.delete(); + } + workingFile = tempJar; + } - if (!result.equals(workingFile) && !workingFile.equals(input)) - workingFile.delete(); - if (!result.getParentFile().equals(workingDir)) { - File finalFile = new File(workingDir, result.getName()); - if (finalFile.exists()) - finalFile.delete(); - result.renameTo(finalFile); - result = finalFile; - } + //post + File result = postProcess(workingFile, workingDir); - if (tempDir.exists()) - Utils.clear(tempDir); + //have to normalize after the post steps + normalize(result, workingDir); - result.setLastModified(lastModified); - --depth; - return result; + if (!result.equals(workingFile) && !workingFile.equals(input)) + workingFile.delete(); + if (!result.getParentFile().equals(workingDir)) { + File finalFile = new File(workingDir, result.getName()); + if (finalFile.exists()) + finalFile.delete(); + result.renameTo(finalFile); + result = finalFile; + } + + result.setLastModified(lastModified); + return result; + } finally { + --depth; + if (tempDir != null && tempDir.exists()) + Utils.clear(tempDir); + } } private void normalize(File input, File directory) { diff --git a/bundles/org.eclipse.equinox.p2.jarprocessor/src_ant/org/eclipse/equinox/internal/p2/jarprocessor/ant/JarProcessorTask.java b/bundles/org.eclipse.equinox.p2.jarprocessor/src_ant/org/eclipse/equinox/internal/p2/jarprocessor/ant/JarProcessorTask.java index 8f6993f00..c8cfbfad1 100644 --- a/bundles/org.eclipse.equinox.p2.jarprocessor/src_ant/org/eclipse/equinox/internal/p2/jarprocessor/ant/JarProcessorTask.java +++ b/bundles/org.eclipse.equinox.p2.jarprocessor/src_ant/org/eclipse/equinox/internal/p2/jarprocessor/ant/JarProcessorTask.java @@ -13,10 +13,7 @@ package org.eclipse.equinox.internal.p2.jarprocessor.ant; import java.io.File; import java.util.ArrayList; import java.util.Properties; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.DirectoryScanner; -import org.apache.tools.ant.Task; +import org.apache.tools.ant.*; import org.apache.tools.ant.types.FileSet; import org.eclipse.internal.provisional.equinox.p2.jarprocessor.JarProcessorExecutor.Options; diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.metadata.generator/META-INF/MANIFEST.MF index 7af44e405..264ed2f50 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.metadata.generator/META-INF/MANIFEST.MF @@ -12,18 +12,22 @@ Import-Package: javax.xml.parsers, org.eclipse.equinox.app;version="1.0.0", org.eclipse.equinox.internal.frameworkadmin.equinox, org.eclipse.equinox.internal.frameworkadmin.utils, - org.eclipse.equinox.internal.p2.artifact.repository, org.eclipse.equinox.internal.p2.metadata, + org.eclipse.equinox.internal.p2.metadata.query, org.eclipse.equinox.internal.p2.metadata.repository, org.eclipse.equinox.internal.p2.repository.helpers, org.eclipse.equinox.internal.provisional.frameworkadmin, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.p2.repository, org.eclipse.equinox.internal.provisional.simpleconfigurator.manipulator, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.expression, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.artifact.spi, + org.eclipse.equinox.p2.repository.metadata, org.w3c.dom, org.xml.sax, org.xml.sax.helpers diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java index 1f46d991d..3ba8394b6 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java +++ b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java @@ -19,21 +19,17 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.URIUtil; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; -import org.eclipse.equinox.internal.p2.artifact.repository.ArtifactRepositoryManager; -import org.eclipse.equinox.internal.p2.core.ProvisioningEventBus; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; import org.eclipse.equinox.internal.provisional.p2.metadata.generator.EclipseInstallGeneratorInfoProvider; import org.eclipse.equinox.internal.provisional.p2.metadata.generator.Generator; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.util.NLS; -import org.osgi.framework.ServiceRegistration; +import org.osgi.framework.ServiceReference; public class EclipseGeneratorApplication implements IApplication { @@ -48,12 +44,6 @@ public class EclipseGeneratorApplication implements IApplication { static final public String PUBLISH_PACK_FILES_AS_SIBLINGS = "publishPackFilesAsSiblings"; //$NON-NLS-1$ - private ArtifactRepositoryManager defaultArtifactManager; - private ServiceRegistration registrationDefaultArtifactManager; - private MetadataRepositoryManager defaultMetadataManager; - private ServiceRegistration registrationDefaultMetadataManager; - private IProvisioningEventBus bus; - private ServiceRegistration registrationBus; private Generator.GeneratorResult incrementalResult = null; private boolean generateRootIU = true; private URI metadataLocation; @@ -68,6 +58,9 @@ public class EclipseGeneratorApplication implements IApplication { //whether repository xml files should be compressed private String compress = "false"; //$NON-NLS-1$ + private ServiceReference agentRef; + private IProvisioningAgent agent; + private File getExecutableName(String base, EclipseInstallGeneratorInfoProvider provider) { File location = provider.getExecutableLocation(); if (location == null) @@ -105,7 +98,7 @@ public class EclipseGeneratorApplication implements IApplication { private void initializeArtifactRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException { if (artifactLocation == null) return; - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.context, IArtifactRepositoryManager.class.getName()); + IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.context, IArtifactRepositoryManager.SERVICE_NAME); URI location = artifactLocation; String repositoryName = (artifactRepoName != null && artifactRepoName.length() > 0) ? artifactRepoName : artifactLocation + " - artifacts"; //$NON-NLS-1$ @@ -169,7 +162,7 @@ public class EclipseGeneratorApplication implements IApplication { Map properties = new HashMap(1); properties.put(IRepository.PROP_COMPRESSED, compress); - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.context, IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.context, IMetadataRepositoryManager.SERVICE_NAME); try { IMetadataRepository result = manager.createRepository(location, repositoryName, IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); manager.removeRepository(location); @@ -304,29 +297,6 @@ public class EclipseGeneratorApplication implements IApplication { } } - private void registerDefaultArtifactRepoManager() { - if (ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()) == null) { - defaultArtifactManager = new ArtifactRepositoryManager(); - defaultArtifactManager.setEventBus(bus); - registrationDefaultArtifactManager = Activator.getContext().registerService(IArtifactRepositoryManager.class.getName(), defaultArtifactManager, null); - } - } - - private void registerDefaultMetadataRepoManager() { - if (ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()) == null) { - defaultMetadataManager = new MetadataRepositoryManager(); - defaultMetadataManager.setEventBus(bus); - registrationDefaultMetadataManager = Activator.getContext().registerService(IMetadataRepositoryManager.class.getName(), defaultMetadataManager, null); - } - } - - private void registerEventBus() { - if (ServiceHelper.getService(Activator.getContext(), IProvisioningEventBus.SERVICE_NAME) == null) { - bus = new ProvisioningEventBus(); - registrationBus = Activator.getContext().registerService(IProvisioningEventBus.SERVICE_NAME, bus, null); - } - } - public Object run(String args[]) throws Exception { EclipseInstallGeneratorInfoProvider provider = new EclipseInstallGeneratorInfoProvider(); processCommandLineArguments(args, provider); @@ -338,9 +308,7 @@ public class EclipseGeneratorApplication implements IApplication { } public Object run(EclipseInstallGeneratorInfoProvider provider) throws Exception { - registerEventBus(); - registerDefaultMetadataRepoManager(); - registerDefaultArtifactRepoManager(); + initializeAgent(); initialize(provider); if (provider.getBaseLocation() == null && provider.getProductFile() == null && !generateRootIU) { @@ -373,6 +341,24 @@ public class EclipseGeneratorApplication implements IApplication { return new Integer(1); } + private void initializeAgent() throws ProvisionException { + agentRef = Activator.getContext().getServiceReference(IProvisioningAgent.SERVICE_NAME); + if (agentRef != null) { + agent = (IProvisioningAgent) Activator.getContext().getService(agentRef); + if (agent != null) + return; + } + ServiceReference providerRef = Activator.getContext().getServiceReference(IProvisioningAgentProvider.SERVICE_NAME); + if (providerRef == null) + throw new RuntimeException("No provisioning agent provider is available"); //$NON-NLS-1$ + IProvisioningAgentProvider provider = (IProvisioningAgentProvider) Activator.getContext().getService(providerRef); + if (provider == null) + throw new RuntimeException("No provisioning agent provider is available"); //$NON-NLS-1$ + //obtain agent for currently running system + agent = provider.createAgent(null); + Activator.getContext().ungetService(providerRef); + } + protected IStatus generate(EclipseInstallGeneratorInfoProvider provider) { Generator generator = new Generator(provider); if (incrementalResult != null) @@ -388,17 +374,9 @@ public class EclipseGeneratorApplication implements IApplication { } public void stop() { - if (registrationDefaultMetadataManager != null) { - registrationDefaultMetadataManager.unregister(); - registrationDefaultMetadataManager = null; - } - if (registrationDefaultArtifactManager != null) { - registrationDefaultArtifactManager.unregister(); - registrationDefaultArtifactManager = null; - } - if (registrationBus != null) { - registrationBus.unregister(); - registrationBus = null; + if (agentRef != null) { + Activator.getContext().ungetService(agentRef); + agentRef = null; } } diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/ProductQuery.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/ProductQuery.java index 1c5dc4bea..2282c393c 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/ProductQuery.java +++ b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/ProductQuery.java @@ -10,17 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.generator; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.io.*; import java.util.*; import org.eclipse.equinox.internal.p2.metadata.generator.features.ProductFile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.internal.provisional.p2.metadata.generator.MetadataGeneratorHelper; import org.eclipse.equinox.internal.provisional.p2.metadata.generator.Generator.GeneratorResult; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.MatchQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.MatchQuery; public class ProductQuery extends MatchQuery { private static final String EQUINOX_LAUNCHER = "org.eclipse.equinox.launcher"; //$NON-NLS-1$ @@ -30,25 +29,6 @@ public class ProductQuery extends MatchQuery { private final Map children = new HashMap(); private final String versionAdvice; - // Collector collects the largest version of each IU - private final Collector collector = new Collector() { - private final HashMap elements = new HashMap(); - - public boolean accept(Object object) { - if (!(object instanceof IInstallableUnit)) - return true; - IInstallableUnit iu = (IInstallableUnit) object; - if (elements.containsKey(iu.getId())) { - IInstallableUnit existing = (IInstallableUnit) elements.get(iu.getId()); - if (existing.getVersion().compareTo(iu.getVersion()) >= 0) - return true; - getCollection().remove(existing); - } - elements.put(iu.getId(), iu); - return super.accept(object); - } - }; - public ProductQuery(ProductFile product, String flavor, Map configIUs, String versionAdvice) { this.product = product; this.flavor = flavor; @@ -56,10 +36,6 @@ public class ProductQuery extends MatchQuery { initialize(configIUs); } - public Collector getCollector() { - return this.collector; - } - private Properties loadVersions(String location) { Properties properties = new Properties(); if (location == null) @@ -94,7 +70,7 @@ public class ProductQuery extends MatchQuery { VersionRange range = VersionRange.emptyRange; if (versions.containsKey(item)) { - Version value = new Version(versions.getProperty(item)); + Version value = Version.create(versions.getProperty(item)); range = new VersionRange(value, true, value, true); } diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/EclipseInstallGeneratorInfoProvider.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/EclipseInstallGeneratorInfoProvider.java index 70c4a2fe0..cd8978009 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/EclipseInstallGeneratorInfoProvider.java +++ b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/EclipseInstallGeneratorInfoProvider.java @@ -20,14 +20,13 @@ import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.metadata.generator.Activator; import org.eclipse.equinox.internal.p2.metadata.generator.Messages; import org.eclipse.equinox.internal.provisional.frameworkadmin.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; import org.eclipse.equinox.internal.provisional.simpleconfigurator.manipulator.SimpleConfiguratorManipulator; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.osgi.service.environment.EnvironmentInfo; import org.eclipse.osgi.util.NLS; import org.osgi.framework.*; -import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.util.tracker.ServiceTracker; /** @@ -45,8 +44,6 @@ public class EclipseInstallGeneratorInfoProvider implements IGeneratorInfo { private final static String frameworkAdminFillter = "(&" + FILTER_OBJECTCLASS + filterFwName + filterLauncherName + ")"; //$NON-NLS-1$ //$NON-NLS-2$ private static final String ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR = "org.eclipse.equinox.simpleconfigurator"; //$NON-NLS-1$ private static final String ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR_CONFIGURL = "org.eclipse.equinox.simpleconfigurator.configUrl"; //$NON-NLS-1$ - private static final String ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR_MANIPULATOR = "org.eclipse.equinox.simpleconfigurator.manipulator"; //$NON-NLS-1$ - private static final String ORG_ECLIPSE_EQUINOX_FRAMEWORKADMIN_EQUINOX = "org.eclipse.equinox.frameworkadmin.equinox"; //$NON-NLS-1$ private static final String ORG_ECLIPSE_EQUINOX_P2_RECONCILER_DROPINS = "org.eclipse.equinox.p2.reconciler.dropins"; //$NON-NLS-1$ private String os; @@ -353,19 +350,8 @@ public class EclipseInstallGeneratorInfoProvider implements IGeneratorInfo { e.printStackTrace(); } } - // try { - // frameworkAdminTracker.waitForService(500); - // } catch (InterruptedException e) { - // // ignore - // } - - FrameworkAdmin admin = (FrameworkAdmin) frameworkAdminTracker.getService(); - if (admin == null) { - startBundle(ORG_ECLIPSE_EQUINOX_FRAMEWORKADMIN_EQUINOX); - startBundle(ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR_MANIPULATOR); - admin = (FrameworkAdmin) frameworkAdminTracker.getService(); - } - return admin; + + return (FrameworkAdmin) frameworkAdminTracker.getService(); } private Collection getIUs(Set ius, String prefix) { @@ -542,27 +528,6 @@ public class EclipseInstallGeneratorInfoProvider implements IGeneratorInfo { this.siteLocation = location; } - private boolean startBundle(String bundleId) { - PackageAdmin packageAdmin = (PackageAdmin) ServiceHelper.getService(Activator.getContext(), PackageAdmin.class.getName()); - if (packageAdmin == null) - return false; - - Bundle[] bundles = packageAdmin.getBundles(bundleId, null); - if (bundles != null && bundles.length > 0) { - for (int i = 0; i < bundles.length; i++) { - try { - if ((bundles[0].getState() & Bundle.RESOLVED) > 0) { - bundles[0].start(); - return true; - } - } catch (BundleException e) { - // failed, try next bundle - } - } - } - return false; - } - public String getVersionAdvice() { return versionAdvice; } diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/FeatureEntry.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/FeatureEntry.java index 13b5ca075..870a3b6f2 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/FeatureEntry.java +++ b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/FeatureEntry.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.equinox.internal.provisional.p2.metadata.generator; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; /** */ diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/Generator.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/Generator.java index 11b998fb9..81cfd9e37 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/Generator.java +++ b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/Generator.java @@ -10,9 +10,6 @@ *******************************************************************************/ package org.eclipse.equinox.internal.provisional.p2.metadata.generator; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.io.*; import java.net.URI; import java.net.URISyntaxException; @@ -26,18 +23,25 @@ import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; import org.eclipse.equinox.internal.p2.metadata.generator.*; import org.eclipse.equinox.internal.p2.metadata.generator.Messages; import org.eclipse.equinox.internal.p2.metadata.generator.features.*; +import org.eclipse.equinox.internal.p2.metadata.query.LatestIUVersionQuery; import org.eclipse.equinox.internal.provisional.frameworkadmin.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitFragmentDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.osgi.service.environment.Constants; import org.eclipse.osgi.service.resolver.*; import org.eclipse.osgi.util.NLS; +import org.osgi.framework.Filter; public class Generator { /** @@ -184,14 +188,15 @@ public class Generator { GeneratorResult productContents = new GeneratorResult(); - ProductQuery query = new ProductQuery(productFile, info.getFlavor(), result.configurationIUs, info.getVersionAdvice()); - Collector collector = info.getMetadataRepository().query(query, query.getCollector(), null); - for (Iterator iterator = collector.iterator(); iterator.hasNext();) { + ProductQuery productQuery = new ProductQuery(productFile, info.getFlavor(), result.configurationIUs, info.getVersionAdvice()); + PipedQuery query = new PipedQuery(new IQuery[] {productQuery, new LatestIUVersionQuery()}); + IQueryResult queryResult = info.getMetadataRepository().query(query, null); + for (Iterator iterator = queryResult.iterator(); iterator.hasNext();) { productContents.rootIUs.add(iterator.next()); } String version = getProductVersion(); - VersionRange range = new VersionRange(new Version(version), true, new Version(version), true); + VersionRange range = new VersionRange(Version.create(version), true, Version.create(version), true); ArrayList requires = new ArrayList(1); requires.add(MetadataFactory.createRequiredCapability(info.getFlavor() + productFile.getId(), productFile.getId() + PRODUCT_LAUCHER_SUFFIX, range, null, false, true)); requires.add(MetadataFactory.createRequiredCapability(info.getFlavor() + productFile.getId(), productFile.getId() + PRODUCT_INI_SUFFIX, range, null, false, false)); @@ -223,7 +228,7 @@ public class Generator { InstallableUnitDescription root = new MetadataFactory.InstallableUnitDescription(); root.setSingleton(true); root.setId(configurationIdentification); - root.setVersion(new Version(configurationVersion)); + root.setVersion(Version.create(configurationVersion)); root.setProperty(IInstallableUnit.PROP_NAME, configurationName); ArrayList reqsConfigurationUnits = new ArrayList(result.rootIUs.size()); @@ -235,13 +240,13 @@ public class Generator { } if (requires != null) reqsConfigurationUnits.addAll(requires); - root.setRequiredCapabilities((IRequiredCapability[]) reqsConfigurationUnits.toArray(new IRequiredCapability[reqsConfigurationUnits.size()])); + root.setRequiredCapabilities((IRequirement[]) reqsConfigurationUnits.toArray(new IRequirement[reqsConfigurationUnits.size()])); root.setArtifacts(new IArtifactKey[0]); root.setProperty("lineUp", "true"); //$NON-NLS-1$ //$NON-NLS-2$ root.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor(configurationIdentification, VersionRange.emptyRange, IUpdateDescriptor.NORMAL, null)); - root.setProperty(IInstallableUnit.PROP_TYPE_GROUP, Boolean.TRUE.toString()); - root.setCapabilities(new IProvidedCapability[] {MetadataGeneratorHelper.createSelfCapability(configurationIdentification, new Version(configurationVersion))}); + root.setProperty(InstallableUnitDescription.PROP_TYPE_GROUP, Boolean.TRUE.toString()); + root.setCapabilities(new IProvidedCapability[] {MetadataGeneratorHelper.createSelfCapability(configurationIdentification, Version.create(configurationVersion))}); root.setTouchpointType(MetadataGeneratorHelper.TOUCHPOINT_OSGI); Map touchpointData = new HashMap(); @@ -400,7 +405,7 @@ public class Generator { format = (String) bundleManifest.get(BundleDescriptionFactory.BUNDLE_FILE_KEY); boolean isDir = (format != null && format.equals(BundleDescriptionFactory.DIR) ? true : false); - IArtifactKey key = new ArtifactKey(MetadataGeneratorHelper.OSGI_BUNDLE_CLASSIFIER, bd.getSymbolicName(), new Version(bd.getVersion().toString())); + IArtifactKey key = new ArtifactKey(MetadataGeneratorHelper.OSGI_BUNDLE_CLASSIFIER, bd.getSymbolicName(), Version.create(bd.getVersion().toString())); IArtifactDescriptor ad = MetadataGeneratorHelper.createArtifactDescriptor(key, new File(bd.getLocation()), true, false); ((ArtifactDescriptor) ad).setProperty(IArtifactDescriptor.DOWNLOAD_CONTENTTYPE, IArtifactDescriptor.TYPE_ZIP); File bundleFile = new File(bd.getLocation()); @@ -511,7 +516,7 @@ public class Generator { while (i > -1) { Version version = null; try { - version = new Version(name.substring(i)); + version = Version.create(name.substring(i)); bundleInfo.setSymbolicName(name.substring(0, i)); bundleInfo.setVersion(version.toString()); return new GeneratorBundleInfo(bundleInfo); @@ -522,9 +527,8 @@ public class Generator { } //Query the repo - Query query = new InstallableUnitQuery(name); - Collector collector = new Collector(); - Iterator matches = info.getMetadataRepository().query(query, collector, null).iterator(); + IQuery query = new InstallableUnitQuery(name); + Iterator matches = info.getMetadataRepository().query(query, null).iterator(); //pick the newest match IInstallableUnit newest = null; while (matches.hasNext()) { @@ -580,7 +584,7 @@ public class Generator { continue; } - IInstallableUnit cu = MetadataGeneratorHelper.createBundleConfigurationUnit(bundle.getSymbolicName(), new Version(bundle.getVersion()), false, bundle, info.getFlavor() + cuIdPrefix, filter); + IInstallableUnit cu = MetadataGeneratorHelper.createBundleConfigurationUnit(bundle.getSymbolicName(), Version.create(bundle.getVersion()), false, bundle, info.getFlavor() + cuIdPrefix, filter); if (cu != null) { allCUs.add(cu); result.rootIUs.add(cu); @@ -637,12 +641,11 @@ public class Generator { if (configuredIU == null) { if (!generateRootIU && data == null) continue; - Query query = new InstallableUnitQuery(bundle.getSymbolicName()); - Collector collector = new Collector(); + IQuery query = new InstallableUnitQuery(bundle.getSymbolicName()); IMetadataRepository metadataRepository = info.getMetadataRepository(); if (metadataRepository == null) continue; - Iterator matches = metadataRepository.query(query, collector, null).iterator(); + Iterator matches = metadataRepository.query(query, null).iterator(); //pick the newest match IInstallableUnit newest = null; while (matches.hasNext()) { @@ -657,8 +660,8 @@ public class Generator { } } bundle.setVersion(configuredIU.getVersion().toString()); - String filter = configuredIU == null ? null : configuredIU.getFilter(); - IInstallableUnit cu = MetadataGeneratorHelper.createBundleConfigurationUnit(bundle.getSymbolicName(), new Version(bundle.getVersion()), false, bundle, info.getFlavor(), filter); + Filter filter = configuredIU == null ? null : configuredIU.getFilter(); + IInstallableUnit cu = MetadataGeneratorHelper.createBundleConfigurationUnit(bundle.getSymbolicName(), Version.create(bundle.getVersion()), false, bundle, info.getFlavor(), filter == null ? null : filter.toString()); //the configuration unit should share the same platform filter as the IU being configured. if (cu != null) { result.rootIUs.add(cu); @@ -708,10 +711,10 @@ public class Generator { IInstallableUnit iu = (IInstallableUnit) iterator.next(); required.add(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, iu.getId(), VersionRange.emptyRange, iu.getFilter(), false, false)); } - cat.setRequiredCapabilities((IRequiredCapability[]) required.toArray(new IRequiredCapability[required.size()])); + cat.setRequiredCapabilities((IRequirement[]) required.toArray(new IRequirement[required.size()])); cat.setCapabilities(new IProvidedCapability[] {MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, categoryId, Version.emptyVersion)}); cat.setArtifacts(new IArtifactKey[0]); - cat.setProperty(IInstallableUnit.PROP_TYPE_CATEGORY, "true"); //$NON-NLS-1$ + cat.setProperty(InstallableUnitDescription.PROP_TYPE_CATEGORY, "true"); //$NON-NLS-1$ return MetadataFactory.createInstallableUnit(cat); } @@ -796,12 +799,12 @@ public class Generator { String launcherIdPrefix = productNamespace + PRODUCT_LAUCHER_SUFFIX; String launcherId = launcherIdPrefix + '.' + ws + '.' + os + '.' + arch; iu.setId(launcherId); - Version launcherVersion = new Version(version); + Version launcherVersion = Version.create(version); iu.setVersion(launcherVersion); iu.setSingleton(true); - String filter = null; + Filter filter = null; if (!ws.equals(CONFIG_ANY) && !os.equals(CONFIG_ANY) && !arch.equals(CONFIG_ANY)) { - filter = "(& (osgi.ws=" + ws + ") (osgi.os=" + os + ") (osgi.arch=" + arch + "))"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + filter = ExpressionUtil.parseLDAP("(& (osgi.ws=" + ws + ") (osgi.os=" + os + ") (osgi.arch=" + arch + "))"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ iu.setFilter(filter); } @@ -814,7 +817,7 @@ public class Generator { String launcherFragment = ORG_ECLIPSE_EQUINOX_LAUNCHER + '.' + ws + '.' + os; if (!(Constants.OS_MACOSX.equals(os) && !Constants.ARCH_X86_64.equals(arch))) launcherFragment += '.' + arch; - iu.setRequiredCapabilities(new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, launcherFragment, VersionRange.emptyRange, filter, false, false)}); + iu.setRequiredCapabilities(new IRequirement[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, launcherFragment, VersionRange.emptyRange, filter, false, false)}); result.rootIUs.add(MetadataFactory.createInstallableUnit(iu)); //Create the CU @@ -824,8 +827,8 @@ public class Generator { cu.setVersion(launcherVersion); if (filter != null) cu.setFilter(filter); - cu.setHost(new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, launcherId, new VersionRange(launcherVersion, true, launcherVersion, true), null, false, false)}); - cu.setProperty(IInstallableUnit.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); + cu.setHost(new IRequirement[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, launcherId, new VersionRange(launcherVersion, true, launcherVersion, true), null, false, false)}); + cu.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); //TODO bug 218890, would like the fragment to provide the launcher capability as well, but can't right now. cu.setCapabilities(new IProvidedCapability[] {MetadataGeneratorHelper.createSelfCapability(configUnitId, launcherVersion)}); @@ -933,7 +936,7 @@ public class Generator { String configUnitId = info.getFlavor() + productFile.getId() + ".config." + ws + '.' + os + '.' + arch; //$NON-NLS-1$ String version = getProductVersion(); - Version cuVersion = new Version(version); + Version cuVersion = Version.create(version); cu.setId(configUnitId); cu.setVersion(cuVersion); cu.setSingleton(true); @@ -979,7 +982,7 @@ public class Generator { InstallableUnitDescription cu = new MetadataFactory.InstallableUnitDescription(); String configUnitId = info.getFlavor() + productFile.getId() + ".ini." + ws + '.' + os + '.' + arch; //$NON-NLS-1$ - Version cuVersion = new Version(version); + Version cuVersion = Version.create(version); cu.setId(configUnitId); cu.setVersion(cuVersion); cu.setSingleton(true); @@ -1023,10 +1026,10 @@ public class Generator { String location = feature.getLocation(); boolean isExploded = (location.endsWith(".jar") ? false : true); //$NON-NLS-1$ IInstallableUnit featureIU = MetadataGeneratorHelper.createFeatureJarIU(feature, true); - IArtifactKey[] artifacts = featureIU.getArtifacts(); + Collection artifacts = featureIU.getArtifacts(); storePluginShape(feature, result); - for (int arti = 0; arti < artifacts.length; arti++) { - IArtifactDescriptor ad = MetadataGeneratorHelper.createArtifactDescriptor(artifacts[arti], new File(location), true, false); + for (Iterator iterator = artifacts.iterator(); iterator.hasNext();) { + IArtifactDescriptor ad = MetadataGeneratorHelper.createArtifactDescriptor((IArtifactKey) iterator.next(), new File(location), true, false); if (isExploded) publishArtifact(ad, new File(location).listFiles(), destination, false, new File(location)); else diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/IGeneratorInfo.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/IGeneratorInfo.java index cf812eafe..21dd8e27a 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/IGeneratorInfo.java +++ b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/IGeneratorInfo.java @@ -15,8 +15,8 @@ import java.net.URI; import java.util.*; import org.eclipse.equinox.internal.provisional.frameworkadmin.ConfigData; import org.eclipse.equinox.internal.provisional.frameworkadmin.LauncherData; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; public interface IGeneratorInfo { diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/MetadataGeneratorHelper.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/MetadataGeneratorHelper.java index f2a157b4c..d3db5f58f 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/MetadataGeneratorHelper.java +++ b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/MetadataGeneratorHelper.java @@ -11,9 +11,6 @@ *******************************************************************************/ package org.eclipse.equinox.internal.provisional.p2.metadata.generator; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.io.*; import java.net.URI; import java.net.URISyntaxException; @@ -30,16 +27,20 @@ import org.eclipse.equinox.internal.p2.metadata.generator.Activator; import org.eclipse.equinox.internal.p2.metadata.generator.LocalizationHelper; import org.eclipse.equinox.internal.p2.metadata.generator.features.SiteCategory; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; import org.eclipse.osgi.service.environment.EnvironmentInfo; import org.eclipse.osgi.service.resolver.*; import org.eclipse.osgi.util.ManifestElement; -import org.osgi.framework.BundleException; -import org.osgi.framework.Constants; +import org.osgi.framework.*; /** * @deprecated this class has been renamed to PublisherHelper and the vast majority @@ -49,7 +50,6 @@ import org.osgi.framework.Constants; public class MetadataGeneratorHelper { /** * A capability namespace representing the type of Eclipse resource (bundle, feature, source bundle, etc) - * @see IRequiredCapability#getNamespace() * @see IProvidedCapability#getNamespace() */ public static final String NAMESPACE_ECLIPSE_TYPE = "org.eclipse.equinox.p2.eclipse.type"; //$NON-NLS-1$ @@ -57,28 +57,24 @@ public class MetadataGeneratorHelper { /** * A capability name in the {@link #NAMESPACE_ECLIPSE_TYPE} namespace * representing and OSGi bundle resource - * @see IRequiredCapability#getName() * @see IProvidedCapability#getName() */ public static final String TYPE_ECLIPSE_BUNDLE = "bundle"; //$NON-NLS-1$ /** * A capability name in the {@link #NAMESPACE_ECLIPSE_TYPE} namespace * representing a feature - * @see IRequiredCapability#getName() */ public static final String TYPE_ECLIPSE_FEATURE = "feature"; //$NON-NLS-1$ /** * A capability name in the {@link #NAMESPACE_ECLIPSE_TYPE} namespace * representing a source bundle - * @see IRequiredCapability#getName() */ public static final String TYPE_ECLIPSE_SOURCE = "source"; //$NON-NLS-1$ /** * A capability namespace representing the localization (translation) * of strings from a specified IU in a specified locale - * @see IRequiredCapability#getNamespace() * @see IProvidedCapability#getNamespace() * TODO: this should be in API, probably in IInstallableUnit */ @@ -96,13 +92,13 @@ public class MetadataGeneratorHelper { private static final String CAPABILITY_NS_UPDATE_FEATURE = "org.eclipse.update.feature"; //$NON-NLS-1$ - private static final Version DEFAULT_JRE_VERSION = new Version("1.6"); //$NON-NLS-1$ + private static final Version DEFAULT_JRE_VERSION = Version.create("1.6"); //$NON-NLS-1$ public static final String ECLIPSE_FEATURE_CLASSIFIER = "org.eclipse.update.feature"; //$NON-NLS-1$ public static final String OSGI_BUNDLE_CLASSIFIER = "osgi.bundle"; //$NON-NLS-1$ public static final String BINARY_ARTIFACT_CLASSIFIER = "binary"; //$NON-NLS-1$ - public static final String INSTALL_FEATURES_FILTER = "(org.eclipse.update.install.features=true)"; //$NON-NLS-1$ + public static final Filter INSTALL_FEATURES_FILTER = ExpressionUtil.parseLDAP("(org.eclipse.update.install.features=true)"); //$NON-NLS-1$ private static final String IU_NAMESPACE = IInstallableUnit.NAMESPACE_IU_ID; @@ -115,22 +111,22 @@ public class MetadataGeneratorHelper { private static final String UPDATE_FEATURE_PRIMARY_PROP = "org.eclipse.update.feature.primary"; //$NON-NLS-1$ //TODO - need to come up with a way to infer launcher version - private static final Version LAUNCHER_VERSION = new Version(1, 0, 0); - - private static final Version versionMax = new Version(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); + private static final Version LAUNCHER_VERSION = Version.createOSGi(1, 0, 0); - public static final ITouchpointType TOUCHPOINT_NATIVE = MetadataFactory.createTouchpointType("org.eclipse.equinox.p2.native", new Version(1, 0, 0)); //$NON-NLS-1$ - public static final ITouchpointType TOUCHPOINT_OSGI = MetadataFactory.createTouchpointType("org.eclipse.equinox.p2.osgi", new Version(1, 0, 0)); //$NON-NLS-1$ + public static final ITouchpointType TOUCHPOINT_NATIVE = MetadataFactory.createTouchpointType("org.eclipse.equinox.p2.native", Version.createOSGi(1, 0, 0)); //$NON-NLS-1$ + public static final ITouchpointType TOUCHPOINT_OSGI = MetadataFactory.createTouchpointType("org.eclipse.equinox.p2.osgi", Version.createOSGi(1, 0, 0)); //$NON-NLS-1$ - public static final IProvidedCapability BUNDLE_CAPABILITY = MetadataFactory.createProvidedCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_BUNDLE, new Version(1, 0, 0)); - public static final IProvidedCapability FEATURE_CAPABILITY = MetadataFactory.createProvidedCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_FEATURE, new Version(1, 0, 0)); - public static final IProvidedCapability SOURCE_BUNDLE_CAPABILITY = MetadataFactory.createProvidedCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_SOURCE, new Version(1, 0, 0)); + public static final IProvidedCapability BUNDLE_CAPABILITY = MetadataFactory.createProvidedCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_BUNDLE, Version.createOSGi(1, 0, 0)); + public static final IProvidedCapability FEATURE_CAPABILITY = MetadataFactory.createProvidedCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_FEATURE, Version.createOSGi(1, 0, 0)); + public static final IProvidedCapability SOURCE_BUNDLE_CAPABILITY = MetadataFactory.createProvidedCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_SOURCE, Version.createOSGi(1, 0, 0)); static final String DEFAULT_BUNDLE_LOCALIZATION = "plugin"; //$NON-NLS-1$ static final String BUNDLE_ADVICE_FILE = "META-INF/p2.inf"; //$NON-NLS-1$ static final String ADVICE_INSTRUCTIONS_PREFIX = "instructions."; //$NON-NLS-1$ + static final String NAMESPACE_FLAVOR = "org.eclipse.equinox.p2.flavor"; //$NON-NLS-1$" + public static IArtifactDescriptor createArtifactDescriptor(IArtifactKey key, File pathOnDisk, boolean asIs, boolean recur) { //TODO this size calculation is bogus ArtifactDescriptor result = new ArtifactDescriptor(key); @@ -187,7 +183,6 @@ public class MetadataGeneratorHelper { * @deprecated moved to AbstractPublishingAction */ public static IArtifactDescriptor createPack200ArtifactDescriptor(IArtifactKey key, File pathOnDisk, String installSize) { - final String PACKED_FORMAT = "packed"; //$NON-NLS-1$ //TODO this size calculation is bogus ArtifactDescriptor result = new ArtifactDescriptor(key); if (pathOnDisk != null) { @@ -195,9 +190,9 @@ public class MetadataGeneratorHelper { // TODO - this is wrong but I'm testing a work-around for bug 205842 result.setProperty(IArtifactDescriptor.DOWNLOAD_SIZE, Long.toString(pathOnDisk.length())); } - ProcessingStepDescriptor[] steps = new ProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; //$NON-NLS-1$ + IProcessingStepDescriptor[] steps = new IProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; //$NON-NLS-1$ result.setProcessingSteps(steps); - result.setProperty(IArtifactDescriptor.FORMAT, PACKED_FORMAT); + result.setProperty(IArtifactDescriptor.FORMAT, IArtifactDescriptor.FORMAT_PACKED); return result; } @@ -214,13 +209,13 @@ public class MetadataGeneratorHelper { cu.setVersion(iuVersion); //Indicate the IU to which this CU apply - cu.setHost(new IRequiredCapability[] { // - MetadataFactory.createRequiredCapability(CAPABILITY_NS_OSGI_BUNDLE, iuId, new VersionRange(iuVersion, true, versionMax, true), null, false, false, true), // - MetadataFactory.createRequiredCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_BUNDLE, new VersionRange(new Version(1, 0, 0), true, new Version(2, 0, 0), false), null, false, false, false)}); + cu.setHost(new IRequirement[] { // + MetadataFactory.createRequiredCapability(CAPABILITY_NS_OSGI_BUNDLE, iuId, new VersionRange(iuVersion, true, Version.MAX_VERSION, true), null, false, false, true), // + MetadataFactory.createRequiredCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_BUNDLE, new VersionRange(Version.createOSGi(1, 0, 0), true, Version.createOSGi(2, 0, 0), false), null, false, false, false)}); //Adds capabilities for fragment, self, and describing the flavor supported - cu.setProperty(IInstallableUnit.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); - cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configUnitId, iuVersion), MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_FLAVOR, configurationFlavor, new Version(1, 0, 0))}); + cu.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); + cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configUnitId, iuVersion), MetadataFactory.createProvidedCapability(NAMESPACE_FLAVOR, configurationFlavor, Version.createOSGi(1, 0, 0))}); Map touchpointData = new HashMap(); touchpointData.put("install", "installBundle(bundle:${artifact})"); //$NON-NLS-1$ //$NON-NLS-2$ @@ -249,7 +244,7 @@ public class MetadataGeneratorHelper { if (!base.equals(org.osgi.framework.Version.emptyVersion)) { updateRange = new VersionRange(Version.emptyVersion, true, Version.fromOSGiVersion(base), false); } else { - updateRange = new VersionRange("0.0.0"); //$NON-NLS-1$ + updateRange = VersionRange.emptyRange; } return updateRange; } @@ -297,7 +292,7 @@ public class MetadataGeneratorHelper { //TODO this needs to be refined to take into account all the attribute handled by imports reqsDeps.add(MetadataFactory.createRequiredCapability(CAPABILITY_NS_JAVA_PACKAGE, importPackageName, versionRange, null, isOptional(importSpec), false)); } - iu.setRequiredCapabilities((IRequiredCapability[]) reqsDeps.toArray(new IRequiredCapability[reqsDeps.size()])); + iu.setRequiredCapabilities((IRequirement[]) reqsDeps.toArray(new IRequirement[reqsDeps.size()])); // Create set of provided capabilities ArrayList providedCapabilities = new ArrayList(); @@ -418,11 +413,11 @@ public class MetadataGeneratorHelper { fragment.setVersion(Version.fromOSGiVersion(bd.getVersion())); // TODO: is this a meaningful version? HostSpecification hostSpec = bd.getHost(); - IRequiredCapability[] hostReqs = new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, hostSpec.getName(), VersionRange.fromOSGiVersionRange(hostSpec.getVersionRange()), null, false, false, false)}; + IRequirement[] hostReqs = new IRequirement[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, hostSpec.getName(), VersionRange.fromOSGiVersionRange(hostSpec.getVersionRange()), null, false, false, false)}; fragment.setHost(hostReqs); fragment.setSingleton(true); - fragment.setProperty(IInstallableUnit.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); + fragment.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); // Create a provided capability for each locale and add the translated properties. ArrayList providedCapabilities = new ArrayList(hostLocalizations.keySet().size()); @@ -463,7 +458,7 @@ public class MetadataGeneratorHelper { } private static IProvidedCapability makeTranslationCapability(String hostId, Locale locale) { - return MetadataFactory.createProvidedCapability(NAMESPACE_IU_LOCALIZATION, locale.toString(), new Version(1, 0, 0)); + return MetadataFactory.createProvidedCapability(NAMESPACE_IU_LOCALIZATION, locale.toString(), Version.createOSGi(1, 0, 0)); } /** @@ -487,13 +482,13 @@ public class MetadataGeneratorHelper { for (Iterator iterator = featureIUs.iterator(); iterator.hasNext();) { IInstallableUnit iu = (IInstallableUnit) iterator.next(); VersionRange range = new VersionRange(iu.getVersion(), true, iu.getVersion(), true); - reqsConfigurationUnits.add(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, iu.getId(), range, iu.getFilter(), false, false)); + reqsConfigurationUnits.add(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, iu.getId(), range, iu.getFilter() == null ? null : iu.getFilter(), false, false)); } //note that update sites don't currently support nested categories, but it may be useful to add in the future if (parentCategory != null) { - reqsConfigurationUnits.add(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, parentCategory.getId(), VersionRange.emptyRange, parentCategory.getFilter(), false, false)); + reqsConfigurationUnits.add(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, parentCategory.getId(), VersionRange.emptyRange, parentCategory.getFilter() == null ? null : parentCategory.getFilter(), false, false)); } - cat.setRequiredCapabilities((IRequiredCapability[]) reqsConfigurationUnits.toArray(new IRequiredCapability[reqsConfigurationUnits.size()])); + cat.setRequiredCapabilities((IRequirement[]) reqsConfigurationUnits.toArray(new IRequirement[reqsConfigurationUnits.size()])); // Create set of provided capabilities ArrayList providedCapabilities = new ArrayList(); @@ -516,7 +511,7 @@ public class MetadataGeneratorHelper { cat.setCapabilities((IProvidedCapability[]) providedCapabilities.toArray(new IProvidedCapability[providedCapabilities.size()])); cat.setArtifacts(new IArtifactKey[0]); - cat.setProperty(IInstallableUnit.PROP_TYPE_CATEGORY, "true"); //$NON-NLS-1$ + cat.setProperty(InstallableUnitDescription.PROP_TYPE_CATEGORY, "true"); //$NON-NLS-1$ return MetadataFactory.createInstallableUnit(cat); } @@ -556,15 +551,15 @@ public class MetadataGeneratorHelper { InstallableUnitFragmentDescription cu = new InstallableUnitFragmentDescription(); String configUnitId = createDefaultConfigUnitId(OSGI_BUNDLE_CLASSIFIER, configurationFlavor); cu.setId(configUnitId); - Version configUnitVersion = new Version(1, 0, 0); + Version configUnitVersion = Version.createOSGi(1, 0, 0); cu.setVersion(configUnitVersion); // Add capabilities for fragment, self, and describing the flavor supported - cu.setProperty(IInstallableUnit.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); - cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configUnitId, configUnitVersion), MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_FLAVOR, configurationFlavor, new Version(1, 0, 0))}); + cu.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); + cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configUnitId, configUnitVersion), MetadataFactory.createProvidedCapability(NAMESPACE_FLAVOR, configurationFlavor, Version.createOSGi(1, 0, 0))}); // Create a required capability on bundles - IRequiredCapability[] reqs = new IRequiredCapability[] {MetadataFactory.createRequiredCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_BUNDLE, VersionRange.emptyRange, null, false, true, false)}; + IRequirement[] reqs = new IRequirement[] {MetadataFactory.createRequiredCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_BUNDLE, VersionRange.emptyRange, null, false, true, false)}; cu.setHost(reqs); Map touchpointData = new HashMap(); @@ -592,15 +587,15 @@ public class MetadataGeneratorHelper { InstallableUnitFragmentDescription cu = new InstallableUnitFragmentDescription(); String configUnitId = createDefaultConfigUnitId(ECLIPSE_FEATURE_CLASSIFIER, configurationFlavor); cu.setId(configUnitId); - Version configUnitVersion = new Version(1, 0, 0); + Version configUnitVersion = Version.createOSGi(1, 0, 0); cu.setVersion(configUnitVersion); // Add capabilities for fragment, self, and describing the flavor supported - cu.setProperty(IInstallableUnit.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); - cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configUnitId, configUnitVersion), MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_FLAVOR, configurationFlavor, new Version(1, 0, 0))}); + cu.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); + cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configUnitId, configUnitVersion), MetadataFactory.createProvidedCapability(NAMESPACE_FLAVOR, configurationFlavor, Version.createOSGi(1, 0, 0))}); // Create a required capability on features - IRequiredCapability[] reqs = new IRequiredCapability[] {MetadataFactory.createRequiredCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_FEATURE, VersionRange.emptyRange, null, true, true, false)}; + IRequirement[] reqs = new IRequirement[] {MetadataFactory.createRequiredCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_FEATURE, VersionRange.emptyRange, null, true, true, false)}; cu.setHost(reqs); cu.setFilter(INSTALL_FEATURES_FILTER); @@ -616,15 +611,15 @@ public class MetadataGeneratorHelper { InstallableUnitFragmentDescription cu = new InstallableUnitFragmentDescription(); String configUnitId = createDefaultConfigUnitId("source", configurationFlavor); //$NON-NLS-1$ cu.setId(configUnitId); - Version configUnitVersion = new Version(1, 0, 0); + Version configUnitVersion = Version.createOSGi(1, 0, 0); cu.setVersion(configUnitVersion); // Add capabilities for fragment, self, and describing the flavor supported - cu.setProperty(IInstallableUnit.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); - cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configUnitId, configUnitVersion), MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_FLAVOR, configurationFlavor, new Version(1, 0, 0))}); + cu.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); + cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configUnitId, configUnitVersion), MetadataFactory.createProvidedCapability(NAMESPACE_FLAVOR, configurationFlavor, Version.createOSGi(1, 0, 0))}); // Create a required capability on source providers - IRequiredCapability[] reqs = new IRequiredCapability[] {MetadataFactory.createRequiredCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_SOURCE, VersionRange.emptyRange, null, true, true, false)}; + IRequirement[] reqs = new IRequirement[] {MetadataFactory.createRequiredCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_SOURCE, VersionRange.emptyRange, null, true, true, false)}; cu.setHost(reqs); Map touchpointData = new HashMap(); @@ -638,7 +633,7 @@ public class MetadataGeneratorHelper { * @deprecated moved to FeaturesAction */ public static IArtifactKey createFeatureArtifactKey(String fsn, String version) { - return new ArtifactKey(ECLIPSE_FEATURE_CLASSIFIER, fsn, new Version(version)); + return new ArtifactKey(ECLIPSE_FEATURE_CLASSIFIER, fsn, Version.create(version)); } /** @@ -666,7 +661,7 @@ public class MetadataGeneratorHelper { if (feature.getProviderName() != null) iu.setProperty(IInstallableUnit.PROP_PROVIDER, feature.getProviderName()); if (feature.getLicense() != null) - iu.setLicense(MetadataFactory.createLicense(toURIOrNull(feature.getLicenseURL()), feature.getLicense())); + iu.setLicenses(new ILicense[] {MetadataFactory.createLicense(toURIOrNull(feature.getLicenseURL()), feature.getLicense())}); if (feature.getCopyright() != null) iu.setCopyright(MetadataFactory.createCopyright(toURIOrNull(feature.getCopyrightURL()), feature.getCopyright())); if (feature.getApplication() != null) @@ -764,13 +759,13 @@ public class MetadataGeneratorHelper { if (feature.getProviderName() != null) iu.setProperty(IInstallableUnit.PROP_PROVIDER, feature.getProviderName()); if (feature.getLicense() != null) - iu.setLicense(MetadataFactory.createLicense(toURIOrNull(feature.getLicenseURL()), feature.getLicense())); + iu.setLicenses(new ILicense[] {MetadataFactory.createLicense(toURIOrNull(feature.getLicenseURL()), feature.getLicense())}); if (feature.getCopyright() != null) iu.setCopyright(MetadataFactory.createCopyright(toURIOrNull(feature.getCopyrightURL()), feature.getCopyright())); iu.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor(id, computeUpdateRange(new org.osgi.framework.Version(feature.getVersion())), IUpdateDescriptor.NORMAL, null)); FeatureEntry entries[] = feature.getEntries(); - IRequiredCapability[] required = new IRequiredCapability[entries.length + (featureIU == null ? 0 : 1)]; + IRequirement[] required = new IRequirement[entries.length + (featureIU == null ? 0 : 1)]; for (int i = 0; i < entries.length; i++) { VersionRange range = getVersionRange(entries[i]); String requiredId = entries[i].getId(); @@ -784,7 +779,7 @@ public class MetadataGeneratorHelper { required[entries.length] = MetadataFactory.createRequiredCapability(IU_NAMESPACE, featureIU.getId(), new VersionRange(featureIU.getVersion(), true, featureIU.getVersion(), true), INSTALL_FEATURES_FILTER, false, false); iu.setRequiredCapabilities(required); iu.setTouchpointType(ITouchpointType.NONE); - iu.setProperty(IInstallableUnit.PROP_TYPE_GROUP, Boolean.TRUE.toString()); + iu.setProperty(InstallableUnitDescription.PROP_TYPE_GROUP, Boolean.TRUE.toString()); // TODO: shouldn't the filter for the group be constructed from os, ws, arch, nl // of the feature? // iu.setFilter(filter); @@ -834,7 +829,7 @@ public class MetadataGeneratorHelper { if (feature.getProviderName() != null) iu.setProperty(IInstallableUnit.PROP_PROVIDER, feature.getProviderName()); if (feature.getLicense() != null) - iu.setLicense(MetadataFactory.createLicense(toURIOrNull(feature.getLicenseURL()), feature.getLicense())); + iu.setLicenses(new ILicense[] {MetadataFactory.createLicense(toURIOrNull(feature.getLicenseURL()), feature.getLicense())}); if (feature.getCopyright() != null) iu.setCopyright(MetadataFactory.createCopyright(toURIOrNull(feature.getCopyrightURL()), feature.getCopyright())); iu.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor(id, computeUpdateRange(new org.osgi.framework.Version(feature.getVersion())), IUpdateDescriptor.NORMAL, null)); @@ -845,13 +840,16 @@ public class MetadataGeneratorHelper { ArrayList requirementChanges = new ArrayList(); for (int i = 0; i < entries.length; i++) { VersionRange range = getVersionRange(entries[i]); - IRequiredCapability req = MetadataFactory.createRequiredCapability(IU_NAMESPACE, getTransformedId(entries[i].getId(), entries[i].isPlugin(), /*isGroup*/true), range, getFilter(entries[i]), entries[i].isOptional(), false); + IRequirement req = MetadataFactory.createRequiredCapability(IU_NAMESPACE, getTransformedId(entries[i].getId(), entries[i].isPlugin(), /*isGroup*/true), range, getFilter(entries[i]), entries[i].isOptional(), false); if (entries[i].isRequires()) { applicabilityScope.add(req); + if (applicabilityScope.size() == 1) { + iu.setLifeCycle(MetadataFactory.createRequiredCapability(IU_NAMESPACE, getTransformedId(entries[i].getId(), entries[i].isPlugin(), /*isGroup*/true), range, null, false, false, false)); + } continue; } if (entries[i].isPlugin()) { - IRequiredCapability from = MetadataFactory.createRequiredCapability(IU_NAMESPACE, getTransformedId(entries[i].getId(), entries[i].isPlugin(), /*isGroup*/true), VersionRange.emptyRange, getFilter(entries[i]), entries[i].isOptional(), false); + IRequirement from = MetadataFactory.createRequiredCapability(IU_NAMESPACE, getTransformedId(entries[i].getId(), entries[i].isPlugin(), /*isGroup*/true), VersionRange.emptyRange, getFilter(entries[i]), entries[i].isOptional(), false); requirementChanges.add(MetadataFactory.createRequirementChange(from, req)); continue; } @@ -859,21 +857,20 @@ public class MetadataGeneratorHelper { } //Always add a requirement on the IU containing the feature jar patchRequirements.add(MetadataFactory.createRequiredCapability(IU_NAMESPACE, featureIU.getId(), new VersionRange(featureIU.getVersion(), true, featureIU.getVersion(), true), INSTALL_FEATURES_FILTER, false, false)); - iu.setRequiredCapabilities((IRequiredCapability[]) patchRequirements.toArray(new IRequiredCapability[patchRequirements.size()])); - iu.setApplicabilityScope(new IRequiredCapability[][] {(IRequiredCapability[]) applicabilityScope.toArray(new IRequiredCapability[applicabilityScope.size()])}); + iu.setRequiredCapabilities((IRequirement[]) patchRequirements.toArray(new IRequirement[patchRequirements.size()])); + iu.setApplicabilityScope(new IRequirement[][] {(IRequirement[]) applicabilityScope.toArray(new IRequirement[applicabilityScope.size()])}); iu.setRequirementChanges((IRequirementChange[]) requirementChanges.toArray(new IRequirementChange[requirementChanges.size()])); //Generate lifecycle - IRequiredCapability lifeCycle = null; + IRequirement lifeCycle = null; if (applicabilityScope.size() > 0) { - IRequiredCapability req = (IRequiredCapability) applicabilityScope.get(0); - lifeCycle = MetadataFactory.createRequiredCapability(req.getNamespace(), req.getName(), req.getRange(), null, false, false, false); - iu.setLifeCycle(lifeCycle); + IRequirement req = (IRequirement) applicabilityScope.get(0); + } iu.setTouchpointType(ITouchpointType.NONE); - iu.setProperty(IInstallableUnit.PROP_TYPE_GROUP, Boolean.TRUE.toString()); - iu.setProperty(IInstallableUnit.PROP_TYPE_PATCH, Boolean.TRUE.toString()); + iu.setProperty(InstallableUnitDescription.PROP_TYPE_GROUP, Boolean.TRUE.toString()); + iu.setProperty(InstallableUnitDescription.PROP_TYPE_PATCH, Boolean.TRUE.toString()); // TODO: shouldn't the filter for the group be constructed from os, ws, arch, nl // of the feature? // iu.setFilter(filter); @@ -939,8 +936,8 @@ public class MetadataGeneratorHelper { String configId = "config." + id;//$NON-NLS-1$ cu.setId(configId); cu.setVersion(version); - cu.setHost(new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, id, new VersionRange(version, true, versionMax, true), null, false, false)}); - cu.setProperty(IInstallableUnit.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); + cu.setHost(new IRequirement[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, id, new VersionRange(version, true, Version.MAX_VERSION, true), null, false, false)}); + cu.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configId, version)}); cu.setTouchpointType(TOUCHPOINT_NATIVE); Map touchpointData = new HashMap(); @@ -1006,8 +1003,8 @@ public class MetadataGeneratorHelper { String configUnitId = configurationFlavor + launcherId; cu.setId(configUnitId); cu.setVersion(LAUNCHER_VERSION); - cu.setHost(new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, launcherId, new VersionRange(LAUNCHER_VERSION, true, versionMax, true), null, false, false)}); - cu.setProperty(IInstallableUnit.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); + cu.setHost(new IRequirement[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, launcherId, new VersionRange(LAUNCHER_VERSION, true, Version.MAX_VERSION, true), null, false, false)}); + cu.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configUnitId, LAUNCHER_VERSION)}); cu.setTouchpointType(TOUCHPOINT_NATIVE); Map touchpointData = new HashMap(); @@ -1142,11 +1139,11 @@ public class MetadataGeneratorHelper { Version version = DEFAULT_JRE_VERSION; //TODO Find a better way to determine JRE version if (profileName.indexOf("1.6") > 0) { //$NON-NLS-1$ - version = new Version("1.6"); //$NON-NLS-1$ + version = Version.create("1.6"); //$NON-NLS-1$ } else if (profileName.indexOf("1.5") > 0) { //$NON-NLS-1$ - version = new Version("1.5"); //$NON-NLS-1$ + version = Version.create("1.5"); //$NON-NLS-1$ } else if (profileName.indexOf("1.4") > 0) { //$NON-NLS-1$ - version = new Version("1.4"); //$NON-NLS-1$ + version = Version.create("1.4"); //$NON-NLS-1$ } iu.setVersion(version); try { @@ -1159,7 +1156,7 @@ public class MetadataGeneratorHelper { /** * @deprecated moved to FeaturesAction */ - public static String getFilter(FeatureEntry entry) { + public static Filter getFilter(FeatureEntry entry) { StringBuffer result = new StringBuffer(); result.append("(&"); //$NON-NLS-1$ if (entry.getFilter() != null) @@ -1175,7 +1172,7 @@ public class MetadataGeneratorHelper { if (result.length() == 2) return null; result.append(')'); - return result.toString(); + return ExpressionUtil.parseLDAP(result.toString()); } /** @@ -1192,20 +1189,22 @@ public class MetadataGeneratorHelper { String versionSpec = entry.getVersion(); if (versionSpec == null) return VersionRange.emptyRange; - Version version = new Version(versionSpec); + Version version = Version.create(versionSpec); if (version.equals(Version.emptyVersion)) return VersionRange.emptyRange; if (!entry.isRequires()) return new VersionRange(version, true, version, true); String match = entry.getMatch(); + + org.osgi.framework.Version osgiVersion = Version.toOSGiVersion(version); if (match == null || match.equals("compatible")) { //$NON-NLS-1$ - Version upper = new Version(version.getMajor() + 1, 0, 0); + Version upper = Version.createOSGi(osgiVersion.getMajor() + 1, 0, 0); return new VersionRange(version, true, upper, false); } if (match.equals("perfect")) //$NON-NLS-1$ return new VersionRange(version, true, version, true); if (match.equals("equivalent")) { //$NON-NLS-1$ - Version upper = new Version(version.getMajor(), version.getMinor() + 1, 0); + Version upper = Version.createOSGi(osgiVersion.getMajor(), osgiVersion.getMinor() + 1, 0); return new VersionRange(version, true, upper, false); } if (match.equals("greaterOrEqual")) //$NON-NLS-1$ diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/.classpath b/bundles/org.eclipse.equinox.p2.metadata.repository/.classpath index ef379494d..834ea833e 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/.classpath +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/.classpath @@ -1,6 +1,6 @@ - + diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/.externalToolBuilders/org.eclipse.equinox.p2.metadata.reposiroy buildAntTasks.xml.launch b/bundles/org.eclipse.equinox.p2.metadata.repository/.externalToolBuilders/org.eclipse.equinox.p2.metadata.reposiroy buildAntTasks.xml.launch index 864bdafe5..d3596d85e 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/.externalToolBuilders/org.eclipse.equinox.p2.metadata.reposiroy buildAntTasks.xml.launch +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/.externalToolBuilders/org.eclipse.equinox.p2.metadata.reposiroy buildAntTasks.xml.launch @@ -1,12 +1,11 @@ - - + - + - + @@ -15,4 +14,4 @@ - + \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.metadata.repository/.settings/org.eclipse.jdt.core.prefs index 904df3197..6a7984c9b 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Fri Feb 22 11:22:59 EST 2008 +#Mon Dec 28 00:17:37 CET 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.builder.cleanOutputFolder=clean org.eclipse.jdt.core.builder.duplicateResourceTask=warning @@ -7,24 +7,24 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fieldHiding=warning org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning @@ -71,7 +71,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=en org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.metadata.repository/META-INF/MANIFEST.MF index 45b9a8093..fcca9dedf 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/META-INF/MANIFEST.MF @@ -4,37 +4,16 @@ Bundle-SymbolicName: org.eclipse.equinox.p2.metadata.repository;singleton:=true Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-Localization: plugin -Bundle-Version: 1.0.100.qualifier -Export-Package: org.eclipse.equinox.internal.p2.metadata.mirror;x-internal:=true, - org.eclipse.equinox.internal.p2.metadata.repository; +Bundle-Version: 1.1.0.qualifier +Export-Package: org.eclipse.equinox.internal.p2.metadata.repository; x-friends:="org.eclipse.equinox.p2.engine, org.eclipse.equinox.p2.metadata.generator, org.eclipse.equinox.p2.publisher, org.eclipse.equinox.p2.reconciler.dropins, org.eclipse.equinox.p2.ui, - org.eclipse.equinox.p2.updatesite", - org.eclipse.equinox.internal.p2.metadata.repository.io;x-friends:="org.eclipse.equinox.p2.engine", - org.eclipse.equinox.internal.provisional.p2.metadata.repository; - x-friends:="org.eclipse.equinox.p2.console, - org.eclipse.equinox.p2.director, - org.eclipse.equinox.p2.director.app, - org.eclipse.equinox.p2.directorywatcher, - org.eclipse.equinox.p2.engine, - org.eclipse.equinox.p2.extensionlocation, - org.eclipse.equinox.p2.installer, - org.eclipse.equinox.p2.metadata.generator, - org.eclipse.equinox.p2.publisher, - org.eclipse.equinox.p2.reconciler.dropins, - org.eclipse.equinox.p2.ui, - org.eclipse.equinox.p2.ui.admin, - org.eclipse.equinox.p2.ui.sdk, - org.eclipse.equinox.p2.updatechecker, org.eclipse.equinox.p2.updatesite, - org.eclipse.pde.ui, - org.eclipse.equinox.p2.touchpoint.eclipse, - org.eclipse.equinox.p2.repository.tools, - org.eclipse.pde.core", - org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository;x-friends:="org.eclipse.equinox.p2.extensionlocation,org.eclipse.equinox.p2.updatesite,org.eclipse.equinox.p2.engine" + org.eclipse.equinox.p2.extensionlocation", + org.eclipse.equinox.internal.p2.metadata.repository.io;x-friends:="org.eclipse.equinox.p2.engine" Import-Package: javax.xml.parsers, org.eclipse.ecf.core.util, org.eclipse.equinox.app;resolution:=optional, @@ -43,22 +22,28 @@ Import-Package: javax.xml.parsers, org.eclipse.equinox.internal.p2.persistence, org.eclipse.equinox.internal.p2.repository, org.eclipse.equinox.internal.p2.repository.helpers, - org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.core.eventbus, - org.eclipse.equinox.internal.provisional.p2.core.location, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, org.eclipse.equinox.internal.provisional.p2.repository, - org.eclipse.equinox.internal.provisional.spi.p2.repository, org.eclipse.equinox.p2.core, org.eclipse.equinox.p2.core.spi, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.expression, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.metadata, + org.eclipse.equinox.p2.repository.metadata.spi, + org.eclipse.equinox.p2.repository.spi, org.eclipse.osgi.util;version="1.1.0", org.osgi.framework;version="1.3.0", + org.osgi.service.prefs;version="1.1.1", org.osgi.util.tracker;version="1.3.0", org.xml.sax Bundle-Activator: org.eclipse.equinox.internal.p2.metadata.repository.Activator Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: J2SE-1.4, +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, CDC-1.1/Foundation-1.1 Require-Bundle: org.eclipse.equinox.common;bundle-version="[3.5.0,4.0.0)", org.eclipse.equinox.registry, diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/OSGI-INF/repositoryManager.xml b/bundles/org.eclipse.equinox.p2.metadata.repository/OSGI-INF/repositoryManager.xml index 11fb66f15..fdf2579b5 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/OSGI-INF/repositoryManager.xml +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/OSGI-INF/repositoryManager.xml @@ -4,5 +4,5 @@ - + \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/build.properties b/bundles/org.eclipse.equinox.p2.metadata.repository/build.properties index 3e90a6c41..ffda85291 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/build.properties +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/build.properties @@ -24,3 +24,5 @@ jars.compile.order = .,\ ant_tasks/metadataRepository-ant.jar source.ant_tasks/metadataRepository-ant.jar = src_ant/ output.ant_tasks/metadataRepository-ant.jar = bin_ant/ +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/p2 tools - mirror metadata.launch b/bundles/org.eclipse.equinox.p2.metadata.repository/p2 tools - mirror metadata.launch deleted file mode 100644 index 4d7cb3c6a..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/p2 tools - mirror metadata.launch +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/plugin.xml b/bundles/org.eclipse.equinox.p2.metadata.repository/plugin.xml index c1bac455c..3deee9519 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/plugin.xml +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/plugin.xml @@ -4,20 +4,9 @@ - - - - - - - + + @@ -36,12 +25,6 @@ class="org.eclipse.equinox.internal.p2.metadata.repository.ant.CreateCompositeMetadataRepositoryTask"> - - - = 0 || token.indexOf('(') >= 0) && tokens.hasMoreTokens()) - result.add(token + separator + tokens.nextToken()); - else - result.add(token); - } - } - return (String[]) result.toArray(new String[result.size()]); - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext) - */ - public Object start(IApplicationContext context) throws Exception { - try { - initializeFromArguments((String[]) context.getArguments().get(IApplicationContext.APPLICATION_ARGS)); - setupRepositories(); - new Mirroring().mirror(source, destination, rootSpecs, transitive); - return IApplication.EXIT_OK; - } catch (Exception e) { - System.err.println(e.getMessage()); - throw e; - } finally { - //if the repository was not already loaded before the mirror application started, close it. - if (!sourceLoaded && sourceLocation != null) - getManager().removeRepository(sourceLocation); - if (!destinationLoaded && destinationLocation != null) - getManager().removeRepository(destinationLocation); - } - } - - private void setupRepositories() throws ProvisionException { - if (destinationLocation == null || sourceLocation == null) - throw new IllegalStateException("Must specify a source and destination"); //$NON-NLS-1$ - - //Check if repositories are already loaded - //TODO modify the contains statement once the API is available - sourceLoaded = getManager().contains(sourceLocation); - //TODO modify the contains statement once the API is available - destinationLoaded = getManager().contains(destinationLocation); - - //must execute before initializeDestination is called - source = getManager().loadRepository(sourceLocation, 0, null); - destination = initializeDestination(); - } - - /* - * Return the metadata repository manager. We need to check the service here - * as well as creating one manually in case we are running a stand-alone application - * in which no one has registered a manager yet. - */ - private IMetadataRepositoryManager getManager() { - if (cachedManager != null) - return cachedManager; - IMetadataRepositoryManager result = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); - // service not available... create one and hang onto it - if (result == null) { - cachedManager = new MetadataRepositoryManager(); - result = cachedManager; - } - return result; - } - - private IMetadataRepository initializeDestination() throws ProvisionException { - try { - IMetadataRepository repository = getManager().loadRepository(destinationLocation, IRepositoryManager.REPOSITORY_HINT_MODIFIABLE, null); - if (repository != null && repository.isModifiable()) { - if (destinationName != null) - repository.setName(destinationName); - if (!append) - repository.removeAll(); - return repository; - } - } catch (ProvisionException e) { - //fall through and create repo - } - //This code assumes source has been successfully loaded before this point - //No existing repository; create a new repository at destinationLocation but with source's attributes. - // TODO for now create a Simple repo by default. - return (IMetadataRepository) RepositoryHelper.validDestinationRepository(getManager().createRepository(destinationLocation, destinationName == null ? source.getName() : destinationName, IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, source.getProperties())); - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.app.IApplication#stop() - */ - public void stop() { - //do nothing - } - - public void initializeFromArguments(String[] args) throws Exception { - if (args == null) - return; - for (int i = 0; i < args.length; i++) { - // check for args with parameters. If we are at the last argument or - // if the next one has a '-' as the first character, then we can't have - // an arg with a param so continue. - if (i == args.length - 1 || args[i + 1].startsWith("-")) //$NON-NLS-1$ - continue; - String arg = args[++i]; - - if (args[i - 1].equalsIgnoreCase("-destinationName")) //$NON-NLS-1$ - destinationName = arg; - if (args[i - 1].equalsIgnoreCase("-writeMode")) //$NON-NLS-1$ - if (args[i].equalsIgnoreCase("clean")) //$NON-NLS-1$ - append = false; - - try { - if (args[i - 1].equalsIgnoreCase("-source")) //$NON-NLS-1$ - sourceLocation = RepositoryHelper.localRepoURIHelper(URIUtil.fromString(arg)); - if (args[i - 1].equalsIgnoreCase("-destination")) //$NON-NLS-1$ - destinationLocation = RepositoryHelper.localRepoURIHelper(URIUtil.fromString(arg)); - } catch (URISyntaxException e) { - throw new IllegalArgumentException("Repository location (" + arg + ") must be a URL."); //$NON-NLS-1$ //$NON-NLS-2$ - } - if (args[i - 1].equalsIgnoreCase("-roots")) //$NON-NLS-1$ - rootSpecs = getArrayArgsFromString(arg, ","); //$NON-NLS-1$ - if (args[i - 1].equalsIgnoreCase("-transitive")) //$NON-NLS-1$ - transitive = true; - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/mirror/Mirroring.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/mirror/Mirroring.java deleted file mode 100644 index 4d9f965f8..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/mirror/Mirroring.java +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 Code 9 and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Code 9 - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.mirror; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; - -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; - -/** - * A utility class that performs mirroring of metadatas between repositories. - */ -public class Mirroring { - - public void validate(IMetadataRepository source, IMetadataRepository destination) { - if (source == null) - throw new IllegalStateException("Source repository is null."); //$NON-NLS-1$ - if (destination == null) - throw new IllegalStateException("Destination repository is null."); //$NON-NLS-1$ - if (!destination.isModifiable()) - throw new IllegalStateException("Destination repository must be modifiable: " + destination.getLocation()); //$NON-NLS-1$ - } - - public void mirror(IMetadataRepository source, IMetadataRepository destination, String[] rootSpecs, boolean transitive) { - if (rootSpecs == null) - mirror(source, destination, InstallableUnitQuery.ANY, transitive); - else { - VersionRangedName[] roots = new VersionRangedName[rootSpecs.length]; - for (int i = 0; i < rootSpecs.length; i++) - roots[i] = VersionRangedName.parse(rootSpecs[i]); - mirror(source, destination, new RangeQuery(roots), transitive); - } - } - - public void mirror(IMetadataRepository source, IMetadataRepository destination, Query query, boolean transitive) { - validate(source, destination); - Collector result = source.query(query, new Collector(), null); - mirror(source, destination, (IInstallableUnit[]) result.toArray(IInstallableUnit.class), transitive); - } - - private void mirror(IMetadataRepository source, IMetadataRepository destination, IInstallableUnit[] roots, boolean transitive) { - if (transitive) - roots = addTransitiveIUs(source, roots); - destination.addInstallableUnits(roots); - } - - protected IInstallableUnit[] addTransitiveIUs(IMetadataRepository source, IInstallableUnit[] roots) { - // TODO Here we should create a profile from the source repo and discover all the - // IUs that are needed to support the given roots. For now just assume that the - // given roots are enough. - return roots; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/mirror/RangeQuery.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/mirror/RangeQuery.java deleted file mode 100644 index 5c2803f00..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/mirror/RangeQuery.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 Code 9 and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Code 9 - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.mirror; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.MatchQuery; - -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; - -/** - * A convenience query that will match any {@link IInstallableUnit} - * it encounters. - */ -public class RangeQuery extends MatchQuery { - private VersionRangedName[] targets; - - /** - * Creates a query that will match any {@link IInstallableUnit} with the given - * VerionRangedName. - * - * @param targets The installable unit names with versions to match, or null to match any id - */ - public RangeQuery(VersionRangedName[] targets) { - this.targets = targets; - } - - /** - * Returns true if the IInstallableUnit object is contained in the VerionRangedName's or targets is null. - */ - public boolean isMatch(Object object) { - if (!(object instanceof IInstallableUnit)) - return false; - if (targets == null) - return true; - IInstallableUnit candidate = (IInstallableUnit) object; - for (int i = 0; i < targets.length; i++) { - VersionRangedName entry = targets[i]; - if (entry.getId().equalsIgnoreCase(candidate.getId()) && entry.getVersionRange().isIncluded(candidate.getVersion())) - return true; - } - return false; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/mirror/VersionRangedName.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/mirror/VersionRangedName.java deleted file mode 100644 index 087fc9c2f..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/mirror/VersionRangedName.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 Code 9 and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Code 9 - initial API and implementation - * IBM - ongoing development - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.mirror; - -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - -public class VersionRangedName { - private final String id; - private final VersionRange range; - - /** - * Creates and returns a new version ranged id from the given spec. The spec should be - * id/version range. - * @param spec the spec for the version ranged id to create - * @return the parsed versioned id - */ - public static VersionRangedName parse(String spec) { - String[] segments = MirrorApplication.getArrayArgsFromString(spec, "/"); //$NON-NLS-1$ - return new VersionRangedName(segments[0], segments.length == 1 ? null : segments[1]); - } - - public VersionRangedName(String id, String rangeSpec) { - this(id, new VersionRange(rangeSpec)); - } - - public VersionRangedName(String id, VersionRange range) { - if (id == null) - throw new IllegalArgumentException("id cannot be null"); //$NON-NLS-1$ - this.id = id; - this.range = range != null ? range : new VersionRange(null); - } - - public String getId() { - return id; - } - - public VersionRange getVersionRange() { - return range; - } - - public String toString() { - return id + "/" + (range == null ? "0.0.0" : range.toString()); //$NON-NLS-1$ //$NON-NLS-2$ - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/Activator.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/Activator.java index 0706b2556..59e004922 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/Activator.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/Activator.java @@ -11,10 +11,8 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.repository; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.osgi.framework.*; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; @@ -25,66 +23,48 @@ public class Activator implements BundleActivator, ServiceTrackerCustomizer { public static final String REPO_PROVIDER_XPT = ID + '.' + "metadataRepositories"; //$NON-NLS-1$ private static BundleContext bundleContext; - private static CacheManager cacheManager; private ServiceRegistration repositoryManagerRegistration; - private MetadataRepositoryManager repositoryManager; - private ServiceTracker busTracker; + private ServiceTracker tracker; public static BundleContext getContext() { return bundleContext; } - public static CacheManager getCacheManager() { - return cacheManager; + public Object addingService(ServiceReference reference) { + if (repositoryManagerRegistration == null) { + //TODO: eventually we shouldn't register a singleton manager automatically + IProvisioningAgent agent = (IProvisioningAgent) bundleContext.getService(reference); + IMetadataRepositoryManager manager = (MetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME); + repositoryManagerRegistration = bundleContext.registerService(IMetadataRepositoryManager.SERVICE_NAME, manager, null); + return agent; + } + return null; } - public void start(BundleContext context) throws Exception { - //TODO eventually there should be no singleton repository manager registered - Activator.bundleContext = context; - cacheManager = new CacheManager((AgentLocation) ServiceHelper.getService(context, AgentLocation.SERVICE_NAME)); - repositoryManager = new MetadataRepositoryManager(); - repositoryManagerRegistration = context.registerService(IMetadataRepositoryManager.class.getName(), repositoryManager, null); - - // need to track event bus coming and going to make sure cache gets cleaned on repository removals - busTracker = new ServiceTracker(context, IProvisioningEventBus.SERVICE_NAME, this); - busTracker.open(); + public void modifiedService(ServiceReference reference, Object service) { + // nothing to do } - public void stop(BundleContext context) throws Exception { - IProvisioningEventBus bus = (IProvisioningEventBus) busTracker.getService(); - if (cacheManager != null) { - cacheManager.unsetEventBus(bus); - cacheManager = null; - } - Activator.bundleContext = null; - if (repositoryManagerRegistration != null) + public void removedService(ServiceReference reference, Object service) { + if (repositoryManagerRegistration != null) { repositoryManagerRegistration.unregister(); - repositoryManagerRegistration = null; - if (repositoryManager != null) { - repositoryManager.shutdown(); - repositoryManager = null; + repositoryManagerRegistration = null; } } - public Object addingService(ServiceReference reference) { - IProvisioningEventBus bus = (IProvisioningEventBus) bundleContext.getService(reference); - if (repositoryManager != null) - repositoryManager.setEventBus(bus); - if (cacheManager != null) - cacheManager.setEventBus(bus); - return bus; + public void start(BundleContext aContext) throws Exception { + bundleContext = aContext; + //only want to register a service for the agent of the currently running system + String filter = "(&(objectClass=" + IProvisioningAgent.SERVICE_NAME + ")(agent.current=true))"; //$NON-NLS-1$ //$NON-NLS-2$ + tracker = new ServiceTracker(aContext, aContext.createFilter(filter), this); + tracker.open(); } - public void modifiedService(ServiceReference reference, Object service) { - // ignored - - } - - public void removedService(ServiceReference reference, Object service) { - final IProvisioningEventBus bus = (IProvisioningEventBus) service; - if (repositoryManager != null) - repositoryManager.unsetEventBus(bus); - if (cacheManager != null) - cacheManager.unsetEventBus(bus); + public void stop(BundleContext aContext) throws Exception { + if (tracker != null) { + tracker.close(); + tracker = null; + } + bundleContext = null; } } diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CacheManager.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CacheManager.java index 24397e5e4..0e4eba8e5 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CacheManager.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CacheManager.java @@ -11,21 +11,22 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.repository; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.*; import java.net.URI; -import java.net.URL; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.ecf.filetransfer.UserCancelledException; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.p2.core.helpers.URLUtil; import org.eclipse.equinox.internal.p2.repository.*; import org.eclipse.equinox.internal.p2.repository.Activator; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.SynchronousProvisioningListener; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; -import org.eclipse.equinox.internal.provisional.p2.repository.*; +import org.eclipse.equinox.internal.provisional.p2.repository.IStateful; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.repository.IRepository; import org.eclipse.osgi.util.NLS; /** @@ -37,7 +38,12 @@ import org.eclipse.osgi.util.NLS; * was created for the repository. */ public class CacheManager { - private final AgentLocation agentLocation; + /** + * Service name for the internal cache manager service. + */ + public static final String SERVICE_NAME = CacheManager.class.getName(); + + private final IAgentLocation agentLocation; /** * IStateful implementation of BufferedOutputStream. Class is used to get the status from @@ -61,7 +67,7 @@ public class CacheManager { } - public CacheManager(AgentLocation agentLocation) { + public CacheManager(IAgentLocation agentLocation) { this.agentLocation = agentLocation; } @@ -72,7 +78,7 @@ public class CacheManager { private static final String RESUME_DEFAULT = "true"; //$NON-NLS-1$ private static final String XML_EXTENSION = ".xml"; //$NON-NLS-1$ - private final HashSet knownPrefixes = new HashSet(5); + private final HashSet knownPrefixes = new HashSet(5); /** * Returns a hash of the repository location. @@ -211,8 +217,7 @@ public class CacheManager { * @param repositoryLocation */ void deleteCache(URI repositoryLocation) { - for (Iterator it = knownPrefixes.iterator(); it.hasNext();) { - String prefix = (String) it.next(); + for (String prefix : knownPrefixes) { File[] cacheFiles = getCacheFiles(repositoryLocation, prefix); for (int i = 0; i < cacheFiles.length; i++) { // delete the cache file if it exists @@ -241,8 +246,7 @@ public class CacheManager { * Returns the file corresponding to the data area to be used by the cache manager. */ private File getCacheDirectory() { - URL dataArea = agentLocation.getDataArea(Activator.ID + "/cache/"); //$NON-NLS-1$ - return URLUtil.toFile(dataArea); + return URIUtil.toFile(agentLocation.getDataArea(Activator.ID + "/cache/")); //$NON-NLS-1$ } /** @@ -264,7 +268,7 @@ public class CacheManager { return RepositoryTransport.getInstance(); } - public boolean isResumeEnabled() { + private boolean isResumeEnabled() { String resumeProp = System.getProperty(PROP_RESUMABLE, RESUME_DEFAULT); return Boolean.valueOf(resumeProp).booleanValue(); } @@ -333,7 +337,7 @@ public class CacheManager { * Adds a {@link SynchronousProvisioningListener} to the event bus for * deleting cache files when the corresponding repository is deleted. */ - public void registerRepoEventListener(IProvisioningEventBus eventBus) { + private void registerRepoEventListener(IProvisioningEventBus eventBus) { if (busListener == null) { busListener = new SynchronousProvisioningListener() { public void notify(EventObject o) { @@ -372,7 +376,7 @@ public class CacheManager { * Removes the {@link SynchronousProvisioningListener} that cleans up the * cache file from the event bus. */ - public void unregisterRepoEventListener(IProvisioningEventBus bus) { + private void unregisterRepoEventListener(IProvisioningEventBus bus) { if (bus != null && busListener != null) bus.removeListener(busListener); } diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepository.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepository.java index 0c57a1544..a627e566d 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepository.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepository.java @@ -19,20 +19,20 @@ import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryIO; import org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryState; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.ICompositeRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.AbstractMetadataRepository; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.ICompositeRepository; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.spi.AbstractMetadataRepository; import org.eclipse.osgi.util.NLS; -public class CompositeMetadataRepository extends AbstractMetadataRepository implements IMetadataRepository, ICompositeRepository { +public class CompositeMetadataRepository extends AbstractMetadataRepository implements IMetadataRepository, ICompositeRepository { static final public String REPOSITORY_TYPE = CompositeMetadataRepository.class.getName(); public static final String PI_REPOSITORY_TYPE = "compositeMetadataRepository"; //$NON-NLS-1$ @@ -42,27 +42,30 @@ public class CompositeMetadataRepository extends AbstractMetadataRepository impl // keep a list of the child URIs. they can be absolute or relative. they may or may not point // to a valid reachable repo - private List childrenURIs = new ArrayList(); + private List childrenURIs = new ArrayList(); // keep a list of the repositories that we have successfully loaded - private List loadedRepos = new ArrayList(); + private List loadedRepos = new ArrayList(); + private IMetadataRepositoryManager manager; /** * Create a Composite repository in memory. * @return the repository or null if unable to create one */ - public static CompositeMetadataRepository createMemoryComposite() { - IMetadataRepositoryManager manager = getManager(); - if (manager == null) + public static CompositeMetadataRepository createMemoryComposite(IProvisioningAgent agent) { + if (agent == null) + return null; + IMetadataRepositoryManager repoManager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME); + if (repoManager == null) return null; try { //create a unique opaque URI long time = System.currentTimeMillis(); URI repositoryURI = new URI("memory:" + String.valueOf(time)); //$NON-NLS-1$ - while (manager.contains(repositoryURI)) + while (repoManager.contains(repositoryURI)) repositoryURI = new URI("memory:" + String.valueOf(++time)); //$NON-NLS-1$ - CompositeMetadataRepository result = (CompositeMetadataRepository) manager.createRepository(repositoryURI, repositoryURI.toString(), IMetadataRepositoryManager.TYPE_COMPOSITE_REPOSITORY, null); - manager.removeRepository(repositoryURI); + CompositeMetadataRepository result = (CompositeMetadataRepository) repoManager.createRepository(repositoryURI, repositoryURI.toString(), IMetadataRepositoryManager.TYPE_COMPOSITE_REPOSITORY, null); + repoManager.removeRepository(repositoryURI); return result; } catch (ProvisionException e) { // just return null @@ -73,8 +76,8 @@ public class CompositeMetadataRepository extends AbstractMetadataRepository impl return null; } - static private IMetadataRepositoryManager getManager() { - return (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + private IMetadataRepositoryManager getManager() { + return manager; } private boolean isLocal() { @@ -85,8 +88,9 @@ public class CompositeMetadataRepository extends AbstractMetadataRepository impl return isLocal(); } - public CompositeMetadataRepository(URI location, String name, Map properties) { + CompositeMetadataRepository(IMetadataRepositoryManager manager, URI location, String name, Map properties) { super(name == null ? (location != null ? location.toString() : "") : name, REPOSITORY_TYPE, REPOSITORY_VERSION.toString(), location, null, null, properties); //$NON-NLS-1$ + this.manager = manager; //when creating a repository, we must ensure it exists on disk so a subsequent load will succeed save(); } @@ -94,8 +98,9 @@ public class CompositeMetadataRepository extends AbstractMetadataRepository impl /* * This is only called by the parser when loading a repository. */ - public CompositeMetadataRepository(CompositeRepositoryState state) { + CompositeMetadataRepository(IMetadataRepositoryManager manager, CompositeRepositoryState state) { super(state.getName(), state.getType(), state.getVersion(), state.getLocation(), state.getDescription(), state.getProvider(), state.getProperties()); + this.manager = manager; for (int i = 0; i < state.getChildren().length; i++) addChild(state.getChildren()[i], false); } @@ -114,22 +119,21 @@ public class CompositeMetadataRepository extends AbstractMetadataRepository impl result.setProvider(getProvider()); result.setProperties(getProperties()); // it is important to directly access the field so we have the relative URIs - result.setChildren((URI[]) childrenURIs.toArray(new URI[childrenURIs.size()])); + result.setChildren(childrenURIs.toArray(new URI[childrenURIs.size()])); return result; } - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { + public IQueryResult query(IQuery query, IProgressMonitor monitor) { if (monitor == null) monitor = new NullProgressMonitor(); try { // Query all the all the repositories this composite repo contains - CompoundQueryable queryable = new CompoundQueryable((IQueryable[]) loadedRepos.toArray(new IQueryable[loadedRepos.size()])); - collector = queryable.query(query, collector, monitor); + CompoundQueryable queryable = new CompoundQueryable(loadedRepos); + return queryable.query(query, monitor); } finally { if (monitor != null) monitor.done(); } - return collector; } private void addChild(URI childURI, boolean save) { @@ -172,13 +176,12 @@ public class CompositeMetadataRepository extends AbstractMetadataRepository impl if (removed) { // we removed the child from the list so remove the associated repo object as well IMetadataRepository found = null; - for (Iterator iter = loadedRepos.iterator(); found == null && iter.hasNext();) { - IMetadataRepository current = (IMetadataRepository) iter.next(); + for (IMetadataRepository current : loadedRepos) { URI repoLocation = current.getLocation(); - if (URIUtil.sameURI(childURI, repoLocation)) - found = current; - else if (URIUtil.sameURI(other, repoLocation)) + if (URIUtil.sameURI(childURI, repoLocation) || URIUtil.sameURI(other, repoLocation)) { found = current; + break; + } } if (found != null) loadedRepos.remove(found); @@ -200,7 +203,7 @@ public class CompositeMetadataRepository extends AbstractMetadataRepository impl throw new UnsupportedOperationException("Cannot remove IUs to a composite repository"); } - public synchronized boolean removeInstallableUnits(Query query, IProgressMonitor monitor) { + public synchronized boolean removeInstallableUnits(IInstallableUnit[] installableUnits, IProgressMonitor monitor) { throw new UnsupportedOperationException("Cannot remove IUs to a composite repository"); } @@ -233,7 +236,7 @@ public class CompositeMetadataRepository extends AbstractMetadataRepository impl return; File file = getActualLocation(location); File jarFile = getActualLocation(location, JAR_EXTENSION); - boolean compress = "true".equalsIgnoreCase((String) properties.get(PROP_COMPRESSED)); //$NON-NLS-1$ + boolean compress = "true".equalsIgnoreCase(properties.get(PROP_COMPRESSED)); //$NON-NLS-1$ try { OutputStream output = null; if (!compress) { @@ -267,10 +270,10 @@ public class CompositeMetadataRepository extends AbstractMetadataRepository impl } } - public List getChildren() { - List result = new ArrayList(); - for (Iterator iter = childrenURIs.iterator(); iter.hasNext();) - result.add(URIUtil.makeAbsolute((URI) iter.next(), location)); + public List getChildren() { + List result = new ArrayList(); + for (URI childURI : childrenURIs) + result.add(URIUtil.makeAbsolute(childURI, location)); return result; } diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepositoryFactory.java index c2560bbc3..74792b07d 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepositoryFactory.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/CompositeMetadataRepositoryFactory.java @@ -10,6 +10,10 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.repository; +import org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory; + +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.*; import java.net.URI; import java.util.Map; @@ -19,10 +23,9 @@ import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.Tracing; import org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryIO; import org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryState; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.util.NLS; public class CompositeMetadataRepositoryFactory extends MetadataRepositoryFactory { @@ -32,8 +35,14 @@ public class CompositeMetadataRepositoryFactory extends MetadataRepositoryFactor private static final String PROTOCOL_FILE = "file"; //$NON-NLS-1$ public static final String CONTENT_FILENAME = "compositeContent"; //$NON-NLS-1$ - public IMetadataRepository create(URI location, String name, String type, Map properties) { - return new CompositeMetadataRepository(location, name, properties); + public IMetadataRepository create(URI location, String name, String type, Map properties) { + return new CompositeMetadataRepository(getManager(), location, name, properties); + } + + private IMetadataRepositoryManager getManager() { + if (getAgent() != null) + return (IMetadataRepositoryManager) getAgent().getService(IMetadataRepositoryManager.SERVICE_NAME); + return null; } /** @@ -58,7 +67,10 @@ public class CompositeMetadataRepositoryFactory extends MetadataRepositoryFactor throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, null)); } //file is not local, create a cache of the repository metadata - localFile = Activator.getCacheManager().createCache(location, CONTENT_FILENAME, monitor); + CacheManager cache = (CacheManager) getAgent().getService(CacheManager.SERVICE_NAME); + if (cache == null) + throw new IllegalArgumentException("Cache manager service not available"); //$NON-NLS-1$ + localFile = cache.createCache(location, CONTENT_FILENAME, monitor); if (localFile == null) { //there is no remote file in either form String msg = NLS.bind(Messages.io_failedRead, location); @@ -69,7 +81,7 @@ public class CompositeMetadataRepositoryFactory extends MetadataRepositoryFactor /* * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory#validate(java.net.URL, org.eclipse.core.runtime.IProgressMonitor) + * @see org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory#validate(java.net.URL, org.eclipse.core.runtime.IProgressMonitor) */ public IStatus validate(URI location, IProgressMonitor monitor) { try { @@ -81,7 +93,7 @@ public class CompositeMetadataRepositoryFactory extends MetadataRepositoryFactor } /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory#load(java.net.URL, org.eclipse.core.runtime.IProgressMonitor) + * @see org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory#load(java.net.URL, org.eclipse.core.runtime.IProgressMonitor) */ public IMetadataRepository load(URI location, int flags, IProgressMonitor monitor) throws ProvisionException { return validateAndLoad(location, true, flags, monitor); @@ -124,7 +136,7 @@ public class CompositeMetadataRepositoryFactory extends MetadataRepositoryFactor CompositeRepositoryState resultState = io.read(localFile.toURL(), descriptorStream, CompositeMetadataRepository.PI_REPOSITORY_TYPE, sub.newChild(100)); if (resultState.getLocation() == null) resultState.setLocation(location); - CompositeMetadataRepository result = new CompositeMetadataRepository(resultState); + CompositeMetadataRepository result = new CompositeMetadataRepository(getManager(), resultState); if (Tracing.DEBUG_METADATA_PARSING) { time += System.currentTimeMillis(); Tracing.debug(debugMsg + "time (ms): " + time); //$NON-NLS-1$ diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/IUMap.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/IUMap.java new file mode 100644 index 000000000..ba8adab1d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/IUMap.java @@ -0,0 +1,107 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.repository; + +import java.util.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.Collector; +import org.eclipse.equinox.p2.query.IQueryResult; + +/** + * A map that stores {@link IInstallableUnit} instances in a way that is efficient to query + */ +public class IUMap { + /** + * Iterator over all the {@link IInstallableUnit} instances in the map. + */ + public class MapIterator implements Iterator { + //iterator over the keys in UIMap + private Iterator unitIterator; + //iterator over the Set inside a single value of the IUMap + private Iterator currentBucket; + + MapIterator() { + super(); + unitIterator = units.keySet().iterator(); + } + + public boolean hasNext() { + return unitIterator.hasNext() || (currentBucket != null && currentBucket.hasNext()); + } + + public IInstallableUnit next() { + if (currentBucket == null || !currentBucket.hasNext()) + currentBucket = units.get(unitIterator.next()).iterator(); + return currentBucket.next(); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + } + + /** + * Map> mapping IU id to iu's with that id. + */ + final Map> units = new HashMap>(); + + public void add(IInstallableUnit unit) { + Set matching = units.get(unit.getId()); + if (matching == null) { + matching = new HashSet(2); + units.put(unit.getId(), matching); + } + matching.add(unit); + } + + public void addAll(IInstallableUnit[] toAdd) { + for (int i = 0; i < toAdd.length; i++) + add(toAdd[i]); + } + + public void clear() { + units.clear(); + } + + public Iterator iterator() { + return new MapIterator(); + } + + public IQueryResult query(InstallableUnitQuery query) { + //iterate over the entire map, or just the IU's with the given id + Iterator candidates; + if (query.getId() == null) + candidates = iterator(); + else { + Collection bucket = units.get(query.getId()); + if (bucket == null) + return Collector.emptyCollector(); + candidates = bucket.iterator(); + } + return query.perform(candidates); + + } + + public void remove(IInstallableUnit unit) { + Set matching = units.get(unit.getId()); + if (matching == null) + return; + matching.remove(unit); + if (matching.isEmpty()) + units.remove(unit.getId()); + } + + public void removeAll(Collection toRemove) { + for (IInstallableUnit iu : toRemove) + remove(iu); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/LocalMetadataRepository.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/LocalMetadataRepository.java index a85a4e612..709c7357f 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/LocalMetadataRepository.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/LocalMetadataRepository.java @@ -11,27 +11,24 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; - -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; - import java.io.*; import java.net.URI; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.internal.p2.core.helpers.*; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.AbstractMetadataRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.RepositoryReference; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.spi.AbstractMetadataRepository; +import org.eclipse.equinox.p2.repository.spi.RepositoryReference; /** * A metadata repository that resides in the local file system. If the repository @@ -46,8 +43,8 @@ public class LocalMetadataRepository extends AbstractMetadataRepository { static final private String JAR_EXTENSION = ".jar"; //$NON-NLS-1$ static final private String XML_EXTENSION = ".xml"; //$NON-NLS-1$ - protected HashSet units = new LinkedHashSet(); - protected HashSet repositories = new HashSet(); + protected IUMap units = new IUMap(); + protected HashSet repositories = new HashSet(); private static File getActualLocation(URI location, String extension) { File spec = URIUtil.toFile(location); @@ -80,7 +77,7 @@ public class LocalMetadataRepository extends AbstractMetadataRepository { * @param location The location of the repository * @param name The name of the repository */ - public LocalMetadataRepository(URI location, String name, Map properties) { + public LocalMetadataRepository(URI location, String name, Map properties) { super(name == null ? (location != null ? location.toString() : "") : name, REPOSITORY_TYPE, REPOSITORY_VERSION.toString(), location, null, null, properties); //$NON-NLS-1$ if (!location.getScheme().equals("file")) //$NON-NLS-1$ throw new IllegalArgumentException("Invalid local repository location: " + location); //$NON-NLS-1$ @@ -91,7 +88,7 @@ public class LocalMetadataRepository extends AbstractMetadataRepository { public synchronized void addInstallableUnits(IInstallableUnit[] installableUnits) { if (installableUnits == null || installableUnits.length == 0) return; - units.addAll(Arrays.asList(installableUnits)); + units.addAll(installableUnits); save(); } @@ -109,7 +106,7 @@ public class LocalMetadataRepository extends AbstractMetadataRepository { this.description = state.Description; this.location = state.Location; this.properties = state.Properties; - this.units.addAll(Arrays.asList(state.Units)); + this.units.addAll(state.Units); this.repositories.addAll(Arrays.asList(state.Repositories)); } publishRepositoryReferences(); @@ -123,18 +120,17 @@ public class LocalMetadataRepository extends AbstractMetadataRepository { if (bus == null) return; - List repositoriesSnapshot = createRepositoriesSnapshot(); - for (Iterator it = repositoriesSnapshot.iterator(); it.hasNext();) { - RepositoryReference reference = (RepositoryReference) it.next(); + List repositoriesSnapshot = createRepositoriesSnapshot(); + for (RepositoryReference reference : repositoriesSnapshot) { boolean isEnabled = (reference.Options & IRepository.ENABLED) != 0; bus.publishEvent(new RepositoryEvent(reference.Location, reference.Type, RepositoryEvent.DISCOVERED, isEnabled)); } } - private synchronized List createRepositoriesSnapshot() { + private synchronized List createRepositoriesSnapshot() { if (repositories.isEmpty()) - return Collections.EMPTY_LIST; - return new ArrayList(repositories); + return CollectionUtils.emptyList(); + return new ArrayList(repositories); } // use this method to setup any transient fields etc after the object has been restored from a stream @@ -146,8 +142,10 @@ public class LocalMetadataRepository extends AbstractMetadataRepository { return true; } - public synchronized Collector query(Query query, Collector collector, IProgressMonitor monitor) { - return query.perform(units.iterator(), collector); + public synchronized IQueryResult query(IQuery query, IProgressMonitor monitor) { + if (query instanceof InstallableUnitQuery) + return units.query((InstallableUnitQuery) query); + return query.perform(units.iterator()); } public synchronized void removeAll() { @@ -155,12 +153,11 @@ public class LocalMetadataRepository extends AbstractMetadataRepository { save(); } - public synchronized boolean removeInstallableUnits(Query query, IProgressMonitor monitor) { + public synchronized boolean removeInstallableUnits(IInstallableUnit[] installableUnits, IProgressMonitor monitor) { boolean changed = false; - Collector results = query.perform(units.iterator(), new Collector()); - if (results.size() > 0) { + if (installableUnits != null && installableUnits.length > 0) { changed = true; - units.removeAll(results.toCollection()); + units.removeAll(Arrays.asList(installableUnits)); } if (changed) save(); @@ -171,7 +168,7 @@ public class LocalMetadataRepository extends AbstractMetadataRepository { private void save() { File file = getActualLocation(location); File jarFile = getActualLocation(location, JAR_EXTENSION); - boolean compress = "true".equalsIgnoreCase((String) properties.get(PROP_COMPRESSED)); //$NON-NLS-1$ + boolean compress = "true".equalsIgnoreCase(properties.get(PROP_COMPRESSED)); //$NON-NLS-1$ try { OutputStream output = null; if (!compress) { @@ -214,7 +211,7 @@ public class LocalMetadataRepository extends AbstractMetadataRepository { save(); } //force repository manager to reload this repository because it caches properties - MetadataRepositoryManager manager = (MetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + MetadataRepositoryManager manager = (MetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); if (manager.removeRepository(getLocation())) manager.addRepository(this); return oldValue; diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/MetadataRepositoryComponent.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/MetadataRepositoryComponent.java index 9474158c8..822be6365 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/MetadataRepositoryComponent.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/MetadataRepositoryComponent.java @@ -11,10 +11,10 @@ package org.eclipse.equinox.internal.p2.metadata.repository; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.IAgentLocation; import org.eclipse.equinox.p2.core.IProvisioningAgent; import org.eclipse.equinox.p2.core.spi.IAgentServiceFactory; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; /** * Service factory for creating {@link IMetadataRepositoryManager} instances. @@ -25,8 +25,11 @@ public class MetadataRepositoryComponent implements IAgentServiceFactory { MetadataRepositoryManager manager = new MetadataRepositoryManager(); final IProvisioningEventBus eventBus = (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME); manager.setEventBus(eventBus); - CacheManager cache = new CacheManager((AgentLocation) agent.getService(AgentLocation.SERVICE_NAME)); + manager.setAgentLocation((IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME)); + manager.setAgent(agent); + CacheManager cache = new CacheManager((IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME)); cache.setEventBus(eventBus); + agent.registerService(CacheManager.SERVICE_NAME, cache); return manager; } diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/MetadataRepositoryIO.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/MetadataRepositoryIO.java index dbc5b1ccc..4de5b12e0 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/MetadataRepositoryIO.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/MetadataRepositoryIO.java @@ -11,10 +11,8 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.io.*; import java.net.MalformedURLException; @@ -28,13 +26,13 @@ import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; import org.eclipse.equinox.internal.p2.metadata.repository.io.MetadataParser; import org.eclipse.equinox.internal.p2.metadata.repository.io.MetadataWriter; import org.eclipse.equinox.internal.p2.persistence.XMLWriter; -import org.eclipse.equinox.internal.provisional.p2.core.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.AbstractMetadataRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.RepositoryReference; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.AbstractMetadataRepository.RepositoryState; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.spi.AbstractMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.spi.AbstractMetadataRepository.RepositoryState; +import org.eclipse.equinox.p2.repository.spi.RepositoryReference; import org.eclipse.osgi.util.NLS; import org.osgi.framework.BundleContext; import org.xml.sax.*; @@ -99,9 +97,9 @@ public class MetadataRepositoryIO { // Constants defining the structure of the XML for a MetadataRepository // A format version number for metadata repository XML. - public static final Version COMPATIBLE_VERSION = new Version(1, 0, 0); - public static final Version CURRENT_VERSION = new Version(1, 1, 0); - public static final VersionRange XML_TOLERANCE = new VersionRange(COMPATIBLE_VERSION, true, new Version(2, 0, 0), false); + public static final Version COMPATIBLE_VERSION = Version.createOSGi(1, 0, 0); + public static final Version CURRENT_VERSION = Version.createOSGi(1, 1, 0); + public static final VersionRange XML_TOLERANCE = new VersionRange(COMPATIBLE_VERSION, true, Version.createOSGi(2, 0, 0), false); // Constants for processing Instructions public static final String PI_REPOSITORY_TARGET = "metadataRepository"; //$NON-NLS-1$ @@ -111,7 +109,7 @@ public class MetadataRepositoryIO { } - protected XMLWriter.ProcessingInstruction[] createPI(Class repositoryClass) { + protected XMLWriter.ProcessingInstruction[] createPI(Class repositoryClass) { //TODO We should remove this processing instruction, but currently old clients rely on this. See bug 210450. return new XMLWriter.ProcessingInstruction[] {XMLWriter.ProcessingInstruction.makeTargetVersionInstruction(XMLConstants.PI_REPOSITORY_TARGET, XMLConstants.CURRENT_VERSION)}; } @@ -119,7 +117,7 @@ public class MetadataRepositoryIO { // XML writer for a IMetadataRepository protected class Writer extends MetadataWriter implements XMLConstants { - public Writer(OutputStream output, Class repositoryClass) throws IOException { + public Writer(OutputStream output, Class repositoryClass) throws IOException { super(output, createPI(repositoryClass)); } @@ -135,11 +133,12 @@ public class MetadataRepositoryIO { attributeOptional(DESCRIPTION_ATTRIBUTE, repository.getDescription()); // TODO: could be cdata? writeProperties(repository.getProperties()); - Collector units = repository.query(InstallableUnitQuery.ANY, new Collector(), null); if (repository instanceof LocalMetadataRepository) { - Set references = ((LocalMetadataRepository) repository).repositories; + Set references = ((LocalMetadataRepository) repository).repositories; writeRepositoryReferences(references.iterator(), references.size()); } + // The size attribute is a problematic since it forces the use of a collection. + Set units = repository.query(InstallableUnitQuery.ANY, null).unmodifiableSet(); writeInstallableUnits(units.iterator(), units.size()); end(REPOSITORY_ELEMENT); @@ -151,13 +150,13 @@ public class MetadataRepositoryIO { * @param references An Iterator of {@link RepositoryReference}. * @param size The number of references to write */ - protected void writeRepositoryReferences(Iterator references, int size) { + protected void writeRepositoryReferences(Iterator references, int size) { if (size == 0) return; start(REPOSITORY_REFERENCES_ELEMENT); attribute(COLLECTION_SIZE_ATTRIBUTE, size); while (references.hasNext()) - writeRepositoryReference((RepositoryReference) references.next()); + writeRepositoryReference(references.next()); end(REPOSITORY_REFERENCES_ELEMENT); } @@ -309,7 +308,7 @@ public class MetadataRepositoryIO { //can't create repository if missing type - this is already logged when parsing attributes if (state.Type == null) return; - Class clazz = Class.forName(state.Type); + Class clazz = Class.forName(state.Type); Object repositoryObject = clazz.newInstance(); if (repositoryObject instanceof AbstractMetadataRepository) { repository = (AbstractMetadataRepository) repositoryObject; diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/MetadataRepositoryManager.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/MetadataRepositoryManager.java index 35573be3c..315dc6f38 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/MetadataRepositoryManager.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/MetadataRepositoryManager.java @@ -11,22 +11,24 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.repository; +import org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory; + +import org.eclipse.equinox.p2.core.ProvisionException; + import java.net.URI; -import java.util.*; +import java.util.Map; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.util.NLS; /** * Default implementation of {@link IMetadataRepositoryManager}. */ -public class MetadataRepositoryManager extends AbstractRepositoryManager implements IMetadataRepositoryManager { +public class MetadataRepositoryManager extends AbstractRepositoryManager implements IMetadataRepositoryManager { public MetadataRepositoryManager() { super(); @@ -36,21 +38,23 @@ public class MetadataRepositoryManager extends AbstractRepositoryManager impleme super.addRepository(repository, true, null); } - public IMetadataRepository createRepository(URI location, String name, String type, Map properties) throws ProvisionException { + public IMetadataRepository createRepository(URI location, String name, String type, Map properties) throws ProvisionException { return (IMetadataRepository) doCreateRepository(location, name, type, properties); } - protected IRepository factoryCreate(URI location, String name, String type, Map properties, IExtension extension) throws ProvisionException { + protected IRepository factoryCreate(URI location, String name, String type, Map properties, IExtension extension) throws ProvisionException { MetadataRepositoryFactory factory = (MetadataRepositoryFactory) createExecutableExtension(extension, EL_FACTORY); if (factory == null) return null; + factory.setAgent(agent); return factory.create(location, name, type, properties); } - protected IRepository factoryLoad(URI location, IExtension extension, int flags, SubMonitor monitor) throws ProvisionException { + protected IRepository factoryLoad(URI location, IExtension extension, int flags, SubMonitor monitor) throws ProvisionException { MetadataRepositoryFactory factory = (MetadataRepositoryFactory) createExecutableExtension(extension, EL_FACTORY); if (factory == null) return null; + factory.setAgent(agent); return factory.load(location, flags, monitor.newChild(10)); } @@ -81,9 +85,6 @@ public class MetadataRepositoryManager extends AbstractRepositoryManager impleme return IRepository.TYPE_METADATA; } - /** - * @deprecated see {@link #loadRepository(URI, int, IProgressMonitor)} - */ public IMetadataRepository loadRepository(URI location, IProgressMonitor monitor) throws ProvisionException { return loadRepository(location, 0, monitor); } @@ -92,49 +93,6 @@ public class MetadataRepositoryManager extends AbstractRepositoryManager impleme return (IMetadataRepository) loadRepository(location, monitor, null, flags); } - /** - * Performs a query against all of the installable units of each known - * repository, accumulating any objects that satisfy the query in the - * provided collector. - *

    - * Note that using this method can be quite expensive, as every known - * metadata repository will be loaded in order to query each one. If a - * client wishes to query only certain repositories, it is better to use - * {@link #getKnownRepositories(int)} to filter the list of repositories - * loaded and then query each of the returned repositories. - *

    - * This method is long-running; progress and cancellation are provided - * by the given progress monitor. - * - * @param query The query to perform against each installable unit in each known repository - * @param collector Collects the results of the query - * @param monitor a progress monitor, or null if progress - * reporting is not desired - * @return The collector argument - */ - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - URI[] locations = getKnownRepositories(REPOSITORIES_ALL); - List queryables = new ArrayList(locations.length); // use a list since we don't know exactly how many will load - SubMonitor sub = SubMonitor.convert(monitor, locations.length * 10); - for (int i = 0; i < locations.length; i++) { - try { - if (sub.isCanceled()) - throw new OperationCanceledException(); - queryables.add(loadRepository(locations[i], sub.newChild(9))); - } catch (ProvisionException e) { - //ignore this repository for this query - } - } - try { - IQueryable[] queryablesArray = (IQueryable[]) queryables.toArray(new IQueryable[queryables.size()]); - CompoundQueryable compoundQueryable = new CompoundQueryable(queryablesArray); - compoundQueryable.query(query, collector, sub.newChild(locations.length * 1)); - } finally { - sub.done(); - } - return collector; - } - public IMetadataRepository refreshRepository(URI location, IProgressMonitor monitor) throws ProvisionException { return (IMetadataRepository) basicRefreshRepository(location, monitor); } diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/SimpleMetadataRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/SimpleMetadataRepositoryFactory.java new file mode 100644 index 000000000..9da7a8c06 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/SimpleMetadataRepositoryFactory.java @@ -0,0 +1,164 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.repository; + +import java.io.*; +import java.net.URI; +import java.util.Map; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.core.helpers.Tracing; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory; +import org.eclipse.osgi.util.NLS; + +public class SimpleMetadataRepositoryFactory extends MetadataRepositoryFactory { + + private static final String JAR_EXTENSION = ".jar"; //$NON-NLS-1$ + private static final String XML_EXTENSION = ".xml"; //$NON-NLS-1$ + private static final String PROTOCOL_FILE = "file"; //$NON-NLS-1$ + + public IMetadataRepository create(URI location, String name, String type, Map properties) { + if (location.getScheme().equals("file")) //$NON-NLS-1$ + return new LocalMetadataRepository(location, name, properties); + return new URLMetadataRepository(location, name, properties); + } + + /** + * Returns a file in the local file system that contains the contents of the + * metadata repository at the given location. + */ + private File getLocalFile(URI location, IProgressMonitor monitor) throws IOException, ProvisionException { + File localFile = null; + URI jarLocation = URLMetadataRepository.getActualLocation(location, JAR_EXTENSION); + URI xmlLocation = URLMetadataRepository.getActualLocation(location, XML_EXTENSION); + // If the repository is local, we can return the repository file directly + if (PROTOCOL_FILE.equals(xmlLocation.getScheme())) { + //look for a compressed local file + localFile = URIUtil.toFile(jarLocation); + if (localFile.exists()) + return localFile; + //look for an uncompressed local file + localFile = URIUtil.toFile(xmlLocation); + if (localFile.exists()) + return localFile; + String msg = NLS.bind(Messages.io_failedRead, location); + throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, null)); + } + // file is not local, create a cache of the repository metadata + CacheManager cache = (CacheManager) getAgent().getService(CacheManager.SERVICE_NAME); + if (cache == null) + throw new IllegalArgumentException("Cache manager service not available"); //$NON-NLS-1$ + localFile = cache.createCache(location, URLMetadataRepository.CONTENT_FILENAME, monitor); + if (localFile == null) { + // there is no remote file in either form - this should not really happen as + // createCache should bail out with exception if something is wrong. This is an internal + // error. + throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, Messages.repoMan_internalError, null)); + } + return localFile; + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory#validate(java.net.URL, org.eclipse.core.runtime.IProgressMonitor) + */ + public IStatus validate(URI location, IProgressMonitor monitor) { + try { + validateAndLoad(location, false, 0, monitor); + } catch (ProvisionException e) { + return e.getStatus(); + } + return Status.OK_STATUS; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory#load(java.net.URL, org.eclipse.core.runtime.IProgressMonitor) + */ + public IMetadataRepository load(URI location, int flags, IProgressMonitor monitor) throws ProvisionException { + return validateAndLoad(location, true, flags, monitor); + } + + protected IMetadataRepository validateAndLoad(URI location, boolean doLoad, int flags, IProgressMonitor monitor) throws ProvisionException { + long time = 0; + final String debugMsg = "Validating and loading metadata repository "; //$NON-NLS-1$ + if (Tracing.DEBUG_METADATA_PARSING) { + Tracing.debug(debugMsg + location); + time = -System.currentTimeMillis(); + } + SubMonitor sub = SubMonitor.convert(monitor, 400); + try { + File localFile = getLocalFile(location, sub.newChild(300)); + InputStream inStream = new BufferedInputStream(new FileInputStream(localFile)); + JarInputStream jarStream = null; + try { + //if reading from a jar, obtain a stream on the entry with the actual contents + if (localFile.getAbsolutePath().endsWith(JAR_EXTENSION)) { + jarStream = new JarInputStream(inStream); + JarEntry jarEntry = jarStream.getNextJarEntry(); + String entryName = URLMetadataRepository.CONTENT_FILENAME + URLMetadataRepository.XML_EXTENSION; + while (jarEntry != null && (!entryName.equals(jarEntry.getName()))) { + jarEntry = jarStream.getNextJarEntry(); + } + //if there is a jar but the entry is missing or invalid, treat this as an invalid repository + if (jarEntry == null) + throw new IOException(NLS.bind(Messages.repoMan_invalidLocation, location)); + } + //parse the repository descriptor file + sub.setWorkRemaining(100); + if (doLoad) { + InputStream descriptorStream = jarStream != null ? jarStream : inStream; + IMetadataRepository result = new MetadataRepositoryIO().read(localFile.toURL(), descriptorStream, sub.newChild(100)); + if (result != null && (flags & IRepositoryManager.REPOSITORY_HINT_MODIFIABLE) > 0 && !result.isModifiable()) + return null; + if (result instanceof LocalMetadataRepository) + ((LocalMetadataRepository) result).initializeAfterLoad(location); + if (result instanceof URLMetadataRepository) + ((URLMetadataRepository) result).initializeAfterLoad(location); + if (Tracing.DEBUG_METADATA_PARSING) { + time += System.currentTimeMillis(); + Tracing.debug(debugMsg + "time (ms): " + time); //$NON-NLS-1$ + } + return result; + } + } finally { + safeClose(jarStream); + safeClose(inStream); + } + } catch (FileNotFoundException e) { + String msg = NLS.bind(Messages.io_failedRead, location); + throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, e)); + } catch (IOException e) { + String msg = NLS.bind(Messages.io_failedRead, location); + throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, msg, e)); + } finally { + if (monitor != null) + monitor.done(); + } + return null; + } + + /** + * Closes a stream, ignoring any secondary exceptions + */ + private void safeClose(InputStream stream) { + if (stream == null) + return; + try { + stream.close(); + } catch (IOException e) { + //ignore + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/URLMetadataRepository.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/URLMetadataRepository.java index a80a20a33..287be742b 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/URLMetadataRepository.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/URLMetadataRepository.java @@ -11,15 +11,15 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; - import java.net.URI; -import java.util.*; +import java.util.Map; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.AbstractMetadataRepository; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.spi.AbstractMetadataRepository; /** * A metadata repository backed by an arbitrary URL. @@ -32,7 +32,7 @@ public class URLMetadataRepository extends AbstractMetadataRepository { private static final Integer REPOSITORY_VERSION = new Integer(1); transient protected URI content; - protected HashSet units = new LinkedHashSet(); + protected IUMap units = new IUMap(); public static URI getActualLocation(URI base) { return getActualLocation(base, XML_EXTENSION); @@ -48,7 +48,7 @@ public class URLMetadataRepository extends AbstractMetadataRepository { super(); } - public URLMetadataRepository(URI location, String name, Map properties) { + public URLMetadataRepository(URI location, String name, Map properties) { super(name == null ? (location != null ? location.toString() : "") : name, REPOSITORY_TYPE, REPOSITORY_VERSION.toString(), location, null, null, properties); //$NON-NLS-1$ content = getActualLocation(location); } @@ -66,7 +66,7 @@ public class URLMetadataRepository extends AbstractMetadataRepository { this.description = state.Description; this.location = state.Location; this.properties = state.Properties; - this.units.addAll(Arrays.asList(state.Units)); + this.units.addAll(state.Units); } // Use this method to setup any transient fields etc after the object has been restored from a stream @@ -79,7 +79,9 @@ public class URLMetadataRepository extends AbstractMetadataRepository { return false; } - public synchronized Collector query(Query query, Collector collector, IProgressMonitor monitor) { - return query.perform(units.iterator(), collector); + public synchronized IQueryResult query(IQuery query, IProgressMonitor monitor) { + if (query instanceof InstallableUnitQuery) + return units.query((InstallableUnitQuery) query); + return query.perform(units.iterator()); } } diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/io/MetadataParser.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/io/MetadataParser.java index d79b4df5d..e9eed98a8 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/io/MetadataParser.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/io/MetadataParser.java @@ -12,34 +12,47 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.repository.io; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.net.URI; import java.util.*; +import java.util.Map.Entry; import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; import org.eclipse.equinox.internal.p2.persistence.XMLParser; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.*; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.RepositoryReference; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil; +import org.eclipse.equinox.p2.repository.spi.RepositoryReference; import org.osgi.framework.BundleContext; +import org.osgi.framework.Filter; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; public abstract class MetadataParser extends XMLParser implements XMLConstants { + static final ILicense[] NO_LICENSES = new ILicense[0]; public MetadataParser(BundleContext context, String bundleId) { super(context, bundleId); } - protected class RepositoryReferencesHandler extends AbstractHandler { - private HashSet references; + protected abstract class AbstractMetadataHandler extends AbstractHandler { + + public AbstractMetadataHandler(ContentHandler parentHandler, String elementHandled) { + super(parentHandler, elementHandled); + } + + int getOptionalSize(Attributes attributes, int dflt) { + String sizeStr = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); + return sizeStr != null ? Integer.parseInt(sizeStr) : dflt; + } + } + + protected class RepositoryReferencesHandler extends AbstractMetadataHandler { + private HashSet references; public RepositoryReferencesHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, REPOSITORY_REFERENCES_ELEMENT); - String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - references = (size != null ? new HashSet(Integer.parseInt(size)) : new HashSet(4)); + references = new HashSet(getOptionalSize(attributes, 4)); } public void startElement(String name, Attributes attributes) { @@ -51,7 +64,7 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { } public RepositoryReference[] getReferences() { - return (RepositoryReference[]) references.toArray(new RepositoryReference[references.size()]); + return references.toArray(new RepositoryReference[references.size()]); } } @@ -59,7 +72,7 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { private final String[] required = new String[] {TYPE_ATTRIBUTE, OPTIONS_ATTRIBUTE}; - public RepositoryReferenceHandler(AbstractHandler parentHandler, Attributes attributes, Set references) { + public RepositoryReferenceHandler(AbstractHandler parentHandler, Attributes attributes, Set references) { super(parentHandler, REPOSITORY_REFERENCE_ELEMENT); String[] values = parseRequiredAttributes(attributes, required); String name = parseOptionalAttribute(attributes, NAME_ATTRIBUTE); @@ -75,23 +88,20 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { } } - protected class InstallableUnitsHandler extends AbstractHandler { - private ArrayList units; + protected class InstallableUnitsHandler extends AbstractMetadataHandler { + private ArrayList units; public InstallableUnitsHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, INSTALLABLE_UNITS_ELEMENT); - String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - units = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); + units = new ArrayList(getOptionalSize(attributes, 4)); } public IInstallableUnit[] getUnits() { int size = units.size(); IInstallableUnit[] result = new IInstallableUnit[size]; int i = 0; - for (Iterator it = units.iterator(); it.hasNext(); i++) { - InstallableUnitDescription desc = (InstallableUnitDescription) it.next(); - result[i] = MetadataFactory.createInstallableUnit(desc); - } + for (InstallableUnitDescription desc : units) + result[i++] = MetadataFactory.createInstallableUnit(desc); return result; } @@ -128,9 +138,9 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { private Version version; private boolean singleton; - private List units; + private List units; - public InstallableUnitHandler(AbstractHandler parentHandler, Attributes attributes, List units) { + public InstallableUnitHandler(AbstractHandler parentHandler, Attributes attributes, List units) { super(parentHandler, INSTALLABLE_UNIT_ELEMENT); String[] values = parseAttributes(attributes, REQUIRED_IU_ATTRIBUTES, OPTIONAL_IU_ATTRIBUTES); this.units = units; @@ -248,7 +258,7 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { if (isValidXML()) { if (requirementChangesHandler != null) { currentUnit = new MetadataFactory.InstallableUnitPatchDescription(); - ((InstallableUnitPatchDescription) currentUnit).setRequirementChanges((IRequirementChange[]) requirementChangesHandler.getRequirementChanges().toArray(new IRequirementChange[requirementChangesHandler.getRequirementChanges().size()])); + ((InstallableUnitPatchDescription) currentUnit).setRequirementChanges(requirementChangesHandler.getRequirementChanges().toArray(new IRequirementChange[requirementChangesHandler.getRequirementChanges().size()])); if (applicabilityScopeHandler != null) ((InstallableUnitPatchDescription) currentUnit).setApplicabilityScope(applicabilityScopeHandler.getScope()); if (lifeCycleHandler != null) @@ -265,15 +275,15 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { OrderedProperties properties = (propertiesHandler == null ? new OrderedProperties(0) : propertiesHandler.getProperties()); String updateFrom = null; VersionRange updateRange = null; - for (Enumeration e = properties.keys(); e.hasMoreElements();) { - String key = (String) e.nextElement(); - String value = properties.getProperty(key); + for (Entry e : properties.entrySet()) { + String key = e.getKey(); + String value = e.getValue(); //Backward compatibility - if (key.equals("equinox.p2.update.from")) { + if (key.equals("equinox.p2.update.from")) { //$NON-NLS-1$ updateFrom = value; continue; } - if (key.equals("equinox.p2.update.range")) { + if (key.equals("equinox.p2.update.range")) { //$NON-NLS-1$ updateRange = new VersionRange(value); continue; } @@ -286,8 +296,7 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { //End of backward compatibility if (licensesHandler != null) { - ILicense license = licensesHandler.getLicense(); - currentUnit.setLicense(license); + currentUnit.setLicenses(licensesHandler.getLicenses()); } if (copyrightHandler != null) { @@ -297,9 +306,9 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { IProvidedCapability[] providedCapabilities = (providedCapabilitiesHandler == null ? new IProvidedCapability[0] : providedCapabilitiesHandler.getProvidedCapabilities()); currentUnit.setCapabilities(providedCapabilities); - IRequiredCapability[] requiredCapabilities = (requiredCapabilitiesHandler == null ? new IRequiredCapability[0] : requiredCapabilitiesHandler.getRequiredCapabilities()); + IRequirement[] requiredCapabilities = (requiredCapabilitiesHandler == null ? new IRequirement[0] : requiredCapabilitiesHandler.getRequiredCapabilities()); currentUnit.setRequiredCapabilities(requiredCapabilities); - IRequiredCapability[] metaRequiredCapabilities = (metaRequiredCapabilitiesHandler == null ? new IRequiredCapability[0] : metaRequiredCapabilitiesHandler.getMetaRequiredCapabilities()); + IRequirement[] metaRequiredCapabilities = (metaRequiredCapabilitiesHandler == null ? new IRequirement[0] : metaRequiredCapabilitiesHandler.getMetaRequiredCapabilities()); currentUnit.setMetaRequiredCapabilities(metaRequiredCapabilities); if (filterHandler != null) { currentUnit.setFilter(filterHandler.getText()); @@ -321,13 +330,12 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { } } - protected class ApplicabilityScopesHandler extends AbstractHandler { - private List scopes; + protected class ApplicabilityScopesHandler extends AbstractMetadataHandler { + private List scopes; public ApplicabilityScopesHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, APPLICABILITY_SCOPE); - String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - scopes = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); + scopes = new ArrayList(getOptionalSize(attributes, 4)); } public void startElement(String name, Attributes attributes) { @@ -338,16 +346,16 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { } } - public IRequiredCapability[][] getScope() { - return (IRequiredCapability[][]) scopes.toArray(new IRequiredCapability[scopes.size()][]); + public IRequirement[][] getScope() { + return scopes.toArray(new IRequirement[scopes.size()][]); } } protected class ApplicabilityScopeHandler extends AbstractHandler { private RequiredCapabilitiesHandler children; - private List scopes; + private List scopes; - public ApplicabilityScopeHandler(AbstractHandler parentHandler, Attributes attributes, List scopes) { + public ApplicabilityScopeHandler(AbstractHandler parentHandler, Attributes attributes, List scopes) { super(parentHandler, APPLY_ON); this.scopes = scopes; } @@ -367,13 +375,12 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { } } - protected class RequirementsChangeHandler extends AbstractHandler { - private List requirementChanges; + protected class RequirementsChangeHandler extends AbstractMetadataHandler { + private List requirementChanges; public RequirementsChangeHandler(InstallableUnitHandler parentHandler, Attributes attributes) { super(parentHandler, REQUIREMENT_CHANGES); - String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - requirementChanges = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); + requirementChanges = new ArrayList(getOptionalSize(attributes, 4)); } public void startElement(String name, Attributes attributes) { @@ -384,20 +391,20 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { } } - public List getRequirementChanges() { + public List getRequirementChanges() { return requirementChanges; } } protected class RequirementChangeHandler extends AbstractHandler { - private List from; - private List to; - private List requirementChanges; + private List from; + private List to; + private List requirementChanges; - public RequirementChangeHandler(AbstractHandler parentHandler, Attributes attributes, List requirementChanges) { + public RequirementChangeHandler(AbstractHandler parentHandler, Attributes attributes, List requirementChanges) { super(parentHandler, REQUIREMENT_CHANGE); - from = new ArrayList(1); - to = new ArrayList(1); + from = new ArrayList(1); + to = new ArrayList(1); this.requirementChanges = requirementChanges; } @@ -415,14 +422,14 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { } protected void finished() { - requirementChanges.add(MetadataFactory.createRequirementChange(from.size() == 0 ? null : (IRequiredCapability) from.get(0), to.size() == 0 ? null : (IRequiredCapability) to.get(0))); + requirementChanges.add(MetadataFactory.createRequirementChange(from.size() == 0 ? null : (IRequirement) from.get(0), to.size() == 0 ? null : (IRequirement) to.get(0))); } } protected class RequirementChangeEltHandler extends AbstractHandler { - private List requirement; + private List requirement; - public RequirementChangeEltHandler(AbstractHandler parentHandler, String parentId, Attributes attributes, List from) { + public RequirementChangeEltHandler(AbstractHandler parentHandler, String parentId, Attributes attributes, List from) { super(parentHandler, parentId); requirement = from; } @@ -438,17 +445,17 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { } protected class LifeCycleHandler extends AbstractHandler { - private List lifeCycleRequirement; + private List lifeCycleRequirement; public LifeCycleHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, LIFECYCLE); - lifeCycleRequirement = new ArrayList(1); + lifeCycleRequirement = new ArrayList(1); } - public IRequiredCapability getLifeCycleRequirement() { + public IRequirement getLifeCycleRequirement() { if (lifeCycleRequirement.size() == 0) return null; - return (IRequiredCapability) lifeCycleRequirement.get(0); + return lifeCycleRequirement.get(0); } public void startElement(String name, Attributes attributes) { @@ -460,17 +467,16 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { } } - protected class ProvidedCapabilitiesHandler extends AbstractHandler { - private List providedCapabilities; + protected class ProvidedCapabilitiesHandler extends AbstractMetadataHandler { + private List providedCapabilities; public ProvidedCapabilitiesHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, PROVIDED_CAPABILITIES_ELEMENT); - String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - providedCapabilities = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); + providedCapabilities = new ArrayList(getOptionalSize(attributes, 4)); } public IProvidedCapability[] getProvidedCapabilities() { - return (IProvidedCapability[]) providedCapabilities.toArray(new IProvidedCapability[providedCapabilities.size()]); + return providedCapabilities.toArray(new IProvidedCapability[providedCapabilities.size()]); } public void startElement(String name, Attributes attributes) { @@ -484,7 +490,7 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { protected class ProvidedCapabilityHandler extends AbstractHandler { - public ProvidedCapabilityHandler(AbstractHandler parentHandler, Attributes attributes, List capabilities) { + public ProvidedCapabilityHandler(AbstractHandler parentHandler, Attributes attributes, List capabilities) { super(parentHandler, PROVIDED_CAPABILITY_ELEMENT); String[] values = parseRequiredAttributes(attributes, REQUIRED_PROVIDED_CAPABILITY_ATTRIBUTES); Version version = checkVersion(PROVIDED_CAPABILITY_ELEMENT, VERSION_ATTRIBUTE, values[2]); @@ -496,17 +502,16 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { } } - protected class HostRequiredCapabilitiesHandler extends AbstractHandler { - private List requiredCapabilities; + protected class HostRequiredCapabilitiesHandler extends AbstractMetadataHandler { + private List requiredCapabilities; public HostRequiredCapabilitiesHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, HOST_REQUIRED_CAPABILITIES_ELEMENT); - String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - requiredCapabilities = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); + requiredCapabilities = new ArrayList(getOptionalSize(attributes, 4)); } - public IRequiredCapability[] getHostRequiredCapabilities() { - return (IRequiredCapability[]) requiredCapabilities.toArray(new IRequiredCapability[requiredCapabilities.size()]); + public IRequirement[] getHostRequiredCapabilities() { + return requiredCapabilities.toArray(new IRequirement[requiredCapabilities.size()]); } public void startElement(String name, Attributes attributes) { @@ -518,17 +523,16 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { } } - protected class MetaRequiredCapabilitiesHandler extends AbstractHandler { - private List requiredCapabilities; + protected class MetaRequiredCapabilitiesHandler extends AbstractMetadataHandler { + private List requiredCapabilities; public MetaRequiredCapabilitiesHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, META_REQUIRED_CAPABILITIES_ELEMENT); - String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - requiredCapabilities = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); + requiredCapabilities = new ArrayList(getOptionalSize(attributes, 4)); } - public IRequiredCapability[] getMetaRequiredCapabilities() { - return (IRequiredCapability[]) requiredCapabilities.toArray(new IRequiredCapability[requiredCapabilities.size()]); + public IRequirement[] getMetaRequiredCapabilities() { + return requiredCapabilities.toArray(new IRequirement[requiredCapabilities.size()]); } public void startElement(String name, Attributes attributes) { @@ -540,17 +544,16 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { } } - protected class RequiredCapabilitiesHandler extends AbstractHandler { - private List requiredCapabilities; + protected class RequiredCapabilitiesHandler extends AbstractMetadataHandler { + private List requiredCapabilities; public RequiredCapabilitiesHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, REQUIRED_CAPABILITIES_ELEMENT); - String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - requiredCapabilities = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); + requiredCapabilities = new ArrayList(getOptionalSize(attributes, 4)); } - public IRequiredCapability[] getRequiredCapabilities() { - return (IRequiredCapability[]) requiredCapabilities.toArray(new IRequiredCapability[requiredCapabilities.size()]); + public IRequirement[] getRequiredCapabilities() { + return requiredCapabilities.toArray(new IRequirement[requiredCapabilities.size()]); } public void startElement(String name, Attributes attributes) { @@ -563,28 +566,34 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { } protected class RequiredCapabilityHandler extends AbstractHandler { + private List capabilities; - private IRequiredCapability currentCapability = null; + private String namespace; + private String name; + private VersionRange range; + private int min; + private int max; + private boolean greedy; private TextHandler filterHandler = null; - private CapabilitySelectorsHandler selectorsHandler = null; - public RequiredCapabilityHandler(AbstractHandler parentHandler, Attributes attributes, List capabilities) { + public RequiredCapabilityHandler(AbstractHandler parentHandler, Attributes attributes, List capabilities) { super(parentHandler, REQUIRED_CAPABILITY_ELEMENT); + this.capabilities = capabilities; String[] values = parseAttributes(attributes, REQIURED_CAPABILITY_ATTRIBUTES, OPTIONAL_CAPABILITY_ATTRIBUTES); - VersionRange range = checkVersionRange(REQUIRED_CAPABILITY_ELEMENT, VERSION_RANGE_ATTRIBUTE, values[2]); + namespace = values[0]; + name = values[1]; + range = checkVersionRange(REQUIRED_CAPABILITY_ELEMENT, VERSION_RANGE_ATTRIBUTE, values[2]); boolean isOptional = checkBoolean(REQUIRED_CAPABILITY_ELEMENT, CAPABILITY_OPTIONAL_ATTRIBUTE, values[3], false).booleanValue(); + min = isOptional ? 0 : 1; boolean isMultiple = checkBoolean(REQUIRED_CAPABILITY_ELEMENT, CAPABILITY_MULTIPLE_ATTRIBUTE, values[4], false).booleanValue(); - boolean isGreedy = checkBoolean(REQUIRED_CAPABILITY_ELEMENT, CAPABILITY_GREED_ATTRIBUTE, values[5], true).booleanValue(); - currentCapability = MetadataFactory.createRequiredCapability(values[0], values[1], range, null, isOptional, isMultiple, isGreedy); - capabilities.add(currentCapability); + max = isMultiple ? Integer.MAX_VALUE : 1; + greedy = checkBoolean(REQUIRED_CAPABILITY_ELEMENT, CAPABILITY_GREED_ATTRIBUTE, values[5], true).booleanValue(); } public void startElement(String name, Attributes attributes) { if (name.equals(CAPABILITY_FILTER_ELEMENT)) { filterHandler = new TextHandler(this, CAPABILITY_FILTER_ELEMENT, attributes); - } else if (name.equals(CAPABILITY_SELECTORS_ELEMENT)) { - selectorsHandler = new CapabilitySelectorsHandler(this, attributes); } else { invalidElement(name, attributes); } @@ -592,30 +601,26 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { protected void finished() { if (isValidXML()) { - if (currentCapability != null) { - if (filterHandler != null) { - currentCapability.setFilter(filterHandler.getText()); - } - if (selectorsHandler != null) { - currentCapability.setSelectors(selectorsHandler.getSelectors()); - } - } + Filter filter = null; + if (filterHandler != null) + filter = ExpressionUtil.parseLDAP(filterHandler.getText()); + capabilities.add(MetadataFactory.createRequiredCapability(namespace, name, range, filter, min, max, greedy)); } } } protected class ArtifactsHandler extends AbstractHandler { - private List artifacts; + private List artifacts; public ArtifactsHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, ARTIFACT_KEYS_ELEMENT); String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - artifacts = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); + artifacts = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); } public IArtifactKey[] getArtifactKeys() { - return (IArtifactKey[]) artifacts.toArray(new IArtifactKey[artifacts.size()]); + return artifacts.toArray(new IArtifactKey[artifacts.size()]); } public void startElement(String name, Attributes attributes) { @@ -631,7 +636,7 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { private final String[] required = new String[] {CLASSIFIER_ATTRIBUTE, ID_ATTRIBUTE, VERSION_ATTRIBUTE}; - public ArtifactHandler(AbstractHandler parentHandler, Attributes attributes, List artifacts) { + public ArtifactHandler(AbstractHandler parentHandler, Attributes attributes, List artifacts) { super(parentHandler, ARTIFACT_KEY_ELEMENT); String[] values = parseRequiredAttributes(attributes, required); Version version = checkVersion(ARTIFACT_KEY_ELEMENT, VERSION_ATTRIBUTE, values[2]); @@ -643,29 +648,6 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { } } - protected class CapabilitySelectorsHandler extends AbstractHandler { - - private List selectors; - - public CapabilitySelectorsHandler(AbstractHandler parentHandler, Attributes attributes) { - super(parentHandler, CAPABILITY_SELECTORS_ELEMENT); - String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - selectors = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); - } - - public String[] getSelectors() { - return (String[]) selectors.toArray(new String[selectors.size()]); - } - - public void startElement(String name, Attributes attributes) { - if (name.equals(CAPABILITY_SELECTOR_ELEMENT)) { - new TextHandler(this, CAPABILITY_SELECTOR_ELEMENT, attributes, selectors); - } else { - invalidElement(name, attributes); - } - } - } - protected class TouchpointTypeHandler extends AbstractHandler { private final String[] required = new String[] {ID_ATTRIBUTE, VERSION_ATTRIBUTE}; @@ -692,18 +674,18 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { ITouchpointData touchpointData = null; - List data = null; + List data = null; public TouchpointDataHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, TOUCHPOINT_DATA_ELEMENT); String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - data = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); + data = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); } public ITouchpointData[] getTouchpointData() { ITouchpointData[] result = new ITouchpointData[data.size()]; for (int i = 0; i < result.length; i++) - result[i] = ((TouchpointInstructionsHandler) data.get(i)).getTouchpointData(); + result[i] = data.get(i).getTouchpointData(); return result; } @@ -718,12 +700,12 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { protected class TouchpointInstructionsHandler extends AbstractHandler { - Map instructions = null; + Map instructions = null; - public TouchpointInstructionsHandler(AbstractHandler parentHandler, Attributes attributes, List data) { + public TouchpointInstructionsHandler(AbstractHandler parentHandler, Attributes attributes, List data) { super(parentHandler, TOUCHPOINT_DATA_INSTRUCTIONS_ELEMENT); String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - instructions = (size != null ? new LinkedHashMap(new Integer(size).intValue()) : new LinkedHashMap(4)); + instructions = (size != null ? new LinkedHashMap(new Integer(size).intValue()) : new LinkedHashMap(4)); } public ITouchpointData getTouchpointData() { @@ -744,11 +726,11 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { private final String[] required = new String[] {TOUCHPOINT_DATA_INSTRUCTION_KEY_ATTRIBUTE}; private final String[] optional = new String[] {TOUCHPOINT_DATA_INSTRUCTION_IMPORT_ATTRIBUTE}; - Map instructions = null; + Map instructions = null; String key = null; String qualifier = null; - public TouchpointInstructionHandler(AbstractHandler parentHandler, Attributes attributes, Map instructions) { + public TouchpointInstructionHandler(AbstractHandler parentHandler, Attributes attributes, Map instructions) { super(parentHandler, TOUCHPOINT_DATA_INSTRUCTION_ELEMENT); String[] values = parseAttributes(attributes, required, optional); key = values[0]; @@ -788,21 +770,22 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { * Handler for a list of licenses. */ protected class LicensesHandler extends AbstractHandler { + // Note this handler is set up to handle multiple license elements, but for now // the API for IInstallableUnit only reflects one. // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=216911 - private List licenses; + private List licenses; public LicensesHandler(ContentHandler parentHandler, Attributes attributes) { super(parentHandler, LICENSES_ELEMENT); String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - licenses = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(2)); + licenses = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(2)); } - public ILicense getLicense() { + public ILicense[] getLicenses() { if (licenses.size() == 0) - return null; - return (ILicense) licenses.get(0); + return NO_LICENSES; + return licenses.toArray(new ILicense[licenses.size()]); } public void startElement(String name, Attributes attributes) { @@ -822,9 +805,9 @@ public abstract class MetadataParser extends XMLParser implements XMLConstants { URI location = null; - private final List licenses; + private final List licenses; - public LicenseHandler(AbstractHandler parentHandler, Attributes attributes, List licenses) { + public LicenseHandler(AbstractHandler parentHandler, Attributes attributes, List licenses) { super(parentHandler, LICENSE_ELEMENT); location = parseURIAttribute(attributes, false); this.licenses = licenses; diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/io/MetadataWriter.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/io/MetadataWriter.java index 7879ab7b7..1a5801bb1 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/io/MetadataWriter.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/io/MetadataWriter.java @@ -14,13 +14,15 @@ package org.eclipse.equinox.internal.p2.metadata.repository.io; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; -import java.util.Iterator; -import java.util.Map; +import java.util.*; +import java.util.Map.Entry; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.p2.metadata.repository.Activator; import org.eclipse.equinox.internal.p2.persistence.XMLWriter; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.FragmentQuery; public abstract class MetadataWriter extends XMLWriter implements XMLConstants { @@ -34,13 +36,15 @@ public abstract class MetadataWriter extends XMLWriter implements XMLConstants { * @param units An Iterator of {@link IInstallableUnit}. * @param size The number of units to write */ - protected void writeInstallableUnits(Iterator units, int size) { + protected void writeInstallableUnits(Iterator units, int size) { if (size == 0) return; start(INSTALLABLE_UNITS_ELEMENT); + + // The size is a bummer. Is it really needed? It forces the use of a collect attribute(COLLECTION_SIZE_ATTRIBUTE, size); while (units.hasNext()) - writeInstallableUnit((IInstallableUnit) units.next()); + writeInstallableUnit(units.next()); end(INSTALLABLE_UNITS_ELEMENT); } @@ -52,7 +56,7 @@ public abstract class MetadataWriter extends XMLWriter implements XMLConstants { attribute(SINGLETON_ATTRIBUTE, iu.isSingleton(), true); // attribute(FRAGMENT_ATTRIBUTE, iu.isFragment(), false); - if (iu.isFragment() && iu instanceof IInstallableUnitFragment) { + if (FragmentQuery.isFragment(iu) && iu instanceof IInstallableUnitFragment) { IInstallableUnitFragment fragment = (IInstallableUnitFragment) iu; writeHostRequiredCapabilities(fragment.getHost()); } @@ -69,18 +73,18 @@ public abstract class MetadataWriter extends XMLWriter implements XMLConstants { writeMetaRequiredCapabilities(iu.getMetaRequiredCapabilities()); writeProvidedCapabilities(iu.getProvidedCapabilities()); writeRequiredCapabilities(iu.getRequiredCapabilities()); - writeTrimmedCdata(IU_FILTER_ELEMENT, iu.getFilter()); + writeTrimmedCdata(IU_FILTER_ELEMENT, iu.getFilter() == null ? null : iu.getFilter().toString()); writeArtifactKeys(iu.getArtifacts()); writeTouchpointType(iu.getTouchpointType()); writeTouchpointData(iu.getTouchpointData()); - writeLicenses(iu.getLicense()); + writeLicenses(iu.getLicenses()); writeCopyright(iu.getCopyright()); end(INSTALLABLE_UNIT_ELEMENT); } - protected void writeLifeCycle(IRequiredCapability capability) { + protected void writeLifeCycle(IRequirement capability) { if (capability == null) return; start(LIFECYCLE); @@ -88,7 +92,7 @@ public abstract class MetadataWriter extends XMLWriter implements XMLConstants { end(LIFECYCLE); } - protected void writeHostRequiredCapabilities(IRequiredCapability[] capabilities) { + protected void writeHostRequiredCapabilities(IRequirement[] capabilities) { if (capabilities != null && capabilities.length > 0) { start(HOST_REQUIRED_CAPABILITIES_ELEMENT); attribute(COLLECTION_SIZE_ATTRIBUTE, capabilities.length); @@ -99,38 +103,38 @@ public abstract class MetadataWriter extends XMLWriter implements XMLConstants { } } - protected void writeProvidedCapabilities(IProvidedCapability[] capabilities) { - if (capabilities != null && capabilities.length > 0) { + protected void writeProvidedCapabilities(Collection capabilities) { + if (capabilities != null && capabilities.size() > 0) { start(PROVIDED_CAPABILITIES_ELEMENT); - attribute(COLLECTION_SIZE_ATTRIBUTE, capabilities.length); - for (int i = 0; i < capabilities.length; i++) { + attribute(COLLECTION_SIZE_ATTRIBUTE, capabilities.size()); + for (IProvidedCapability capability : capabilities) { start(PROVIDED_CAPABILITY_ELEMENT); - attribute(NAMESPACE_ATTRIBUTE, capabilities[i].getNamespace()); - attribute(NAME_ATTRIBUTE, capabilities[i].getName()); - attribute(VERSION_ATTRIBUTE, capabilities[i].getVersion()); + attribute(NAMESPACE_ATTRIBUTE, capability.getNamespace()); + attribute(NAME_ATTRIBUTE, capability.getName()); + attribute(VERSION_ATTRIBUTE, capability.getVersion()); end(PROVIDED_CAPABILITY_ELEMENT); } end(PROVIDED_CAPABILITIES_ELEMENT); } } - protected void writeMetaRequiredCapabilities(IRequiredCapability[] capabilities) { - if (capabilities != null && capabilities.length > 0) { + protected void writeMetaRequiredCapabilities(Collection metaRequirements) { + if (metaRequirements != null && metaRequirements.size() > 0) { start(META_REQUIRED_CAPABILITIES_ELEMENT); - attribute(COLLECTION_SIZE_ATTRIBUTE, capabilities.length); - for (int i = 0; i < capabilities.length; i++) { - writeRequiredCapability(capabilities[i]); + attribute(COLLECTION_SIZE_ATTRIBUTE, metaRequirements.size()); + for (IRequirement req : metaRequirements) { + writeRequiredCapability(req); } end(META_REQUIRED_CAPABILITIES_ELEMENT); } } - protected void writeRequiredCapabilities(IRequiredCapability[] capabilities) { - if (capabilities != null && capabilities.length > 0) { + protected void writeRequiredCapabilities(Collection requirements) { + if (requirements != null && requirements.size() > 0) { start(REQUIRED_CAPABILITIES_ELEMENT); - attribute(COLLECTION_SIZE_ATTRIBUTE, capabilities.length); - for (int i = 0; i < capabilities.length; i++) { - writeRequiredCapability(capabilities[i]); + attribute(COLLECTION_SIZE_ATTRIBUTE, requirements.size()); + for (IRequirement req : requirements) { + writeRequiredCapability(req); } end(REQUIRED_CAPABILITIES_ELEMENT); } @@ -148,20 +152,20 @@ public abstract class MetadataWriter extends XMLWriter implements XMLConstants { end(UPDATE_DESCRIPTOR_ELEMENT); } - protected void writeApplicabilityScope(IRequiredCapability[][] capabilities) { + protected void writeApplicabilityScope(IRequirement[][] capabilities) { start(APPLICABILITY_SCOPE); for (int i = 0; i < capabilities.length; i++) { start(APPLY_ON); - writeRequiredCapabilities(capabilities[i]); + writeRequiredCapabilities(Arrays.asList(capabilities[i])); end(APPLY_ON); } end(APPLICABILITY_SCOPE); } - protected void writeRequirementsChange(IRequirementChange[] changes) { + protected void writeRequirementsChange(List changes) { start(REQUIREMENT_CHANGES); - for (int i = 0; i < changes.length; i++) { - writeRequirementChange(changes[i]); + for (int i = 0; i < changes.size(); i++) { + writeRequirementChange(changes.get(i)); } end(REQUIREMENT_CHANGES); } @@ -181,38 +185,34 @@ public abstract class MetadataWriter extends XMLWriter implements XMLConstants { end(REQUIREMENT_CHANGE); } - protected void writeRequiredCapability(IRequiredCapability capability) { - start(REQUIRED_CAPABILITY_ELEMENT); - attribute(NAMESPACE_ATTRIBUTE, capability.getNamespace()); - attribute(NAME_ATTRIBUTE, capability.getName()); - attribute(VERSION_RANGE_ATTRIBUTE, capability.getRange()); - attribute(CAPABILITY_OPTIONAL_ATTRIBUTE, capability.isOptional(), false); - attribute(CAPABILITY_MULTIPLE_ATTRIBUTE, capability.isMultiple(), false); - attribute(CAPABILITY_GREED_ATTRIBUTE, capability.isGreedy(), true); - writeTrimmedCdata(CAPABILITY_FILTER_ELEMENT, capability.getFilter()); - - String[] selectors = capability.getSelectors(); - if (selectors.length > 0) { - start(CAPABILITY_SELECTORS_ELEMENT); - attribute(COLLECTION_SIZE_ATTRIBUTE, selectors.length); - for (int j = 0; j < selectors.length; j++) { - writeTrimmedCdata(CAPABILITY_SELECTOR_ELEMENT, selectors[j]); - } - end(CAPABILITY_SELECTORS_ELEMENT); + protected void writeRequiredCapability(IRequirement requirement) { + if (requirement instanceof IRequiredCapability) { + IRequiredCapability reqCapability = (IRequiredCapability) requirement; + start(REQUIRED_CAPABILITY_ELEMENT); + attribute(NAMESPACE_ATTRIBUTE, reqCapability.getNamespace()); + attribute(NAME_ATTRIBUTE, reqCapability.getName()); + attribute(VERSION_RANGE_ATTRIBUTE, reqCapability.getRange()); + attribute(CAPABILITY_OPTIONAL_ATTRIBUTE, requirement.getMin() == 0, false); + attribute(CAPABILITY_MULTIPLE_ATTRIBUTE, requirement.getMax() > 1, false); + attribute(CAPABILITY_GREED_ATTRIBUTE, requirement.isGreedy(), true); + if (requirement.getFilter() != null) + writeTrimmedCdata(CAPABILITY_FILTER_ELEMENT, requirement.getFilter().toString()); + end(REQUIRED_CAPABILITY_ELEMENT); + } else { + throw new IllegalStateException(); } - end(REQUIRED_CAPABILITY_ELEMENT); } - protected void writeArtifactKeys(IArtifactKey[] artifactKeys) { - if (artifactKeys != null && artifactKeys.length > 0) { + protected void writeArtifactKeys(Collection artifactKeys) { + if (artifactKeys != null && artifactKeys.size() > 0) { start(ARTIFACT_KEYS_ELEMENT); - attribute(COLLECTION_SIZE_ATTRIBUTE, artifactKeys.length); - for (int i = 0; i < artifactKeys.length; i++) { + attribute(COLLECTION_SIZE_ATTRIBUTE, artifactKeys.size()); + for (IArtifactKey artifactKey : artifactKeys) { start(ARTIFACT_KEY_ELEMENT); - attribute(ARTIFACT_KEY_CLASSIFIER_ATTRIBUTE, artifactKeys[i].getClassifier()); - attribute(ID_ATTRIBUTE, artifactKeys[i].getId()); - attribute(VERSION_ATTRIBUTE, artifactKeys[i].getVersion()); + attribute(ARTIFACT_KEY_CLASSIFIER_ATTRIBUTE, artifactKey.getClassifier()); + attribute(ID_ATTRIBUTE, artifactKey.getId()); + attribute(VERSION_ATTRIBUTE, artifactKey.getVersion()); end(ARTIFACT_KEY_ELEMENT); } end(ARTIFACT_KEYS_ELEMENT); @@ -226,21 +226,20 @@ public abstract class MetadataWriter extends XMLWriter implements XMLConstants { end(TOUCHPOINT_TYPE_ELEMENT); } - protected void writeTouchpointData(ITouchpointData[] touchpointData) { - if (touchpointData != null && touchpointData.length > 0) { + protected void writeTouchpointData(List touchpointData) { + if (touchpointData != null && touchpointData.size() > 0) { start(TOUCHPOINT_DATA_ELEMENT); - attribute(COLLECTION_SIZE_ATTRIBUTE, touchpointData.length); - for (int i = 0; i < touchpointData.length; i++) { - ITouchpointData nextData = touchpointData[i]; - Map instructions = nextData.getInstructions(); + attribute(COLLECTION_SIZE_ATTRIBUTE, touchpointData.size()); + for (int i = 0; i < touchpointData.size(); i++) { + ITouchpointData nextData = touchpointData.get(i); + Map instructions = nextData.getInstructions(); if (instructions.size() > 0) { start(TOUCHPOINT_DATA_INSTRUCTIONS_ELEMENT); attribute(COLLECTION_SIZE_ATTRIBUTE, instructions.size()); - for (Iterator iter = instructions.entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); + for (Entry entry : instructions.entrySet()) { start(TOUCHPOINT_DATA_INSTRUCTION_ELEMENT); attribute(TOUCHPOINT_DATA_INSTRUCTION_KEY_ATTRIBUTE, entry.getKey()); - ITouchpointInstruction instruction = (ITouchpointInstruction) entry.getValue(); + ITouchpointInstruction instruction = entry.getValue(); if (instruction.getImportAttribute() != null) attribute(TOUCHPOINT_DATA_INSTRUCTION_IMPORT_ATTRIBUTE, instruction.getImportAttribute()); cdata(instruction.getBody(), true); @@ -262,27 +261,31 @@ public abstract class MetadataWriter extends XMLWriter implements XMLConstants { } } - private void writeLicenses(ILicense license) { - if (license != null) { + private void writeLicenses(Collection licenses) { + if (licenses != null && licenses.size() > 0) { // In the future there may be more than one license, so we write this // as a collection of one. // See bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=216911 start(LICENSES_ELEMENT); - attribute(COLLECTION_SIZE_ATTRIBUTE, 1); - start(LICENSE_ELEMENT); - if (license.getLocation() != null) { - attribute(URI_ATTRIBUTE, license.getLocation().toString()); + attribute(COLLECTION_SIZE_ATTRIBUTE, licenses.size()); + for (ILicense license : licenses) { + if (license == null) + continue; + start(LICENSE_ELEMENT); + if (license.getLocation() != null) { + attribute(URI_ATTRIBUTE, license.getLocation().toString()); - try { - // we write the URL attribute for backwards compatibility with 3.4.x - // this attribute should be removed if we make a breaking format change. - attribute(URL_ATTRIBUTE, URIUtil.toURL(license.getLocation()).toExternalForm()); - } catch (MalformedURLException e) { - attribute(URL_ATTRIBUTE, license.getLocation().toString()); + try { + // we write the URL attribute for backwards compatibility with 3.4.x + // this attribute should be removed if we make a breaking format change. + attribute(URL_ATTRIBUTE, URIUtil.toURL(license.getLocation()).toExternalForm()); + } catch (MalformedURLException e) { + attribute(URL_ATTRIBUTE, license.getLocation().toString()); + } } + cdata(license.getBody(), true); + end(LICENSE_ELEMENT); } - cdata(license.getBody(), true); - end(LICENSE_ELEMENT); end(LICENSES_ELEMENT); } } diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/io/XMLConstants.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/io/XMLConstants.java index 337470ed3..49c113f90 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/io/XMLConstants.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/p2/metadata/repository/io/XMLConstants.java @@ -10,16 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.repository.io; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; public interface XMLConstants extends org.eclipse.equinox.internal.p2.persistence.XMLConstants { // Constants defining the structure of the XML for metadata objects // A format version number for metadata XML. - public static final Version CURRENT_VERSION = new Version(0, 0, 1); - public static final VersionRange XML_TOLERANCE = new VersionRange(CURRENT_VERSION, true, new Version(2, 0, 0), false); + public static final Version CURRENT_VERSION = Version.createOSGi(0, 0, 1); + public static final VersionRange XML_TOLERANCE = new VersionRange(CURRENT_VERSION, true, Version.createOSGi(2, 0, 0), false); // Constants for processing Instructions public static final String PI_METADATA_TARGET = "metadata"; //$NON-NLS-1$ @@ -64,8 +64,6 @@ public interface XMLConstants extends org.eclipse.equinox.internal.p2.persistenc // Constants for sub-elements of a required capability element public static final String CAPABILITY_FILTER_ELEMENT = "filter"; //$NON-NLS-1$ - public static final String CAPABILITY_SELECTORS_ELEMENT = "selectors"; //$NON-NLS-1$ - public static final String CAPABILITY_SELECTOR_ELEMENT = "selector"; //$NON-NLS-1$ // Constants for attributes of a required capability element public static final String CAPABILITY_OPTIONAL_ATTRIBUTE = "optional"; //$NON-NLS-1$ diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/p2/metadata/repository/IMetadataRepository.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/p2/metadata/repository/IMetadataRepository.java deleted file mode 100644 index 34a057d69..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/p2/metadata/repository/IMetadataRepository.java +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.repository; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; - -import java.net.URI; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.AbstractMetadataRepository; - -/** - * A metadata repository stores information about a set of installable units - *

    - * This interface is not intended to be implemented by clients. Metadata repository - * implementations must subclass {@link AbstractMetadataRepository} rather than - * implementing this interface directly. - *

    - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface IMetadataRepository extends IRepository, IQueryable { - - /** - * Add the given installable units to this repository - * @param installableUnits the installable units to add - */ - public void addInstallableUnits(IInstallableUnit[] installableUnits); - - /** - * Adds a reference to another repository to this repository. When a repository - * is loaded by {@link IMetadataRepositoryManager}, its references - * are automatically added to the repository manager's set of known repositories. - *

    - * Note that this method does not add the contents of the given - * repository to this repository, but merely adds the location of another - * repository to the metadata of this repository. - *

    - * The {@link IRepository#ENABLED} option flag controls whether the - * referenced repository should be marked as enabled when added to the repository - * manager. If this flag is set, the repository will be marked as enabled when - * added to the repository manager. If this flag is missing, the repository will - * be marked as disabled. - * - * @param location the location of the repository to add - * @param nickname The nickname of the repository, or null - * @param type the repository type (currently either {@link IRepository#TYPE_METADATA} - * or {@link IRepository#TYPE_ARTIFACT}). - * @param options bit-wise or of option constants (currently either - * {@link IRepository#ENABLED} or {@link IRepository#NONE}). - * @see IMetadataRepositoryManager#setEnabled(URI, boolean) - */ - public void addReference(URI location, String nickname, int type, int options); - - /** - * Removes all installable units that match the given query from this repository. - * - * @param query the installable units to remove - * @param monitor a progress monitor, or null if progress - * reporting is not desired - * @return true if any units were actually removed, and - * false otherwise - */ - public boolean removeInstallableUnits(Query query, IProgressMonitor monitor); - - /** - * Remove all installable units from this repository. - */ - public void removeAll(); - -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/p2/metadata/repository/IMetadataRepositoryManager.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/p2/metadata/repository/IMetadataRepositoryManager.java deleted file mode 100644 index efe48c4ca..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/p2/metadata/repository/IMetadataRepositoryManager.java +++ /dev/null @@ -1,156 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.repository; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; - -import java.net.URI; -import java.util.Map; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; - -/** - * A metadata repository manager is used to create, access, and manipulate - * {@link IMetadataRepository} instances. See {@link IRepositoryManager} - * for a general description of the characteristics of repository managers. - * - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface IMetadataRepositoryManager extends IRepositoryManager, IQueryable { - /** - * The name used for obtaining a reference to the metadata repository manager service - */ - public static final String SERVICE_NAME = IMetadataRepositoryManager.class.getName(); - - /** - * Repository type for a simple repository based on a URL or local file system location. - */ - public static final String TYPE_SIMPLE_REPOSITORY = "org.eclipse.equinox.p2.metadata.repository.simpleRepository"; //$NON-NLS-1$ - public static final String TYPE_COMPOSITE_REPOSITORY = "org.eclipse.equinox.p2.metadata.repository.compositeRepository"; //$NON-NLS-1$ - - /** - * Creates and returns a new empty metadata repository of the given type at - * the given location. - *

    - * The resulting repository is added to the list of repositories tracked by - * the repository manager. Clients must make a subsequent call to {@link #removeRepository(URI)} - * if they do not want the repository manager to remember the repository for subsequent - * load attempts. - *

    - * - * @param location the absolute location for the new repository - * @param name the name of the new repository - * @param type the kind of repository to create - * @param properties the properties to set on the repository - * @return the newly created repository - * @throws ProvisionException if the repository could not be created. Reasons include: - *
      - *
    • The repository type is unknown.
    • - *
    • There was an error writing to the given repository location.
    • - *
    • A repository already exists at that location.
    • - *
    - */ - public IMetadataRepository createRepository(URI location, String name, String type, Map properties) throws ProvisionException; - - /** - * Loads a repository corresponding to the given URL. If a repository has - * previously been loaded at the given location, the same cached repository - * may be returned. - *

    - * The resulting repository is added to the list of repositories tracked by - * the repository manager. Clients must make a subsequent call to {@link #removeRepository(URI)} - * if they do not want the repository manager to remember the repository for subsequent - * load attempts. - *

    - * - * @param location The absolute location of the repository to load - * @param monitor a progress monitor, or null if progress - * reporting is not desired - * @return The loaded metadata repository - * @throws ProvisionException if the repository could not be created. Reasons include: - *
      - *
    • There is no existing repository at that location.
    • - *
    • The repository at that location could not be read.
    • - *
    - */ - public IMetadataRepository loadRepository(URI location, IProgressMonitor monitor) throws ProvisionException; - - /** - * Loads a repository corresponding to the given URL. If a repository has - * previously been loaded at the given location, the same cached repository - * may be returned. - *

    - * The resulting repository is added to the list of repositories tracked by - * the repository manager. Clients must make a subsequent call to {@link #removeRepository(URI)} - * if they do not want the repository manager to remember the repository for subsequent - * load attempts. - *

    - *

    - * The flags passed in should be taken as a hint for the type of repository to load. If - * the manager cannot load a repository that satisfies these hints, it can fail fast. - *

    - * @param location The absolute location of the repository to load - * @param flags - bit-wise or of flags to consider when loading the repository - * (currently only {@link IRepositoryManager#REPOSITORY_HINT_MODIFIABLE} is supported) - * @param monitor a progress monitor, or null if progress - * reporting is not desired - * @return The loaded metadata repository - * @throws ProvisionException if the repository could not be created. Reasons include: - *
      - *
    • There is no existing repository at that location.
    • - *
    • The repository at that location could not be read.
    • - *
    - * @see IRepositoryManager#REPOSITORY_HINT_MODIFIABLE - */ - public IMetadataRepository loadRepository(URI location, int flags, IProgressMonitor monitor) throws ProvisionException; - - /** - * Refreshes the repository corresponding to the given URL. This method discards - * any cached state held by the repository manager and reloads the repository - * contents. The provided repository location must already be known to the repository - * manager. - * - * @param location The absolute location of the repository to refresh - * @param monitor a progress monitor, or null if progress - * reporting is not desired - * @return The refreshed metadata repository - * @throws ProvisionException if the repository could not be refreshed. Reasons include: - *
      - *
    • The location is not known to the repository manager.
    • - *
    • There is no existing repository at that location.
    • - *
    • The repository at that location could not be read.
    • - *
    - */ - public IMetadataRepository refreshRepository(URI location, IProgressMonitor monitor) throws ProvisionException; - - /** - * Validates a given URL and returns a status indicating whether a valid repository is likely - * to be found at the given URL. Callers must assume that the validity of a - * repository location cannot be completely determined until an attempt to load - * the repository is made. - * - * @param location The absolute location of the repository to validate - * @param monitor a progress monitor, or null if progress - * reporting is not desired - * @return A status indicating whether a valid repository is likely located at the - * location. A status with severity OK indicates that the repository is - * likely to be loadable, or that as much validation as could be done was successful. - * Reasons for a non-OK status include: - *
      - *
    • The specified location is not a valid repository location.
    • - *
    • There is no existing repository at that location.
    • - *
    • The repository at that location could not be read.
    • - *
    - */ - public IStatus validateRepositoryLocation(URI location, IProgressMonitor monitor); -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/AbstractMetadataRepository.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/AbstractMetadataRepository.java deleted file mode 100644 index 4a2652cba..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/AbstractMetadataRepository.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository; - -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; - -import org.eclipse.equinox.internal.provisional.spi.p2.repository.AbstractRepository; - -import java.net.URI; -import java.util.Map; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; - -/** - * The common base class for all metadata repositories. - *

    - * Clients may subclass this class. - *

    - */ -public abstract class AbstractMetadataRepository extends AbstractRepository implements IMetadataRepository { - - //TODO Consider removing from abstract class, this is currently an implementation detail of the simple metadata repo parser - public static class RepositoryState { - public String Name; - public String Type; - public Version Version; - public String Provider; - public String Description; - public URI Location; - public Map Properties; - public IInstallableUnit[] Units; - public RepositoryReference[] Repositories; - } - - public AbstractMetadataRepository() { - super("noName", "noType", "noVersion", null, null, null, null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - - //TODO Consider removing from abstract class, this is currently an implementation detail of the simple metadata repo parser - public abstract void initialize(RepositoryState state); - - protected AbstractMetadataRepository(String name, String type, String version, URI location, String description, String provider, Map properties) { - super(name, type, version, location, description, provider, properties); - } - - public void addInstallableUnits(IInstallableUnit[] installableUnit) { - assertModifiable(); - } - - public void addReference(URI repositoryLocation, String nickname, int repositoryType, int options) { - assertModifiable(); - } - - public void removeAll() { - assertModifiable(); - } - - public boolean removeInstallableUnits(Query query, IProgressMonitor monitor) { - assertModifiable(); - return false; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/MetadataRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/MetadataRepositoryFactory.java deleted file mode 100644 index cfd2114d4..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/MetadataRepositoryFactory.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository; - -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; - -import java.net.URI; -import java.util.Map; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; - -/** - * A metadata repository factory is responsible for creating and loading instances - * of a particular type of metadata repository. Factories are provided via the - * org.eclipse.equinox.p2.metadata.repository.metadataRepositories extension point. - */ -public abstract class MetadataRepositoryFactory { - - /** - * Creates and returns a new empty metadata repository of the given type at - * the given location. - * - * @param location the location for the new repository - * @param name the name of the new repository - * @param type the kind of repository to create - * @param properties the properties to set on the repository - * @return the newly created repository - * @throws ProvisionException if the repository could not be created. Reasons include: - *

      - *
    • The repository type is not supported by this factory.
    • - *
    • There was an error writing to the given repository location.
    • - *
    - */ - public abstract IMetadataRepository create(URI location, String name, String type, Map properties) throws ProvisionException; - - /** - * Loads a repository corresponding to the given URL. - *

    - * The error code returned in the case of failure is significant. In particular an - * error code of {@link ProvisionException#REPOSITORY_FAILED_READ} indicates - * that the location definitely identifies a repository of this type, but an error occurred - * while loading the repository. The repository manager will not attempt to load - * a repository from that location using any other factory. An error code of - * {@link ProvisionException#REPOSITORY_NOT_FOUND} indicates there is no - * repository of this type at the given location, and the repository manager is free - * to try again with a different repository factory. - *

    - *

    - * The flags passed in should be taken as a hint for the type of repository to load. If - * the factory knows it will not load a repository that satisfies these hints, it can fail - * fast and return null.
    - * See {@link IRepositoryManager#REPOSITORY_HINT_MODIFIABLE} - *

    - * @param location The location of the repository to load - * @param flags to consider while loading the repository - * @param monitor a progress monitor, or null if progress - * reporting is not desired - * @return The loaded metadata repository - * @throws ProvisionException if the repository could not be created. Reasons include: - *
      - *
    • There is no existing repository at that location.
    • - *
    • The repository at that location could not be read.
    • - *
    - */ - public abstract IMetadataRepository load(URI location, int flags, IProgressMonitor monitor) throws ProvisionException; - - /** - * Validates a candidate repository URL and returns a status indicating the - * likelihood of a valid repository being located at the location. Implementors - * should make all attempts to validate the URL that can be made without - * actually loading the repository. The computation for this method must be - * significantly faster than loading the repository. Early detectable error - * conditions, such as the non-existence of the location, or an inability to read - * the location, should be determined in this method. - * - * @param location The location of the repository to validate - * @param monitor a progress monitor, or null if progress - * reporting is not desired - * @return A status indicating whether a valid repository is likely located at the - * location. A status with severity OK indicates that the repository is - * likely to be loadable, or that as much validation as could be done was successful. - * Reasons for a non-OK status include: - *
      - *
    • The specified location is not a valid repository location.
    • - *
    • There is no existing repository at that location.
    • - *
    • The repository at that location could not be read.
    • - *
    - */ - public abstract IStatus validate(URI location, IProgressMonitor monitor); -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/RepositoryReference.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/RepositoryReference.java deleted file mode 100644 index 9a7e2d842..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/RepositoryReference.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository; - -import java.net.URI; - -/** - * Serialization helper class for repository references. - */ -public class RepositoryReference { - public URI Location; - public int Type; - public int Options; - public String Nickname; - - public RepositoryReference(URI location, String nickname, int type, int options) { - this.Location = location; - this.Type = type; - this.Options = options; - this.Nickname = nickname; - } - - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - RepositoryReference other = (RepositoryReference) obj; - if (Location == null) { - if (other.Location != null) - return false; - } else if (!Location.equals(other.Location)) - return false; - if (Type != other.Type) - return false; - return true; - } - - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((Location == null) ? 0 : Location.hashCode()); - result = prime * result + Type; - return result; - } - -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/SimpleMetadataRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/SimpleMetadataRepositoryFactory.java deleted file mode 100644 index 012c44d1f..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/metadata/repository/SimpleMetadataRepositoryFactory.java +++ /dev/null @@ -1,161 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository; - -import java.io.*; -import java.net.URI; -import java.util.Map; -import java.util.jar.JarEntry; -import java.util.jar.JarInputStream; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.Tracing; -import org.eclipse.equinox.internal.p2.metadata.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.osgi.util.NLS; - -public class SimpleMetadataRepositoryFactory extends MetadataRepositoryFactory { - - private static final String JAR_EXTENSION = ".jar"; //$NON-NLS-1$ - private static final String XML_EXTENSION = ".xml"; //$NON-NLS-1$ - private static final String PROTOCOL_FILE = "file"; //$NON-NLS-1$ - - public IMetadataRepository create(URI location, String name, String type, Map properties) { - if (location.getScheme().equals("file")) //$NON-NLS-1$ - return new LocalMetadataRepository(location, name, properties); - return new URLMetadataRepository(location, name, properties); - } - - /** - * Returns a file in the local file system that contains the contents of the - * metadata repository at the given location. - */ - private File getLocalFile(URI location, IProgressMonitor monitor) throws IOException, ProvisionException { - File localFile = null; - URI jarLocation = URLMetadataRepository.getActualLocation(location, JAR_EXTENSION); - URI xmlLocation = URLMetadataRepository.getActualLocation(location, XML_EXTENSION); - // If the repository is local, we can return the repository file directly - if (PROTOCOL_FILE.equals(xmlLocation.getScheme())) { - //look for a compressed local file - localFile = URIUtil.toFile(jarLocation); - if (localFile.exists()) - return localFile; - //look for an uncompressed local file - localFile = URIUtil.toFile(xmlLocation); - if (localFile.exists()) - return localFile; - String msg = NLS.bind(Messages.io_failedRead, location); - throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, null)); - } - // file is not local, create a cache of the repository metadata - localFile = Activator.getCacheManager().createCache(location, URLMetadataRepository.CONTENT_FILENAME, monitor); - if (localFile == null) { - // there is no remote file in either form - this should not really happen as - // createCache should bail out with exception if something is wrong. This is an internal - // error. - throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, Messages.repoMan_internalError, null)); - } - return localFile; - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory#validate(java.net.URL, org.eclipse.core.runtime.IProgressMonitor) - */ - public IStatus validate(URI location, IProgressMonitor monitor) { - try { - validateAndLoad(location, false, 0, monitor); - } catch (ProvisionException e) { - return e.getStatus(); - } - return Status.OK_STATUS; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory#load(java.net.URL, org.eclipse.core.runtime.IProgressMonitor) - */ - public IMetadataRepository load(URI location, int flags, IProgressMonitor monitor) throws ProvisionException { - return validateAndLoad(location, true, flags, monitor); - } - - protected IMetadataRepository validateAndLoad(URI location, boolean doLoad, int flags, IProgressMonitor monitor) throws ProvisionException { - long time = 0; - final String debugMsg = "Validating and loading metadata repository "; //$NON-NLS-1$ - if (Tracing.DEBUG_METADATA_PARSING) { - Tracing.debug(debugMsg + location); - time = -System.currentTimeMillis(); - } - SubMonitor sub = SubMonitor.convert(monitor, 400); - try { - File localFile = getLocalFile(location, sub.newChild(300)); - InputStream inStream = new BufferedInputStream(new FileInputStream(localFile)); - JarInputStream jarStream = null; - try { - //if reading from a jar, obtain a stream on the entry with the actual contents - if (localFile.getAbsolutePath().endsWith(JAR_EXTENSION)) { - jarStream = new JarInputStream(inStream); - JarEntry jarEntry = jarStream.getNextJarEntry(); - String entryName = URLMetadataRepository.CONTENT_FILENAME + URLMetadataRepository.XML_EXTENSION; - while (jarEntry != null && (!entryName.equals(jarEntry.getName()))) { - jarEntry = jarStream.getNextJarEntry(); - } - //if there is a jar but the entry is missing or invalid, treat this as an invalid repository - if (jarEntry == null) - throw new IOException(NLS.bind(Messages.repoMan_invalidLocation, location)); - } - //parse the repository descriptor file - sub.setWorkRemaining(100); - if (doLoad) { - InputStream descriptorStream = jarStream != null ? jarStream : inStream; - IMetadataRepository result = new MetadataRepositoryIO().read(localFile.toURL(), descriptorStream, sub.newChild(100)); - if (result != null && (flags & IRepositoryManager.REPOSITORY_HINT_MODIFIABLE) > 0 && !result.isModifiable()) - return null; - if (result instanceof LocalMetadataRepository) - ((LocalMetadataRepository) result).initializeAfterLoad(location); - if (result instanceof URLMetadataRepository) - ((URLMetadataRepository) result).initializeAfterLoad(location); - if (Tracing.DEBUG_METADATA_PARSING) { - time += System.currentTimeMillis(); - Tracing.debug(debugMsg + "time (ms): " + time); //$NON-NLS-1$ - } - return result; - } - } finally { - safeClose(jarStream); - safeClose(inStream); - } - } catch (FileNotFoundException e) { - String msg = NLS.bind(Messages.io_failedRead, location); - throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, e)); - } catch (IOException e) { - String msg = NLS.bind(Messages.io_failedRead, location); - throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, msg, e)); - } finally { - if (monitor != null) - monitor.done(); - } - return null; - } - - /** - * Closes a stream, ignoring any secondary exceptions - */ - private void safeClose(InputStream stream) { - if (stream == null) - return; - try { - stream.close(); - } catch (IOException e) { - //ignore - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/AddChildTask.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/AddChildTask.java index a19d18a60..33b151088 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/AddChildTask.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/AddChildTask.java @@ -10,6 +10,8 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.repository.ant; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.net.URI; import java.net.URISyntaxException; import org.apache.tools.ant.BuildException; @@ -18,8 +20,7 @@ import org.eclipse.core.runtime.URIUtil; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.metadata.repository.Activator; import org.eclipse.equinox.internal.p2.metadata.repository.CompositeMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; /** * Ant task for adding a child repository to a composite metadata repository. @@ -34,7 +35,7 @@ public class AddChildTask extends Task { */ public void execute() { validate(); - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); if (manager == null) throw new BuildException("Unable to aquire metadata repository manager service."); diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/CreateCompositeMetadataRepositoryTask.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/CreateCompositeMetadataRepositoryTask.java index b6558259f..a1f80732a 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/CreateCompositeMetadataRepositoryTask.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/CreateCompositeMetadataRepositoryTask.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.repository.ant; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.ProvisionException; import java.net.URI; import java.net.URISyntaxException; @@ -22,9 +22,9 @@ import org.eclipse.core.runtime.URIUtil; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.metadata.repository.Activator; import org.eclipse.equinox.internal.p2.metadata.repository.CompositeMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; /** * Ant task for creating a new composite metadata repository. @@ -35,13 +35,13 @@ public class CreateCompositeMetadataRepositoryTask extends Task { String name = "Composite Metadata Repository"; boolean compressed = true; // compress by default boolean failOnExists = false; // should we fail if one already exists? - Map properties = new HashMap(); + Map properties = new HashMap(); /* (non-Javadoc) * @see org.apache.tools.ant.Task#execute() */ public void execute() { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); if (manager == null) throw new BuildException("Unable to aquire metadata repository manager service."); diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/MirrorApplicationTask.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/MirrorApplicationTask.java deleted file mode 100644 index 07ef39edf..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/MirrorApplicationTask.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.repository.ant; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Task; -import org.eclipse.equinox.app.IApplicationContext; -import org.eclipse.equinox.internal.p2.metadata.mirror.MirrorApplication; -import org.osgi.framework.Bundle; - -/** - * Ant task for running the metadata mirror application. - */ -public class MirrorApplicationTask extends Task { - - private static final String EMPTY_STRING = ""; //$NON-NLS-1$ - private static final String ARG_DESTINATION = "-destination"; //$NON-NLS-1$ - private static final String ARG_DESTINATION_NAME = "-destinationName"; //$NON-NLS-1$ - private static final String ARG_SOURCE = "-source"; //$NON-NLS-1$ - private static final String ARG_WRITE_MODE = "-writeMode"; //$NON-NLS-1$ - URL source; - URL destination; - String destinationName; - String writeMode; - - //TODO add transitive and roots attributed when implemented. - - /* - * Run the mirror application with the given arguments. - */ - private void runMirrorApplication(final String[] args) throws Exception { - new MirrorApplication().start(new IApplicationContext() { - - public void applicationRunning() { - // nothing to do - } - - public Map getArguments() { - Map arguments = new HashMap(); - arguments.put(IApplicationContext.APPLICATION_ARGS, args); - return arguments; - } - - public String getBrandingApplication() { - return null; - } - - public Bundle getBrandingBundle() { - return null; - } - - public String getBrandingDescription() { - return null; - } - - public String getBrandingId() { - return null; - } - - public String getBrandingName() { - return null; - } - - public String getBrandingProperty(String key) { - return null; - } - }); - } - - /* (non-Javadoc) - * @see org.apache.tools.ant.Task#execute() - */ - public void execute() { - // create arguments - String[] args = new String[] { // - ARG_SOURCE, source.toExternalForm(), // - ARG_DESTINATION, destination.toExternalForm(), // - ARG_WRITE_MODE, writeMode == null ? EMPTY_STRING : writeMode, // - destinationName == null ? EMPTY_STRING : ARG_DESTINATION_NAME, // - destinationName == null ? EMPTY_STRING : destinationName}; - - try { - runMirrorApplication(args); - } catch (Exception e) { - throw new BuildException("Error occurred while running metadata mirror application.", e); - } - } - - /* - * Set the source location. - */ - public void setSource(String value) throws MalformedURLException { - source = new URL(value); - } - - /* - * Set the destination location. - */ - public void setDestination(String value) throws MalformedURLException { - destination = new URL(value); - } - - /* - * Set the destination name. - */ - public void setDestinationName(String value) { - destinationName = value; - } - - /* - * Set the write mode for the application. (e.g. clean or append) - */ - public void setWriteMode(String value) { - writeMode = value; - } -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/RemoveChildTask.java b/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/RemoveChildTask.java index 3e12f4716..23421e3bc 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/RemoveChildTask.java +++ b/bundles/org.eclipse.equinox.p2.metadata.repository/src_ant/org/eclipse/equinox/internal/p2/metadata/repository/ant/RemoveChildTask.java @@ -10,6 +10,8 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.repository.ant; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.net.URI; import java.net.URISyntaxException; import org.apache.tools.ant.BuildException; @@ -18,8 +20,7 @@ import org.eclipse.core.runtime.URIUtil; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.metadata.repository.Activator; import org.eclipse.equinox.internal.p2.metadata.repository.CompositeMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; /** * Ant task to remove a specific child repository (or all the children repositories) @@ -35,7 +36,7 @@ public class RemoveChildTask extends Task { * @see org.apache.tools.ant.Task#execute() */ public void execute() { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); if (manager == null) throw new BuildException("Unable to aquire metadata repository manager service."); diff --git a/bundles/org.eclipse.equinox.p2.metadata/.classpath b/bundles/org.eclipse.equinox.p2.metadata/.classpath index 7cdeb7319..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/.classpath +++ b/bundles/org.eclipse.equinox.p2.metadata/.classpath @@ -1,7 +1,7 @@ - - + + diff --git a/bundles/org.eclipse.equinox.p2.metadata/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.metadata/.settings/org.eclipse.jdt.core.prefs index ed5b63b50..1ffc4aa80 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.metadata/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Mon Nov 05 17:01:21 EST 2007 +#Mon Dec 21 22:17:52 CET 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.builder.cleanOutputFolder=clean org.eclipse.jdt.core.builder.duplicateResourceTask=warning @@ -8,24 +8,24 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=warning @@ -74,7 +74,6 @@ org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unsafeTypeOperation=warning org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=enabled @@ -88,7 +87,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enab org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 @@ -160,7 +159,6 @@ org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert diff --git a/bundles/org.eclipse.equinox.p2.metadata/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.metadata/META-INF/MANIFEST.MF index 07e2c28c9..d3106ee44 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.metadata/META-INF/MANIFEST.MF @@ -4,7 +4,7 @@ Bundle-SymbolicName: org.eclipse.equinox.p2.metadata;singleton:=true Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-Localization: plugin -Bundle-Version: 1.0.100.qualifier +Bundle-Version: 2.0.0.qualifier Export-Package: org.eclipse.equinox.internal.p2.metadata; x-friends:="org.eclipse.equinox.p2.metadata.generator, org.eclipse.equinox.p2.metadata.repository, @@ -13,13 +13,17 @@ Export-Package: org.eclipse.equinox.internal.p2.metadata; org.eclipse.equinox.p2.artifact.optimizers, org.eclipse.equinox.p2.artifact.processors, org.eclipse.equinox.p2.ui, + org.eclipse.equinox.p2.operations, org.eclipse.equinox.p2.publisher, - org.eclipse.equinox.p2.director", - org.eclipse.equinox.internal.provisional.p2.metadata; + org.eclipse.equinox.p2.director, + org.eclipse.equinox.p2.director.app, + org.eclipse.equinox.p2.installer", + org.eclipse.equinox.internal.p2.metadata.expression;x-friends:="org.eclipse.equinox.p2.ql", + org.eclipse.equinox.internal.p2.metadata.expression.parser;x-friends:="org.eclipse.equinox.p2.ql", + org.eclipse.equinox.internal.p2.metadata.query; x-friends:="org.eclipse.equinox.p2.artifact.optimizers, org.eclipse.equinox.p2.artifact.processors, org.eclipse.equinox.p2.artifact.repository, - org.eclipse.equinox.p2.console, org.eclipse.equinox.p2.core, org.eclipse.equinox.p2.director, org.eclipse.equinox.p2.director.app, @@ -33,23 +37,29 @@ Export-Package: org.eclipse.equinox.internal.p2.metadata; org.eclipse.equinox.p2.metadata, org.eclipse.equinox.p2.metadata.generator, org.eclipse.equinox.p2.metadata.repository, - org.eclipse.equinox.p2.publisher, + org.eclipse.equinox.p2.operations, + org.eclipse.equinox.p2.ql, org.eclipse.equinox.p2.reconciler.dropins, org.eclipse.equinox.p2.touchpoint.eclipse, org.eclipse.equinox.p2.touchpoint.natives, org.eclipse.equinox.p2.ui, org.eclipse.equinox.p2.ui.admin, + org.eclipse.equinox.p2.ui.admin.rcp, org.eclipse.equinox.p2.ui.sdk, org.eclipse.equinox.p2.ui.sdk.scheduler, org.eclipse.equinox.p2.updatechecker, org.eclipse.equinox.p2.updatesite, + org.eclipse.equinox.p2.console, + org.eclipse.equinox.p2.publisher, org.eclipse.pde.ui, org.eclipse.equinox.p2.repository.tools, org.eclipse.pde.core", - org.eclipse.equinox.internal.provisional.p2.metadata.query; + org.eclipse.equinox.internal.p2.query;x-friends:="org.eclipse.equinox.p2.ql,org.eclipse.equinox.p2.ui", + org.eclipse.equinox.internal.provisional.p2.metadata; x-friends:="org.eclipse.equinox.p2.artifact.optimizers, org.eclipse.equinox.p2.artifact.processors, org.eclipse.equinox.p2.artifact.repository, + org.eclipse.equinox.p2.console, org.eclipse.equinox.p2.core, org.eclipse.equinox.p2.director, org.eclipse.equinox.p2.director.app, @@ -63,28 +73,33 @@ Export-Package: org.eclipse.equinox.internal.p2.metadata; org.eclipse.equinox.p2.metadata, org.eclipse.equinox.p2.metadata.generator, org.eclipse.equinox.p2.metadata.repository, + org.eclipse.equinox.p2.operations, + org.eclipse.equinox.p2.publisher, + org.eclipse.equinox.p2.ql, org.eclipse.equinox.p2.reconciler.dropins, org.eclipse.equinox.p2.touchpoint.eclipse, org.eclipse.equinox.p2.touchpoint.natives, org.eclipse.equinox.p2.ui, org.eclipse.equinox.p2.ui.admin, - org.eclipse.equinox.p2.ui.admin.rcp, org.eclipse.equinox.p2.ui.sdk, org.eclipse.equinox.p2.ui.sdk.scheduler, org.eclipse.equinox.p2.updatechecker, org.eclipse.equinox.p2.updatesite, - org.eclipse.equinox.p2.console, - org.eclipse.equinox.p2.publisher, org.eclipse.pde.ui, org.eclipse.equinox.p2.repository.tools, - org.eclipse.pde.core" + org.eclipse.pde.core", + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.expression, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.query Import-Package: org.eclipse.osgi.service.localization;version="1.0.0", org.eclipse.osgi.util, org.osgi.framework;version="1.3.0" Bundle-Activator: org.eclipse.equinox.internal.p2.metadata.MetadataActivator Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, - J2SE-1.4 +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 Require-Bundle: org.eclipse.equinox.common, org.eclipse.equinox.p2.core, org.eclipse.osgi;bundle-version="3.5.0" diff --git a/bundles/org.eclipse.equinox.p2.metadata/build.properties b/bundles/org.eclipse.equinox.p2.metadata/build.properties index a6b8330d2..246ea6cb7 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/build.properties +++ b/bundles/org.eclipse.equinox.p2.metadata/build.properties @@ -15,3 +15,5 @@ bin.includes = META-INF/,\ about.html,\ plugin.properties src.includes = about.html +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ArtifactKey.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ArtifactKey.java index f495ee2a7..709fa2b1c 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ArtifactKey.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ArtifactKey.java @@ -10,11 +10,12 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata; +import org.eclipse.equinox.p2.metadata.Version; + import java.util.ArrayList; import java.util.StringTokenizer; import org.eclipse.core.runtime.Assert; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.IArtifactKey; /** * The concrete type for representing IArtifactKey's. @@ -31,7 +32,7 @@ public class ArtifactKey implements IArtifactKey { private static String[] getArrayFromList(String stringList, String separator) { if (stringList == null || stringList.trim().length() == 0) return new String[0]; - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList(); boolean separatorSeen = true; StringTokenizer tokens = new StringTokenizer(stringList, separator, true); while (tokens.hasMoreTokens()) { @@ -48,7 +49,7 @@ public class ArtifactKey implements IArtifactKey { } if (separatorSeen) list.add(""); //$NON-NLS-1$ - return (String[]) list.toArray(new String[list.size()]); + return list.toArray(new String[list.size()]); } public static IArtifactKey parse(String specification) { @@ -79,6 +80,12 @@ public class ArtifactKey implements IArtifactKey { this.version = version; } + public ArtifactKey(IArtifactKey artifactKey) { + this.classifier = artifactKey.getClassifier(); + this.id = artifactKey.getId(); + this.version = artifactKey.getVersion(); + } + public String getClassifier() { return classifier; } diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/BasicVersion.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/BasicVersion.java new file mode 100644 index 000000000..0514284f0 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/BasicVersion.java @@ -0,0 +1,83 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata; + +import org.eclipse.equinox.p2.metadata.Version; + +/** + * The abstract BasicVersion class adds the methods necessary to to compare and serialize + * versions in version ranges. The class is not intended as public API. + */ +public abstract class BasicVersion extends Version { + private static final long serialVersionUID = -2983093417537485027L; + + /** + * Returns the OSGi major component of this version identifier. + * + * @return The major component. + * @throws UnsupportedOperationException if the first element in the + * vector is not a number. + * @see #isOSGiCompatible() + */ + public abstract int getMajor(); + + /** + * Returns the OSGi micro component of this version identifier. + * + * @return The micro component. + * @throws UnsupportedOperationException if the third element in the + * vector is not a number. + * @see #isOSGiCompatible() + */ + public abstract int getMicro(); + + /** + * Returns the OSGi minor component of this version identifier. + * + * @return The minor component. + * @throws UnsupportedOperationException if the second element in the + * vector is not a number. + * @see #isOSGiCompatible() + */ + public abstract int getMinor(); + + /** + * Returns the OSGi qualifier component of this version identifier. + * + * @return The qualifier component or null if not set. + * @throws UnsupportedOperationException if the fourth element in the + * vector is set to something other then a string. + * @see #isOSGiCompatible() + */ + public abstract String getQualifier(); + + /** + * Appends the original for this version onto the sb StringBuffer + * if present. + * @param sb The buffer that will receive the raw string format + * @param rangeSafe Set to true if range delimiters should be escaped + */ + public abstract void originalToString(StringBuffer sb, boolean rangeSafe); + + /** + * Appends the raw format for this version onto the sb StringBuffer. + * @param sb The buffer that will receive the raw string format + * @param rangeSafe Set to true if range delimiters should be escaped + */ + public abstract void rawToString(StringBuffer sb, boolean rangeSafe); + + /** + * This method is package protected since it violates the immutable + * contract. + * @return The raw vector. Must be treated as read-only + */ + abstract Comparable[] getVector(); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/Copyright.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/Copyright.java index 9098f377c..b56578830 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/Copyright.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/Copyright.java @@ -11,7 +11,7 @@ package org.eclipse.equinox.internal.p2.metadata; import java.net.URI; -import org.eclipse.equinox.internal.provisional.p2.metadata.ICopyright; +import org.eclipse.equinox.p2.metadata.ICopyright; /** * The Copyright class represents a software copyright. A copyright has diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/IRequiredCapability.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/IRequiredCapability.java new file mode 100644 index 000000000..ef92ee045 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/IRequiredCapability.java @@ -0,0 +1,45 @@ +/******************************************************************************* +* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata; + +import org.eclipse.equinox.p2.metadata.*; + +/** + * A required capability represents some external constraint on an {@link IInstallableUnit}. + * Each capability represents something an {@link IInstallableUnit} needs that + * it expects to be provided by another {@link IInstallableUnit}. Capabilities are + * entirely generic, and are intended to be capable of representing anything that + * an {@link IInstallableUnit} may need either at install time, or at runtime. + *

    + * Capabilities are segmented into namespaces. Anyone can introduce new + * capability namespaces. Some well-known namespaces are introduced directly + * by the provisioning framework. + * + * @see IInstallableUnit#NAMESPACE_IU_ID + * + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + */ +public interface IRequiredCapability extends IRequirement { + + // public String getFilter(); + + public String getName(); + + public String getNamespace(); + + /** + * Returns the range of versions that satisfy this required capability. Returns + * an empty version range ({@link VersionRange#emptyRange} if any version + * will satisfy the capability. + * @return the range of versions that satisfy this required capability. + */ + public VersionRange getRange(); +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/InstallableUnit.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/InstallableUnit.java index b5dd1ac29..018f26cb6 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/InstallableUnit.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/InstallableUnit.java @@ -11,40 +11,45 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata; -import java.util.ArrayList; -import java.util.Map; +import org.eclipse.equinox.p2.metadata.Version; + +import java.util.*; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil; +import org.osgi.framework.Filter; public class InstallableUnit implements IInstallableUnit { private static final OrderedProperties NO_PROPERTIES = new OrderedProperties(); private static final IProvidedCapability[] NO_PROVIDES = new IProvidedCapability[0]; - private static final IRequiredCapability[] NO_REQUIRES = new IRequiredCapability[0]; + private static final IRequirement[] NO_REQUIRES = new IRequirement[0]; private static final IArtifactKey[] NO_ARTIFACTS = new IArtifactKey[0]; private static final ITouchpointData[] NO_TOUCHPOINT_DATA = new ITouchpointData[0]; + private static final ILicense[] NO_LICENSE = new ILicense[0]; private IArtifactKey[] artifacts = NO_ARTIFACTS; - private String filter; + private Filter filter; private String id; private OrderedProperties properties; private OrderedProperties localizedProperties; IProvidedCapability[] providedCapabilities = NO_PROVIDES; - private IRequiredCapability[] requires = NO_REQUIRES; - private IRequiredCapability[] metaRequires = NO_REQUIRES; + private IRequirement[] requires = NO_REQUIRES; + private IRequirement[] metaRequires = NO_REQUIRES; private boolean singleton; - private ArrayList touchpointData = null; + private ITouchpointData[] touchpointData = NO_TOUCHPOINT_DATA; private ITouchpointType touchpointType; - private Version version; + private Version version = Version.emptyVersion; private IUpdateDescriptor updateInfo; - private ILicense license; + private ILicense[] licenses = NO_LICENSE; private ICopyright copyright; public InstallableUnit() { @@ -52,26 +57,22 @@ public class InstallableUnit implements IInstallableUnit { } public void addTouchpointData(ITouchpointData newData) { - ensureTouchpointDataCapacity(1); - touchpointData.add(newData); - } - - public int compareTo(Object toCompareTo) { - if (!(toCompareTo instanceof IInstallableUnit)) { - return -1; + int tl = touchpointData.length; + if (tl == 0) + touchpointData = new ITouchpointData[] {newData}; + else { + ITouchpointData[] newDatas = new ITouchpointData[tl + 1]; + System.arraycopy(touchpointData, 0, newDatas, 0, tl); + newDatas[tl] = newData; + touchpointData = newDatas; } - IInstallableUnit other = (IInstallableUnit) toCompareTo; - if (getId().compareTo(other.getId()) == 0) - return (getVersion().compareTo(other.getVersion())); - return getId().compareTo(other.getId()); } - private void ensureTouchpointDataCapacity(int size) { - if (touchpointData != null) { - touchpointData.ensureCapacity(size); - } else { - touchpointData = new ArrayList(size); - } + public int compareTo(IInstallableUnit other) { + int cmp = getId().compareTo(other.getId()); + if (cmp == 0) + cmp = getVersion().compareTo(other.getVersion()); + return cmp; } public boolean equals(Object obj) { @@ -95,16 +96,16 @@ public class InstallableUnit implements IInstallableUnit { return true; } - public IArtifactKey[] getArtifacts() { - return artifacts; + public Collection getArtifacts() { + return CollectionUtils.unmodifiableList(artifacts); } - public String getFilter() { + public Filter getFilter() { return filter; } - public IInstallableUnitFragment[] getFragments() { - return null; + public List getFragments() { + return CollectionUtils.emptyList(); } public String getId() { @@ -117,7 +118,7 @@ public class InstallableUnit implements IInstallableUnit { * * @return an unmodifiable copy of the IU properties. */ - public Map getProperties() { + public Map getProperties() { return OrderedProperties.unmodifiableProperties(properties()); } @@ -135,18 +136,21 @@ public class InstallableUnit implements IInstallableUnit { return properties().getProperty(key); } - public IProvidedCapability[] getProvidedCapabilities() { - return providedCapabilities; + public Collection getProvidedCapabilities() { + return CollectionUtils.unmodifiableList(providedCapabilities); } - public IRequiredCapability[] getRequiredCapabilities() { - return requires; + public String getProperty(String key, String locale) { + return TranslationSupport.getInstance().getIUProperty(this, key, locale); + } + + public List getRequiredCapabilities() { + return CollectionUtils.unmodifiableList(requires); } - public ITouchpointData[] getTouchpointData() { - return (touchpointData == null ? NO_TOUCHPOINT_DATA // - : (ITouchpointData[]) touchpointData.toArray(new ITouchpointData[touchpointData.size()])); + public List getTouchpointData() { + return CollectionUtils.unmodifiableList(touchpointData); } public ITouchpointType getTouchpointType() { @@ -165,10 +169,6 @@ public class InstallableUnit implements IInstallableUnit { return result; } - public boolean isFragment() { - return false; - } - public boolean isResolved() { return false; } @@ -195,10 +195,14 @@ public class InstallableUnit implements IInstallableUnit { providedCapabilities = newCapabilities; } - public void setFilter(String filter) { + public void setFilter(Filter filter) { this.filter = filter; } + public void setFilter(String filter) { + setFilter(filter == null ? null : ExpressionUtil.parseLDAP(filter)); + } + public void setId(String id) { this.id = id; } @@ -209,7 +213,7 @@ public class InstallableUnit implements IInstallableUnit { public String setLocalizedProperty(String key, String value) { if (localizedProperties == null) localizedProperties = new OrderedProperties(); - return (String) localizedProperties.put(key, value); + return localizedProperties.put(key, value); } public String setProperty(String key, String value) { @@ -220,12 +224,12 @@ public class InstallableUnit implements IInstallableUnit { return (String) properties.setProperty(key, value); } - public void setRequiredCapabilities(IRequiredCapability[] capabilities) { + public void setRequiredCapabilities(IRequirement[] capabilities) { if (capabilities.length == 0) { this.requires = NO_REQUIRES; } else { //copy array for safety - this.requires = (IRequiredCapability[]) capabilities.clone(); + this.requires = capabilities.clone(); } } @@ -257,12 +261,16 @@ public class InstallableUnit implements IInstallableUnit { this.updateInfo = updateInfo; } - public void setLicense(ILicense license) { - this.license = license; + public void setLicenses(ILicense[] license) { + this.licenses = license == null ? NO_LICENSE : license; } - public ILicense getLicense() { - return license; + public Collection getLicenses() { + return CollectionUtils.unmodifiableList(licenses); + } + + public ILicense[] getLicenses(String locale) { + return TranslationSupport.getInstance().getLicenses(this, locale); } public void setCopyright(ICopyright copyright) { @@ -273,24 +281,24 @@ public class InstallableUnit implements IInstallableUnit { return copyright; } - public boolean satisfies(IRequiredCapability candidate) { - IProvidedCapability[] provides = getProvidedCapabilities(); - for (int i = 0; i < provides.length; i++) - if (provides[i].satisfies(candidate)) - return true; - return false; + public ICopyright getCopyright(String locale) { + return TranslationSupport.getInstance().getCopyright(this, locale); + } + + public boolean satisfies(IRequirement candidate) { + return candidate.isMatch(this); } - public IRequiredCapability[] getMetaRequiredCapabilities() { - return metaRequires; + public Collection getMetaRequiredCapabilities() { + return CollectionUtils.unmodifiableList(metaRequires); } - public void setMetaRequiredCapabilities(IRequiredCapability[] metaReqs) { + public void setMetaRequiredCapabilities(IRequirement[] metaReqs) { if (metaReqs.length == 0) { this.metaRequires = NO_REQUIRES; } else { //copy array for safety - this.metaRequires = (IRequiredCapability[]) metaReqs.clone(); + this.metaRequires = metaReqs.clone(); } } } diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/InstallableUnitFragment.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/InstallableUnitFragment.java index 7709c9dbc..86ea33ad2 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/InstallableUnitFragment.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/InstallableUnitFragment.java @@ -10,37 +10,36 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnitFragment; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; +import java.util.List; +import org.eclipse.equinox.p2.metadata.IInstallableUnitFragment; +import org.eclipse.equinox.p2.metadata.IRequirement; public class InstallableUnitFragment extends InstallableUnit implements IInstallableUnitFragment { - private IRequiredCapability[] hostRequirements; + private IRequirement[] hostRequirements; public InstallableUnitFragment() { super(); } - public void setHost(IRequiredCapability[] hostRequirements) { + public void setHost(IRequirement[] hostRequirements) { if (hostRequirements == null) return; this.hostRequirements = hostRequirements; addRequiredCapability(hostRequirements); } - private void addRequiredCapability(IRequiredCapability[] toAdd) { - IRequiredCapability[] current = super.getRequiredCapabilities(); - IRequiredCapability[] result = new IRequiredCapability[current.length + toAdd.length]; - System.arraycopy(current, 0, result, 0, current.length); - System.arraycopy(toAdd, 0, result, current.length, toAdd.length); + private void addRequiredCapability(IRequirement[] toAdd) { + List current = super.getRequiredCapabilities(); + int currSize = current.size(); + IRequirement[] result = new IRequirement[currSize + toAdd.length]; + for (int i = 0; i < currSize; ++i) + result[i] = current.get(i); + System.arraycopy(toAdd, 0, result, current.size(), toAdd.length); setRequiredCapabilities(result); } - public boolean isFragment() { - return true; - } - - public IRequiredCapability[] getHost() { + public IRequirement[] getHost() { return hostRequirements; } } diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/InstallableUnitPatch.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/InstallableUnitPatch.java index 31013548b..41ce8f56a 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/InstallableUnitPatch.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/InstallableUnitPatch.java @@ -8,42 +8,46 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import java.util.List; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; +import org.eclipse.equinox.p2.metadata.*; public class InstallableUnitPatch extends InstallableUnit implements IInstallableUnitPatch { private IRequirementChange[] changes; - private IRequiredCapability lifeCycle; - private IRequiredCapability[][] scope; - - private void addRequiredCapability(IRequiredCapability[] toAdd) { - IRequiredCapability[] current = super.getRequiredCapabilities(); - IRequiredCapability[] result = new IRequiredCapability[current.length + toAdd.length]; - System.arraycopy(current, 0, result, 0, current.length); - System.arraycopy(toAdd, 0, result, current.length, toAdd.length); + private IRequirement lifeCycle; + private IRequirement[][] scope; + + private void addRequiredCapability(IRequirement[] toAdd) { + List current = super.getRequiredCapabilities(); + int currSize = current.size(); + IRequirement[] result = new IRequirement[currSize + toAdd.length]; + for (int i = 0; i < currSize; ++i) + result[i] = current.get(i); + System.arraycopy(toAdd, 0, result, current.size(), toAdd.length); setRequiredCapabilities(result); } - public IRequiredCapability[][] getApplicabilityScope() { + public IRequirement[][] getApplicabilityScope() { return scope; } - public IRequiredCapability getLifeCycle() { + public IRequirement getLifeCycle() { return lifeCycle; } - public IRequirementChange[] getRequirementsChange() { - return changes; + public List getRequirementsChange() { + return CollectionUtils.unmodifiableList(changes); } - public void setApplicabilityScope(IRequiredCapability[][] applyTo) { + public void setApplicabilityScope(IRequirement[][] applyTo) { scope = applyTo; } - public void setLifeCycle(IRequiredCapability lifeCycle) { + public void setLifeCycle(IRequirement lifeCycle) { if (lifeCycle == null) return; this.lifeCycle = lifeCycle; - addRequiredCapability(new IRequiredCapability[] {lifeCycle}); + addRequiredCapability(new IRequirement[] {lifeCycle}); } public void setRequirementsChange(IRequirementChange[] changes) { diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/License.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/License.java index 112956f26..38c62c1b1 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/License.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/License.java @@ -16,7 +16,7 @@ import java.math.BigInteger; import java.net.URI; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import org.eclipse.equinox.internal.provisional.p2.metadata.ILicense; +import org.eclipse.equinox.p2.metadata.ILicense; /** * The License class represents a software license. A license has required body text @@ -38,7 +38,7 @@ public class License implements ILicense { /** * The digest is the cached message digest of the normalized body */ - private BigInteger digest; + private String digest; /** * Creates a new license object which is identified by users using the body field. @@ -49,11 +49,12 @@ public class License implements ILicense { * @param body the license body, cannot be null * @throws IllegalArgumentException when the body is null */ - public License(URI location, String body) { + public License(URI location, String body, String uuid) { if (body == null) throw new IllegalArgumentException("body cannot be null"); //$NON-NLS-1$ this.body = body; this.location = location; + this.digest = uuid; } /** @@ -78,9 +79,10 @@ public class License implements ILicense { * version of the license where all whitespace has been reduced to one space. * @return the message digest as a BigInteger, never null */ - public synchronized BigInteger getDigest() { + public synchronized String getUUID() { if (digest == null) - digest = calculateLicenseDigest(); + digest = calculateLicenseDigest().toString(16); + return digest; } @@ -94,7 +96,7 @@ public class License implements ILicense { return false; if (obj instanceof ILicense) { ILicense other = (ILicense) obj; - if (other.getDigest().equals(getDigest())) + if (other.getUUID().equals(getUUID())) return true; } return false; @@ -104,7 +106,7 @@ public class License implements ILicense { * @see java.lang.Object#hashCode() */ public int hashCode() { - return getDigest().hashCode(); + return getUUID().hashCode(); } private BigInteger calculateLicenseDigest() { diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/Messages.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/Messages.java index 10a596c32..0466d2676 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/Messages.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/Messages.java @@ -16,9 +16,6 @@ import org.eclipse.osgi.util.NLS; * TODO Shouldn't be a public class in an API package. */ public class Messages extends NLS { - public static String _0_is_not_a_positive_integer_in_osgi_1; - - public static String _0_is_not_a_string_in_osgi_1; public static String _0_is_not_a_valid_qualifier_in_osgi_1; @@ -54,6 +51,22 @@ public class Messages extends NLS { public static String expected_slash_after_raw_vector_0; + public static String filter_trailing_characters; + + public static String filter_missing_leftparen; + + public static String filter_missing_rightparen; + + public static String filter_invalid_operator; + + public static String filter_missing_attr; + + public static String filter_invalid_value; + + public static String filter_missing_value; + + public static String filter_premature_end; + public static String format_0_unable_to_parse_1; public static String format_0_unable_to_parse_empty_version; @@ -68,8 +81,6 @@ public class Messages extends NLS { public static String illegal_character_encountered_ascii_0; - public static String illegal_number_of_entries_0_in_osgi_1; - public static String missing_comma_in_range_0; public static String negative_character_range; @@ -80,14 +91,14 @@ public class Messages extends NLS { public static String only_format_specified_0; + public static String only_max_and_empty_string_defaults_can_have_translations; + public static String original_must_start_with_colon_0; public static String original_stated_but_missing_0; public static String pad_defined_more_then_once; - public static String pad_not_allowed_in_osgi_0; - public static String performing_subquery; public static String premature_end_of_format; diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/NotRequirement.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/NotRequirement.java deleted file mode 100644 index 752d5444e..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/NotRequirement.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.eclipse.equinox.internal.p2.metadata; - -import org.eclipse.equinox.internal.provisional.p2.metadata.*; - -public class NotRequirement implements IRequiredCapability { - private IRequiredCapability negatedRequirement; - - public NotRequirement(IRequiredCapability iRequiredCapabilities) { - negatedRequirement = iRequiredCapabilities; - } - - public IRequiredCapability getRequirement() { - return negatedRequirement; - } - - public String getFilter() { - return negatedRequirement.getFilter(); - } - - public String getName() { - return negatedRequirement.getName(); - } - - public String getNamespace() { - return negatedRequirement.getNamespace(); - } - - public VersionRange getRange() { - return negatedRequirement.getRange(); - } - - public String[] getSelectors() { - return negatedRequirement.getSelectors(); - } - - public boolean isGreedy() { - return negatedRequirement.isGreedy(); - } - - public boolean isMultiple() { - return negatedRequirement.isMultiple(); - } - - public boolean isOptional() { - return negatedRequirement.isOptional(); - } - - public void setFilter(String filter) { - // TODO Auto-generated method stub - - } - - public void setSelectors(String[] selectors) { - // TODO Auto-generated method stub - - } - - public boolean isNegation() { - return true; - } - - public String toString() { - return "NOT(" + negatedRequirement.toString() + ')'; //$NON-NLS-1$ - } - - public boolean satisfiedBy(IProvidedCapability cap) { - return !negatedRequirement.satisfiedBy(cap); - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ORRequirement.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ORRequirement.java deleted file mode 100644 index 3aab2c9ff..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ORRequirement.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.eclipse.equinox.internal.p2.metadata; - -import org.eclipse.equinox.internal.provisional.p2.metadata.*; - -public class ORRequirement implements IRequiredCapability { - private IRequiredCapability[] oredRequirements; - - public ORRequirement(IRequiredCapability[] reqs) { - oredRequirements = reqs; - } - - public IRequiredCapability[] getRequirements() { - return oredRequirements; - } - - public String getFilter() { - // TODO Auto-generated method stub - return null; - } - - public String getName() { - // TODO Auto-generated method stub - return null; - } - - public String getNamespace() { - // TODO Auto-generated method stub - return null; - } - - public VersionRange getRange() { - // TODO Auto-generated method stub - return null; - } - - public String[] getSelectors() { - // TODO Auto-generated method stub - return null; - } - - public boolean isGreedy() { - // TODO Auto-generated method stub - return true; - } - - public boolean isMultiple() { - // TODO Auto-generated method stub - return false; - } - - public boolean isOptional() { - return false; - } - - public void setFilter(String filter) { - // TODO Auto-generated method stub - - } - - public void setSelectors(String[] selectors) { - // TODO Auto-generated method stub - - } - - public boolean isNegation() { - return false; - } - - public String toString() { - String result = "OR("; - for (int i = 0; i < oredRequirements.length; i++) { - result += oredRequirements[i].toString(); - } - return result + ")"; - } - - public boolean satisfiedBy(IProvidedCapability cap) { - for (int i = 0; i < oredRequirements.length; i++) { - boolean result = oredRequirements[i].satisfiedBy(cap); - if (result) - return true; - } - return false; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/OSGiVersion.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/OSGiVersion.java new file mode 100644 index 000000000..979494d49 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/OSGiVersion.java @@ -0,0 +1,213 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata; + +import org.eclipse.equinox.p2.metadata.IVersionFormat; +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.osgi.util.NLS; + +/** + * @Immutable + * @noextend This class is not intended to be subclassed by clients. + */ +public class OSGiVersion extends BasicVersion { + + private static final long serialVersionUID = -4530178927569560877L; + + private static final boolean[] allowedOSGiChars; + + private final int major; + + private final int minor; + + private final int micro; + + private final Comparable qualifier; + + static { + allowedOSGiChars = new boolean[128]; + for (int c = '0'; c <= '9'; ++c) + allowedOSGiChars[c] = true; + for (int c = 'A'; c <= 'Z'; ++c) + allowedOSGiChars[c] = true; + for (int c = 'a'; c <= 'z'; ++c) + allowedOSGiChars[c] = true; + allowedOSGiChars['_'] = true; + allowedOSGiChars['-'] = true; + } + + public static boolean isValidOSGiQualifier(Comparable e) { + if (e == VersionVector.MAXS_VALUE) + return true; + + if (!(e instanceof String)) + return false; + + String s = (String) e; + int idx = s.length(); + boolean[] allowed = allowedOSGiChars; + while (--idx >= 0) { + int c = s.charAt(idx); + if (c < '-' || c > 'z' || !allowed[c]) + return false; + } + return true; + } + + static BasicVersion fromVector(Comparable[] vector, Comparable pad) { + if (vector.length != 4) { + if (vector.length == 0) { + if (pad == null) + return (BasicVersion) emptyVersion; + if (pad == VersionVector.MAX_VALUE) + return (BasicVersion) MAX_VERSION; + } + throw new IllegalArgumentException(); + } + int major = ((Integer) vector[0]).intValue(); + int minor = ((Integer) vector[1]).intValue(); + int micro = ((Integer) vector[2]).intValue(); + Comparable qualifier = vector[3]; + return (major == 0 && minor == 0 && micro == 0 && qualifier == VersionVector.MINS_VALUE) ? (BasicVersion) emptyVersion : new OSGiVersion(major, minor, micro, qualifier); + } + + public OSGiVersion(int major, int minor, int micro, Comparable qualifier) { + this.major = major; + this.minor = minor; + this.micro = micro; + if (!isValidOSGiQualifier(qualifier)) + throw new IllegalArgumentException(NLS.bind(Messages._0_is_not_a_valid_qualifier_in_osgi_1, "qualifier", this)); //$NON-NLS-1$ + this.qualifier = qualifier; + } + + public int compareTo(Version v) { + int result; + if (!(v instanceof OSGiVersion)) { + BasicVersion ov = (BasicVersion) v; + result = VersionVector.compare(getVector(), null, ov.getVector(), ov.getPad()); + } else { + OSGiVersion ov = (OSGiVersion) v; + result = major - ov.major; + if (result == 0) { + result = minor - ov.minor; + if (result == 0) { + result = micro - ov.micro; + if (result == 0) + result = VersionVector.compareSegments(qualifier, ov.qualifier); + } + } + } + return result; + } + + public boolean equals(Object object) { + if (object == this) + return true; + + if (!(object instanceof OSGiVersion)) { + if (object instanceof BasicVersion) { + BasicVersion ov = (BasicVersion) object; + return VersionVector.equals(getVector(), null, ov.getVector(), ov.getPad()); + } + return false; + } + + OSGiVersion other = (OSGiVersion) object; + return micro == other.micro && minor == other.minor && major == other.major && qualifier.equals(other.qualifier); + } + + public IVersionFormat getFormat() { + return VersionFormat.OSGI_FORMAT; + } + + public int getMajor() { + return major; + } + + public int getMicro() { + return micro; + } + + public int getMinor() { + return minor; + } + + public String getOriginal() { + return toString(); + } + + public String getQualifier() { + return qualifier == VersionVector.MAXS_VALUE ? IVersionFormat.DEFAULT_MAX_STRING_TRANSLATION : (String) qualifier; + } + + public int hashCode() { + return (major << 24) + (minor << 16) + (micro << 8) + qualifier.hashCode(); + } + + public boolean isOSGiCompatible() { + return true; + } + + public void originalToString(StringBuffer sb, boolean rangeSafe) { + toString(sb); + } + + public void rawToString(StringBuffer sb, boolean rangeSafe) { + sb.append(major); + sb.append('.'); + sb.append(minor); + sb.append('.'); + sb.append(micro); + sb.append('.'); + sb.append('\''); + sb.append(qualifier); + sb.append('\''); + } + + public void toString(StringBuffer sb) { + sb.append(major); + sb.append('.'); + sb.append(minor); + sb.append('.'); + sb.append(micro); + if (qualifier != VersionVector.MINS_VALUE) { + sb.append('.'); + sb.append(getQualifier()); + } + } + + public Comparable[] getVector() { + return new Comparable[] {VersionParser.valueOf(major), VersionParser.valueOf(minor), VersionParser.valueOf(micro), qualifier}; + } + + public Comparable getPad() { + return null; + } + + public Comparable getSegment(int index) { + switch (index) { + case 0 : + return VersionParser.valueOf(major); + case 1 : + return VersionParser.valueOf(minor); + case 2 : + return VersionParser.valueOf(micro); + case 3 : + return qualifier; + } + throw new ArrayIndexOutOfBoundsException(index); // Not in the imaginary vector array + } + + public int getSegmentCount() { + return 4; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/OmniVersion.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/OmniVersion.java new file mode 100644 index 000000000..c45171038 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/OmniVersion.java @@ -0,0 +1,247 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata; + +import org.eclipse.equinox.p2.metadata.IVersionFormat; +import org.eclipse.equinox.p2.metadata.Version; + +/** + *

    The Generic Omni Version is composed of a vector of Comparable objects and a pad value. The pad + * might be null. The vector can contain integers, strings, {@link VersionVector} + * instances, or one of the special objects {@link VersionVector#MAX_VALUE MAX_VALUE}, + * {@link VersionVector#MAXS_VALUE MAXS_VALUE}, or {@link VersionVector#MIN_VALUE MIN_VALUE}.

    + * + *

    When two versions are compared, they are always considered padded to infinity by their + * pad value or by {@link VersionVector#MIN_VALUE MIN_VALUE} in case the pad value is + * null. The comparison is type sensitive so that:

    + * MAX_VALUE > Integer > VersionVector > MAXS_VALUE > String > MIN_VALUE
    + *
    + * + * @Immutable + * @noextend This class is not intended to be subclassed by clients. + */ +public class OmniVersion extends BasicVersion { + private static final long serialVersionUID = 1996212688810048879L; + + private static OmniVersion minimumVersion; + + private static OmniVersion maximumVersion; + + private final Comparable[] vector; + + private final Comparable padValue; + + /** + * The optional format + */ + private final IVersionFormat format; + + /** + * The optional original string + */ + private final String original; + + static BasicVersion fromVector(Comparable[] vector, Comparable padValue, IVersionFormat format, String original) { + if (vector.length == 0) { + if (padValue == null) + return (BasicVersion) emptyVersion; + if (padValue == VersionVector.MAX_VALUE) + return (BasicVersion) MAX_VERSION; + } + if (vector.length == 3 && padValue == null && vector[0] == VersionParser.ZERO_INT && vector[1] == VersionParser.ZERO_INT && vector[2] == VersionParser.ZERO_INT) + return (BasicVersion) emptyVersion; + + return new OmniVersion(vector, padValue, format, original); + } + + public static Version createMinVersion() { + if (minimumVersion == null) + minimumVersion = new OmniVersion(new Comparable[0], null, null, null); + return minimumVersion; + } + + public static Version createMaxVersion() { + if (maximumVersion == null) + maximumVersion = new OmniVersion(new Comparable[0], VersionVector.MAX_VALUE, null, null); + return maximumVersion; + } + + private OmniVersion(Comparable[] array, Comparable padValue, IVersionFormat format, String original) { + this.vector = array; + this.padValue = padValue; + this.format = format; + this.original = original; + } + + public boolean equals(Object o) { + if (o == this) + return true; + + if (!(o instanceof BasicVersion)) + return false; + + BasicVersion ov = (BasicVersion) o; + return VersionVector.equals(vector, padValue, ov.getVector(), ov.getPad()); + } + + public IVersionFormat getFormat() { + return format; + } + + public int getMajor() { + return getIntElement(0); + } + + public int getMicro() { + return getIntElement(2); + } + + public int getMinor() { + return getIntElement(1); + } + + public String getOriginal() { + return original; + } + + public String getQualifier() { + if (vector.length == 3) + return VersionVector.MINS_VALUE; + + if (vector.length != 4) + throw new UnsupportedOperationException(); + + Comparable qualifier = vector[3]; + if (qualifier == VersionVector.MAXS_VALUE) + return IVersionFormat.DEFAULT_MAX_STRING_TRANSLATION; + if (!(qualifier instanceof String)) + throw new UnsupportedOperationException(); + return (String) qualifier; + } + + public int hashCode() { + return VersionVector.hashCode(vector, padValue); + } + + /** + * Checks if this version is in compliance with the OSGi version spec. + * @return A flag indicating whether the version is OSGi compatible or not. + */ + public boolean isOSGiCompatible() { + if (vector.length < 3 || vector.length > 4) + return (this == emptyVersion || this == MAX_VERSION); + + if (getPad() != null) + return false; + + for (int i = 0; i < 3; ++i) { + Object e = vector[i]; + if (!(e instanceof Integer && ((Integer) e).intValue() >= 0)) + return false; + } + + if (vector.length == 3) + return true; // No qualifier. Still compatible + return OSGiVersion.isValidOSGiQualifier(vector[3]); + } + + /** + * Appends the original for this version onto the sb StringBuffer + * if present. + * @param sb The buffer that will receive the raw string format + * @param rangeSafe Set to true if range delimiters should be escaped + */ + public void originalToString(StringBuffer sb, boolean rangeSafe) { + if (original != null) { + if (rangeSafe) { + // Escape all range delimiters while appending + String s = original; + int end = s.length(); + for (int idx = 0; idx < end; ++idx) { + char c = s.charAt(idx); + if (c == '\\' || c == '[' || c == '(' || c == ']' || c == ')' || c == ',' || c <= ' ') + sb.append('\\'); + sb.append(c); + } + } else + sb.append(original); + } + } + + /** + * Appends the raw format for this version onto the sb StringBuffer. + * @param sb The buffer that will receive the raw string format + * @param rangeSafe Set to true if range delimiters should be escaped + */ + public void rawToString(StringBuffer sb, boolean rangeSafe) { + VersionVector.toString(sb, vector, padValue, rangeSafe); + } + + /** + * Appends the string representation of this version onto the + * sb StringBuffer. + * @param sb The buffer that will receive the version string + */ + public void toString(StringBuffer sb) { + if (this == emptyVersion) + sb.append("0.0.0"); //$NON-NLS-1$ + else { + sb.append(RAW_PREFIX); + VersionVector.toString(sb, vector, padValue, false); + if (format != null || original != null) { + sb.append('/'); + if (format != null) + format.toString(sb); + if (original != null) { + sb.append(':'); + originalToString(sb, false); + } + } + } + } + + private int getIntElement(int i) { + if (!(vector.length > i && vector[i] instanceof Integer)) + throw new UnsupportedOperationException(); + return ((Integer) vector[i]).intValue(); + } + + // Preserve singletons during deserialization + private Object readResolve() { + Version v = this; + if (equals(MAX_VERSION)) + v = MAX_VERSION; + else if (equals(emptyVersion)) + v = emptyVersion; + return v; + } + + public Comparable getPad() { + return padValue; + } + + public Comparable getSegment(int index) { + return vector[index]; + } + + public int getSegmentCount() { + return vector.length; + } + + Comparable[] getVector() { + return vector; + } + + public int compareTo(Version v) { + BasicVersion ov = (BasicVersion) v; + return VersionVector.compare(vector, padValue, ov.getVector(), ov.getPad()); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ProvidedCapability.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ProvidedCapability.java index 1d8ed6dfa..06f8af8e1 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ProvidedCapability.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ProvidedCapability.java @@ -12,7 +12,8 @@ package org.eclipse.equinox.internal.p2.metadata; import org.eclipse.core.runtime.Assert; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.IProvidedCapability; +import org.eclipse.equinox.p2.metadata.Version; /** * Describes a capability as exposed or required by an installable unit @@ -59,17 +60,7 @@ public class ProvidedCapability implements IProvidedCapability { return namespace.hashCode() * name.hashCode() * version.hashCode(); } - /** - * Returns whether this provided capability satisfies the given required capability. - * @return true if this capability satisfies the given required - * capability, and false otherwise. - */ - public boolean satisfies(IRequiredCapability candidate) { - return candidate.satisfiedBy(this); - } - public String toString() { return namespace + '/' + name + '/' + version; } - } diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/RequiredCapability.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/RequiredCapability.java index 690c9e1ba..04d5b4ede 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/RequiredCapability.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/RequiredCapability.java @@ -12,7 +12,9 @@ package org.eclipse.equinox.internal.p2.metadata; import org.eclipse.core.runtime.Assert; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.expression.*; +import org.osgi.framework.Filter; /** * A required capability represents some external constraint on an {@link IInstallableUnit}. @@ -28,72 +30,124 @@ import org.eclipse.equinox.internal.provisional.p2.metadata.*; * @see IInstallableUnit#NAMESPACE_IU_ID */ public class RequiredCapability implements IRequiredCapability { - private static final String[] NO_SELECTORS = new String[0]; + private final Filter filter; + private final boolean greedy; + private final IMatchExpression matchExpression; + private final int min; + private final int max; - private String filter; - private final boolean multiple; - private final String name;//never null - private final String namespace;//never null - private boolean optional; - private boolean greedy = true; - private final VersionRange range;//never null - private String[] selectors = NO_SELECTORS;//never null + private static final String MEMBER_NAME = "name"; //$NON-NLS-1$ + private static final String MEMBER_NAMESPACE = "namespace"; //$NON-NLS-1$ + private static final String MEMBER_VERSION = "version"; //$NON-NLS-1$ + private static final String MEMBER_PROVIDED_CAPABILITIES = "providedCapabilities"; //$NON-NLS-1$ + + private static final IExpression allVersionsExpression; + private static final IExpression range_II_Expression; + private static final IExpression range_IN_Expression; + private static final IExpression range_NI_Expression; + private static final IExpression range_NN_Expression; + private static final IExpression strictVersionExpression; + private static final IExpression openEndedExpression; + private static final IExpression openEndedNonInclusiveExpression; + + static { + IExpressionFactory factory = ExpressionUtil.getFactory(); + IExpression xVar = factory.variable("x"); //$NON-NLS-1$ + IExpression nameEqual = factory.equals(factory.member(xVar, MEMBER_NAME), factory.indexedParameter(0)); + IExpression namespaceEqual = factory.equals(factory.member(xVar, MEMBER_NAMESPACE), factory.indexedParameter(1)); + + IExpression versionMember = factory.member(xVar, MEMBER_VERSION); + + IExpression versionCmpLow = factory.indexedParameter(2); + IExpression versionEqual = factory.equals(versionMember, versionCmpLow); + IExpression versionGt = factory.greater(versionMember, versionCmpLow); + IExpression versionGtEqual = factory.greaterEqual(versionMember, versionCmpLow); + + IExpression versionCmpHigh = factory.indexedParameter(3); + IExpression versionLt = factory.less(versionMember, versionCmpHigh); + IExpression versionLtEqual = factory.lessEqual(versionMember, versionCmpHigh); + + IExpression pvMember = factory.member(factory.thisVariable(), MEMBER_PROVIDED_CAPABILITIES); + allVersionsExpression = factory.exists(pvMember, factory.lambda(xVar, factory.and(nameEqual, namespaceEqual))); + strictVersionExpression = factory.exists(pvMember, factory.lambda(xVar, factory.and(nameEqual, namespaceEqual, versionEqual))); + openEndedExpression = factory.exists(pvMember, factory.lambda(xVar, factory.and(nameEqual, namespaceEqual, versionGtEqual))); + openEndedNonInclusiveExpression = factory.exists(pvMember, factory.lambda(xVar, factory.and(nameEqual, namespaceEqual, versionGt))); + range_II_Expression = factory.exists(pvMember, factory.lambda(xVar, factory.and(nameEqual, namespaceEqual, versionGtEqual, versionLtEqual))); + range_IN_Expression = factory.exists(pvMember, factory.lambda(xVar, factory.and(nameEqual, namespaceEqual, versionGtEqual, versionLt))); + range_NI_Expression = factory.exists(pvMember, factory.lambda(xVar, factory.and(nameEqual, namespaceEqual, versionGt, versionLtEqual))); + range_NN_Expression = factory.exists(pvMember, factory.lambda(xVar, factory.and(nameEqual, namespaceEqual, versionGt, versionLt))); + } /** * TODO replace booleans with int options flag. */ public RequiredCapability(String namespace, String name, VersionRange range, String filter, boolean optional, boolean multiple) { - Assert.isNotNull(namespace); - Assert.isNotNull(name); - this.namespace = namespace; - this.name = name; - this.range = range == null ? VersionRange.emptyRange : range; - this.optional = optional; - this.filter = filter; - this.multiple = multiple; + this(namespace, name, range, filter, optional, multiple, true); } public RequiredCapability(String namespace, String name, VersionRange range, String filter, boolean optional, boolean multiple, boolean greedy) { - this(namespace, name, range, filter, optional, multiple); + this(namespace, name, range, filter == null ? (Filter) null : ExpressionUtil.parseLDAP(filter), optional ? 0 : 1, multiple ? 1 : Integer.MAX_VALUE, greedy); + } + + public RequiredCapability(String namespace, String name, VersionRange range, Filter filter, int min, int max, boolean greedy) { + Assert.isNotNull(namespace); + Assert.isNotNull(name); + IExpressionFactory factory = ExpressionUtil.getFactory(); + if (range == null || range.equals(VersionRange.emptyRange)) { + matchExpression = factory.matchExpression(allVersionsExpression, name, namespace); + } else { + if (range.getMinimum().equals(range.getMaximum())) { + // Explicit version appointed + matchExpression = factory.matchExpression(strictVersionExpression, name, namespace, range.getMinimum()); + } else { + if (range.getMaximum().equals(Version.MAX_VERSION)) { + // Open ended + matchExpression = factory.matchExpression(range.getIncludeMinimum() ? openEndedExpression : openEndedNonInclusiveExpression, name, namespace, range.getMinimum()); + } else { + matchExpression = factory.matchExpression(// + range.getIncludeMinimum() ? (range.getIncludeMaximum() ? range_II_Expression : range_IN_Expression) // + : (range.getIncludeMaximum() ? range_NI_Expression : range_NN_Expression), // + name, namespace, range.getMinimum(), range.getMaximum()); + } + } + } + this.min = min; + this.max = max; this.greedy = greedy; + this.filter = filter; } public boolean equals(Object obj) { if (this == obj) return true; - if (obj == null) - return false; - if (!(obj instanceof IRequiredCapability)) - return false; - final IRequiredCapability other = (IRequiredCapability) obj; - if (filter == null) { - if (other.getFilter() != null) + if (obj instanceof RequiredCapability) { + RequiredCapability other = (RequiredCapability) obj; + if (filter == null) { + if (other.getFilter() != null) + return false; + } else if (!filter.equals(other.getFilter())) return false; - } else if (!filter.equals(other.getFilter())) - return false; - if (multiple != other.isMultiple()) - return false; - if (!name.equals(other.getName())) - return false; - if (!namespace.equals(other.getNamespace())) - return false; - if (optional != other.isOptional()) - return false; - if (!range.equals(other.getRange())) - return false; - return true; - } - - public String getFilter() { - return filter; + return min == other.min && max == other.max && greedy == other.greedy && matchExpression.equals(other.matchExpression); + } + if (obj instanceof IRequiredCapability) { + // Some other type of RequiredCapability + IRequiredCapability other = (IRequiredCapability) obj; + if (filter == null) { + if (other.getFilter() != null) + return false; + } else if (!filter.equals(other.getFilter())) + return false; + return min == other.getMin() && max == other.getMax() && greedy == other.isGreedy() && getName().equals(other.getName()) && getNamespace().equals(other.getNamespace()) && getRange().equals(other.getRange()); + } + return false; } public String getName() { - return name; + return (String) matchExpression.getParameters()[0]; } public String getNamespace() { - return namespace; + return (String) matchExpression.getParameters()[1]; } /** @@ -103,55 +157,17 @@ public class RequiredCapability implements IRequiredCapability { * @return the range of versions that satisfy this required capability. */ public VersionRange getRange() { - return range; - } - - /** - * Returns the properties to use for evaluating required capability filters - * downstream from this capability. For example, if the selector "doc" - * is provided, then a downstream InstallableUnit with a required capability - * filtered with "doc=true" will be included. - */ - public String[] getSelectors() { - return selectors; + return extractRange(matchExpression); } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((filter == null) ? 0 : filter.hashCode()); - result = prime * result + (multiple ? 1231 : 1237); - result = prime * result + name.hashCode(); - result = prime * result + namespace.hashCode(); - result = prime * result + (optional ? 1231 : 1237); - result = prime * result + range.hashCode(); + result = prime * result + matchExpression.hashCode(); return result; } - public boolean isMultiple() { - return multiple; - } - - public boolean isOptional() { - return optional; - } - - /** - * TODO This object shouldn't be mutable since it makes equality unstable, and - * introduces lifecycle issues (how are the changes persisted, etc) - */ - public void setFilter(String filter) { - this.filter = filter; - } - - /** - * TODO This object shouldn't be mutable since it makes equality unstable, and - * introduces lifecycle issues (how are the changes persisted, etc) - */ - public void setSelectors(String[] selectors) { - this.selectors = selectors; - } - public boolean isGreedy() { return greedy; } @@ -173,6 +189,7 @@ public class RequiredCapability implements IRequiredCapability { result.append(' '); result.append(getName()); result.append(' '); + VersionRange range = getRange(); //for an exact version match, print a simpler expression if (range.getMinimum().equals(range.getMaximum())) result.append('[').append(range.getMinimum()).append(']'); @@ -181,15 +198,59 @@ public class RequiredCapability implements IRequiredCapability { return result.toString(); } - public boolean isNegation() { - return false; + public int getMin() { + return min; + } + + public int getMax() { + return max; + } + + public IMatchExpression getMatches() { + return matchExpression; + } + + public Filter getFilter() { + return filter; + } + + public boolean isMatch(IInstallableUnit candidate) { + return matchExpression.isMatch(candidate); + } + + public static boolean isVersionStrict(IMatchExpression matchExpression) { + return ExpressionUtil.getOperand(matchExpression) == strictVersionExpression; + } + + public static String extractName(IMatchExpression matchExpression) { + assertValid(matchExpression); + return (String) matchExpression.getParameters()[0]; + } + + public static String extractNamespace(IMatchExpression matchExpression) { + assertValid(matchExpression); + return (String) matchExpression.getParameters()[1]; + } + + public static VersionRange extractRange(IMatchExpression matchExpression) { + IExpression expr = assertValid(matchExpression); + Object[] params = matchExpression.getParameters(); + if (params.length < 3) + return VersionRange.emptyRange; + Version v = (Version) params[2]; + if (params.length < 4) { + if (expr == strictVersionExpression) + return new VersionRange(v, true, v, true); + return new VersionRange(v, expr == openEndedExpression, Version.MAX_VERSION, true); + } + Version h = (Version) params[3]; + return new VersionRange(v, expr == range_II_Expression || expr == range_IN_Expression, h, expr == range_II_Expression || expr == range_NI_Expression); } - public boolean satisfiedBy(IProvidedCapability cap) { - if (getName() == null || !getName().equals(cap.getName())) - return false; - if (getNamespace() == null || !getNamespace().equals(cap.getNamespace())) - return false; - return getRange().isIncluded(cap.getVersion()); + private static IExpression assertValid(IMatchExpression matchExpression) { + IExpression expr = ExpressionUtil.getOperand(matchExpression); + if (!(expr == allVersionsExpression || expr == range_II_Expression || expr == range_IN_Expression || expr == range_NI_Expression || expr == range_NN_Expression || expr == strictVersionExpression || expr == openEndedExpression || expr == openEndedNonInclusiveExpression)) + throw new IllegalArgumentException(); + return expr; } } diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/RequirementChange.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/RequirementChange.java index 49742867a..d67a1ca39 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/RequirementChange.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/RequirementChange.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.IRequirementChange; public class RequirementChange implements IRequirementChange { private IRequiredCapability applyOn; @@ -39,46 +39,7 @@ public class RequirementChange implements IRequirementChange { if (toMatch.getRange().equals(applyOn.getRange())) return true; - return intersect(toMatch.getRange(), applyOn.getRange()) == null ? false : true; - } - - private VersionRange intersect(VersionRange r1, VersionRange r2) { - Version resultMin = null; - boolean resultMinIncluded = false; - Version resultMax = null; - boolean resultMaxIncluded = false; - - int minCompare = r1.getMinimum().compareTo(r2.getMinimum()); - if (minCompare < 0) { - resultMin = r2.getMinimum(); - resultMinIncluded = r2.getIncludeMinimum(); - } else if (minCompare > 0) { - resultMin = r1.getMinimum(); - resultMinIncluded = r1.getIncludeMinimum(); - } else if (minCompare == 0) { - resultMin = r1.getMinimum(); - resultMinIncluded = r1.getIncludeMinimum() && r2.getIncludeMinimum(); - } - - int maxCompare = r1.getMaximum().compareTo(r2.getMaximum()); - if (maxCompare > 0) { - resultMax = r2.getMaximum(); - resultMaxIncluded = r2.getIncludeMaximum(); - } else if (maxCompare < 0) { - resultMax = r1.getMaximum(); - resultMaxIncluded = r1.getIncludeMaximum(); - } else if (maxCompare == 0) { - resultMax = r1.getMaximum(); - resultMaxIncluded = r1.getIncludeMaximum() && r2.getIncludeMaximum(); - } - - int resultRangeComparison = resultMin.compareTo(resultMax); - if (resultRangeComparison < 0) - return new VersionRange(resultMin, resultMinIncluded, resultMax, resultMaxIncluded); - else if (resultRangeComparison == 0 && resultMinIncluded == resultMaxIncluded) - return new VersionRange(resultMin, resultMinIncluded, resultMax, resultMaxIncluded); - else - return null; + return toMatch.getRange().intersect(applyOn.getRange()) != null; } public int hashCode() { diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ResolvedInstallableUnit.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ResolvedInstallableUnit.java index 0d4459aa7..580f5d5a4 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ResolvedInstallableUnit.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/ResolvedInstallableUnit.java @@ -11,41 +11,48 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata; +import org.eclipse.equinox.p2.metadata.Version; + import java.util.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; +import org.eclipse.equinox.p2.metadata.*; +import org.osgi.framework.Filter; public class ResolvedInstallableUnit implements IInstallableUnit { - private static IInstallableUnit[] NO_IU = new IInstallableUnit[0]; + private static IInstallableUnitFragment[] NO_IU = new IInstallableUnitFragment[0]; - private IInstallableUnit[] fragments = NO_IU; - protected IInstallableUnit original; + private final IInstallableUnitFragment[] fragments; + protected final IInstallableUnit original; public ResolvedInstallableUnit(IInstallableUnit resolved) { - this.original = resolved; + this(resolved, null); } public ResolvedInstallableUnit(IInstallableUnit resolved, IInstallableUnitFragment[] fragments) { this.original = resolved; - this.fragments = fragments; + this.fragments = fragments == null ? NO_IU : fragments; } - public IInstallableUnitFragment[] getFragments() { - ArrayList result = new ArrayList(); - if (fragments != null) - result.addAll(Arrays.asList(fragments)); - for (int i = 0; i < result.size(); i++) { - IInstallableUnit fragment = (IInstallableUnit) result.get(i); + public List getFragments() { + int fcount = fragments.length; + if (fcount == 0) + return CollectionUtils.emptyList(); + + ArrayList result = new ArrayList(fcount); + result.addAll(Arrays.asList(fragments)); + for (int i = 0; i < fcount; i++) { + IInstallableUnit fragment = fragments[i]; if (fragment.isResolved()) - result.addAll(Arrays.asList(fragment.getFragments())); + result.addAll(fragment.getFragments()); } - return (IInstallableUnitFragment[]) result.toArray(new IInstallableUnitFragment[result.size()]); + return result; } - public IArtifactKey[] getArtifacts() { + public Collection getArtifacts() { return original.getArtifacts(); } - public String getFilter() { + public Filter getFilter() { return original.getFilter(); } @@ -57,47 +64,56 @@ public class ResolvedInstallableUnit implements IInstallableUnit { return original.getProperty(key); } - public Map getProperties() { + public Map getProperties() { return original.getProperties(); } - public IProvidedCapability[] getProvidedCapabilities() { - ArrayList result = new ArrayList(); - result.addAll(Arrays.asList(original.getProvidedCapabilities())); - for (int i = 0; i < fragments.length; i++) { - result.addAll(Arrays.asList(fragments[i].getProvidedCapabilities())); - } - return (IProvidedCapability[]) result.toArray(new IProvidedCapability[result.size()]); + public String getProperty(String key, String locale) { + return original.getProperty(key, locale); } - public IRequiredCapability[] getRequiredCapabilities() { - ArrayList result = new ArrayList(); - result.addAll(Arrays.asList(original.getRequiredCapabilities())); - for (int i = 0; i < fragments.length; i++) { - result.addAll(Arrays.asList(fragments[i].getRequiredCapabilities())); - } - return (IRequiredCapability[]) result.toArray(new IRequiredCapability[result.size()]); + public Collection getProvidedCapabilities() { + Collection originalCapabilities = original.getProvidedCapabilities(); + if (fragments.length == 0) + return originalCapabilities; + + ArrayList result = new ArrayList(originalCapabilities); + for (int i = 0; i < fragments.length; i++) + result.addAll(fragments[i].getProvidedCapabilities()); + return result; } - public IRequiredCapability[] getMetaRequiredCapabilities() { - ArrayList result = new ArrayList(); - result.addAll(Arrays.asList(original.getMetaRequiredCapabilities())); - for (int i = 0; i < fragments.length; i++) { - result.addAll(Arrays.asList(fragments[i].getMetaRequiredCapabilities())); - } - return (IRequiredCapability[]) result.toArray(new IRequiredCapability[result.size()]); + public Collection getRequiredCapabilities() { + Collection originalCapabilities = original.getRequiredCapabilities(); + if (fragments.length == 0) + return originalCapabilities; + + ArrayList result = new ArrayList(originalCapabilities); + for (int i = 0; i < fragments.length; i++) + result.addAll(fragments[i].getRequiredCapabilities()); + return result; } - public ITouchpointData[] getTouchpointData() { - ArrayList result = new ArrayList(); - result.addAll(Arrays.asList(original.getTouchpointData())); - for (int i = 0; i < fragments.length; i++) { - ITouchpointData[] data = fragments[i].getTouchpointData(); - for (int j = 0; j < data.length; j++) { - result.add(data[j]); - } - } - return (ITouchpointData[]) result.toArray(new ITouchpointData[result.size()]); + public Collection getMetaRequiredCapabilities() { + Collection originalCapabilities = original.getMetaRequiredCapabilities(); + if (fragments.length == 0) + return originalCapabilities; + + ArrayList result = new ArrayList(originalCapabilities); + for (int i = 0; i < fragments.length; i++) + result.addAll(fragments[i].getMetaRequiredCapabilities()); + return result; + } + + public List getTouchpointData() { + List originalTouchpointData = original.getTouchpointData(); + if (fragments.length == 0) + return originalTouchpointData; + + ArrayList result = new ArrayList(originalTouchpointData); + for (int i = 0; i < fragments.length; i++) + result.addAll(fragments[i].getTouchpointData()); + return result; } public ITouchpointType getTouchpointType() { @@ -108,10 +124,6 @@ public class ResolvedInstallableUnit implements IInstallableUnit { return original.getVersion(); } - public boolean isFragment() { - return original.isFragment(); - } - public boolean isSingleton() { return original.isSingleton(); } @@ -139,14 +151,11 @@ public class ResolvedInstallableUnit implements IInstallableUnit { return original; } - public int compareTo(Object toCompareTo) { - if (!(toCompareTo instanceof IInstallableUnit)) { - return -1; - } - IInstallableUnit other = (IInstallableUnit) toCompareTo; - if (getId().compareTo(other.getId()) == 0) - return (getVersion().compareTo(other.getVersion())); - return getId().compareTo(other.getId()); + public int compareTo(IInstallableUnit other) { + int cmp = getId().compareTo(other.getId()); + if (cmp == 0) + cmp = getVersion().compareTo(other.getVersion()); + return cmp; } public boolean isResolved() { @@ -161,20 +170,24 @@ public class ResolvedInstallableUnit implements IInstallableUnit { return original.getUpdateDescriptor(); } - public ILicense getLicense() { - return original.getLicense(); + public Collection getLicenses() { + return original.getLicenses(); + } + + public ILicense[] getLicenses(String locale) { + return original.getLicenses(locale); } public ICopyright getCopyright() { return original.getCopyright(); } - public boolean satisfies(IRequiredCapability candidate) { - IProvidedCapability[] provides = getProvidedCapabilities(); - for (int i = 0; i < provides.length; i++) - if (provides[i].satisfies(candidate)) - return true; - return false; + public ICopyright getCopyright(String locale) { + return original.getCopyright(locale); + } + + public boolean satisfies(IRequirement candidate) { + return candidate.isMatch(this); } } diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TouchpointData.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TouchpointData.java index 9ea83d479..791363dd5 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TouchpointData.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TouchpointData.java @@ -11,9 +11,12 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata; -import java.util.*; +import java.util.Collections; +import java.util.Map; import java.util.Map.Entry; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.ITouchpointData; +import org.eclipse.equinox.p2.metadata.ITouchpointInstruction; /** * Touchpoint data instances contain the additional information needed by a touchpoint @@ -31,7 +34,7 @@ public class TouchpointData implements ITouchpointData { * of keys supported is up to the touchpoint that will process these * instructions. This map is never null. */ - private Map instructions; + private Map instructions; public int hashCode() { return 31 * 1 + ((instructions == null) ? 0 : instructions.hashCode()); @@ -56,7 +59,7 @@ public class TouchpointData implements ITouchpointData { /** * Clients must use the factory method on {@link MetadataFactory}. */ - public TouchpointData(Map instructions) { + public TouchpointData(Map instructions) { this.instructions = instructions; } @@ -64,7 +67,7 @@ public class TouchpointData implements ITouchpointData { * Returns the touchpoint instruction corresponding to the given key. */ public ITouchpointInstruction getInstruction(String instructionKey) { - return (ITouchpointInstruction) instructions.get(instructionKey); + return instructions.get(instructionKey); } /** @@ -73,7 +76,7 @@ public class TouchpointData implements ITouchpointData { * * @return the touchpoint instructions */ - public Map getInstructions() { + public Map getInstructions() { return Collections.unmodifiableMap(instructions); } @@ -82,8 +85,7 @@ public class TouchpointData implements ITouchpointData { */ public String toString() { StringBuffer result = new StringBuffer(); - for (Iterator iterator = instructions.entrySet().iterator(); iterator.hasNext();) { - Entry instruction = (Entry) iterator.next(); + for (Entry instruction : instructions.entrySet()) { result.append(instruction.getKey()).append(" -> ").append(instruction.getValue()).append('\n'); //$NON-NLS-1$ } return result.toString(); diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TouchpointInstruction.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TouchpointInstruction.java index e59e9beea..5928639a1 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TouchpointInstruction.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TouchpointInstruction.java @@ -11,10 +11,10 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata; -import java.util.Iterator; import java.util.Map; -import org.eclipse.equinox.internal.provisional.p2.metadata.ITouchpointInstruction; +import java.util.Map.Entry; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.ITouchpointInstruction; /** * A touchpoint instruction contains either a sequence of instruction statements @@ -65,16 +65,18 @@ public class TouchpointInstruction implements ITouchpointInstruction { * where the keys are parameter names, and the values are parameter values * @return An encoded touchpoint instruction statement */ - public static String encodeAction(String actionName, Map parameters) { + public static String encodeAction(String actionName, Map parameters) { StringBuffer result = new StringBuffer(actionName); result.append('('); - for (Iterator it = parameters.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); + boolean first = true; + for (Entry entry : parameters.entrySet()) { + if (first) + first = false; + else + result.append(','); result.append(entry.getKey()); result.append(':'); - appendEncoded(result, (String) entry.getValue()); - if (it.hasNext()) - result.append(','); + appendEncoded(result, entry.getValue()); } result.append(')').append(';'); return result.toString(); diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TouchpointType.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TouchpointType.java index 4056d7f09..86bb05b87 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TouchpointType.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TouchpointType.java @@ -11,8 +11,9 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata; -import org.eclipse.equinox.internal.provisional.p2.metadata.ITouchpointType; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.p2.metadata.ITouchpointType; /** * Identifies a particular touchpoint. A touchpoint is identified by an id diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TranslationSupport.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TranslationSupport.java new file mode 100644 index 000000000..e42289040 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/TranslationSupport.java @@ -0,0 +1,299 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * EclipseSource - ongoing development + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata; + +import java.lang.ref.SoftReference; +import java.util.*; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil; +import org.eclipse.equinox.p2.metadata.expression.IExpression; +import org.eclipse.equinox.p2.metadata.query.ExpressionQuery; +import org.eclipse.equinox.p2.metadata.query.FragmentQuery; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.osgi.service.localization.LocaleProvider; + +/** + * TranslationSupport provides string translations for properties of an + * IInstallableUnit. Clients can specify an {@link IQueryable} that should be used + * to obtain the translation fragment IU's, as well as the locale that + * should be used for translations. + * + * @since 2.0 + */ +public class TranslationSupport { + // TODO: these constants should come from API, eg. IInstallableUnit or ??? + static final Locale DEFAULT_LOCALE = new Locale("df", "LT"); //$NON-NLS-1$//$NON-NLS-2$ + private static TranslationSupport instance; + + static final String NAMESPACE_IU_LOCALIZATION = "org.eclipse.equinox.p2.localization"; //$NON-NLS-1$ + private IQueryable fragmentSource; + + private static IExpression capabilityMatch = ExpressionUtil.parse("providedCapabilities.exists(x | x.name == $0 && x.namespace == $1)"); //$NON-NLS-1$ + + // Cache the IU fragments that provide localizations for a given locale. + // Map>: locale => soft reference to a queryResult + private Map>> localeCollectorCache = new HashMap>>(2); + + private LocaleProvider localeProvider; + + public synchronized static TranslationSupport getInstance() { + if (instance == null) + instance = new TranslationSupport(); + return instance; + } + + /** + * Create an instance of TranslationSupport for the current locale. + * Unless otherwise specified, the currently running profile will serve + * as the source of the translation fragments. + * + * @since 2.0 + */ + public TranslationSupport() { + super(); + } + + /** + */ + private List buildLocaleVariants(String locale) { + ArrayList result = new ArrayList(4); + int lastSeparator; + while (true) { + result.add(locale); + lastSeparator = locale.lastIndexOf('_'); + if (lastSeparator == -1) + break; + locale = locale.substring(0, lastSeparator); + } + // Add the default locale (most general) + result.add(DEFAULT_LOCALE.toString()); + return result; + } + + /** + * Cache the translated property value to optimize future retrieval of the same value. + * Currently we just cache on the installable unit object in memory. In future + * we should push support for localized property retrieval into IInstallableUnit + * so we aren't required to reach around the API here. + */ + private String cacheResult(IInstallableUnit iu, String localizedKey, String localizedValue) { + if (iu instanceof InstallableUnit) + ((InstallableUnit) iu).setLocalizedProperty(localizedKey, localizedValue); + return localizedValue; + } + + /** + * Return the copyright for the specified IInstallableUnit, + * localized for the receiver's locale. + * + * @param iu the IInstallableUnit in question + * @return the localized copyright defined by the IInstallableUnit + */ + public ICopyright getCopyright(IInstallableUnit iu, String locale) { + if (locale == null) + locale = getCurrentLocale(); + ICopyright copyright = iu.getCopyright(); + String body = (copyright != null ? copyright.getBody() : null); + if (body == null || body.length() <= 1 || body.charAt(0) != '%') + return copyright; + final String actualKey = body.substring(1); // Strip off the % + body = getLocalizedIUProperty(iu, actualKey, locale); + return MetadataFactory.createCopyright(copyright.getLocation(), body); + } + + private String getCurrentLocale() { + if (localeProvider != null) + return localeProvider.getLocale().toString(); + return Locale.getDefault().toString(); + } + + /** + * Return the localized value for the specified IInstallableUnit + * property. + * + * @param iu the IInstallableUnit in question + * @param propertyKey the name of the property to be retrieved + * @param locale The locale to return the property for + * @return the localized property value, or null if no + * such property is defined. + */ + public String getIUProperty(IInstallableUnit iu, String propertyKey, String locale) { + if (locale == null) + locale = getCurrentLocale(); + String value = iu.getProperty(propertyKey); + if (value == null || value.length() <= 1 || value.charAt(0) != '%') + return value; + // else have a localizable property + final String actualKey = value.substring(1); // Strip off the % + return getLocalizedIUProperty(iu, actualKey, locale); + } + + /** + * Return the localized value for the specified IInstallableUnit + * property using the default locale. + * + * @param iu the IInstallableUnit in question + * @param propertyKey the name of the property to be retrieved + * @return the localized property value, or null if no + * such property is defined. + */ + public String getIUProperty(IInstallableUnit iu, String propertyKey) { + return getIUProperty(iu, propertyKey, null); + } + + private ILicense getLicense(IInstallableUnit iu, ILicense license, String locale) { + String body = (license != null ? license.getBody() : null); + if (body == null || body.length() <= 1 || body.charAt(0) != '%') + return license; + final String actualKey = body.substring(1); // Strip off the % + body = getLocalizedIUProperty(iu, actualKey, locale); + return MetadataFactory.createLicense(license.getLocation(), body); + } + + /** + * Return an array of licenses for the specified IInstallableUnit, + * localized for the receiver's locale. + * + * @param iu the IInstallableUnit in question + * @return the localized licenses defined by the IInstallableUnit + */ + public ILicense[] getLicenses(IInstallableUnit iu, String locale) { + if (locale == null) + locale = getCurrentLocale(); + Collection licenses = iu.getLicenses(); + ILicense[] translatedLicenses = new ILicense[licenses.size()]; + int i = 0; + for (ILicense iLicense : licenses) { + translatedLicenses[i++] = getLicense(iu, iLicense, locale); + } + return translatedLicenses; + } + + /** + * Collects the installable unit fragments that contain locale data for the given locales. + */ + private synchronized IQueryResult getLocalizationFragments(List localeVariants, String locale) { + if (fragmentSource == null) { + LogHelper.log(new Status(IStatus.ERROR, MetadataActivator.PI_METADATA, "Profile registry unavailable. Default language will be used.", new RuntimeException())); //$NON-NLS-1$ + return Collector.emptyCollector(); + } + + SoftReference> queryResultReference = localeCollectorCache.get(locale); + if (queryResultReference != null) { + Collector cached = (Collector) queryResultReference.get(); + if (cached != null) + return cached; + } + + final List locales = localeVariants; + + @SuppressWarnings("unchecked") + IQuery[] localeQuery = new IQuery[locales.size()]; + for (int j = 0; j < locales.size(); j++) { + localeQuery[j] = new ExpressionQuery(IInstallableUnit.class, capabilityMatch, locales.get(j), NAMESPACE_IU_LOCALIZATION); + } + + IQuery iuQuery = new PipedQuery(new FragmentQuery(), CompoundQuery.createCompoundQuery(localeQuery, false)); + IQueryResult collected = fragmentSource.query(iuQuery, null); + localeCollectorCache.put(locale, new SoftReference>(collected)); + return collected; + } + + private String getLocalizedIUProperty(IInstallableUnit iu, String actualKey, String locale) { + String localizedKey = makeLocalizedKey(actualKey, locale); + String localizedValue = null; + + //first check for a cached localized value + if (iu instanceof InstallableUnit) + localizedValue = ((InstallableUnit) iu).getLocalizedProperty(localizedKey); + //next check if the localized value is stored in the same IU (common case) + if (localizedValue == null) + localizedValue = iu.getProperty(localizedKey); + if (localizedValue != null) + return localizedValue; + + final List locales = buildLocaleVariants(locale); + final IInstallableUnit theUnit = iu; + + IQueryResult localizationFragments = getLocalizationFragments(locales, locale); + + IQuery hostLocalizationQuery = new MatchQuery() { + public boolean isMatch(IInstallableUnit object) { + boolean haveHost = false; + if (object instanceof IInstallableUnitFragment) { + IInstallableUnitFragment fragment = (IInstallableUnitFragment) object; + IRequirement[] hosts = fragment.getHost(); + for (int i = 0; i < hosts.length; i++) { + if (theUnit.satisfies(hosts[i])) { + haveHost = true; + break; + } + } + } + return haveHost; + } + }; + + IQuery iuQuery = new PipedQuery(new FragmentQuery(), hostLocalizationQuery); + IQueryResult collected = iuQuery.perform(localizationFragments.iterator()); + if (!collected.isEmpty()) { + String translation = null; + for (Iterator iter = collected.iterator(); iter.hasNext() && translation == null;) { + IInstallableUnit localizationIU = iter.next(); + for (Iterator jter = locales.iterator(); jter.hasNext();) { + String localeKey = makeLocalizedKey(actualKey, jter.next()); + translation = localizationIU.getProperty(localeKey); + if (translation != null) + return cacheResult(iu, localizedKey, translation); + } + } + } + + for (String nextLocale : locales) { + String localeKey = makeLocalizedKey(actualKey, nextLocale); + String nextValue = iu.getProperty(localeKey); + if (nextValue != null) + return cacheResult(iu, localizedKey, nextValue); + } + + return cacheResult(iu, localizedKey, actualKey); + } + + private String makeLocalizedKey(String actualKey, String localeImage) { + return localeImage + '.' + actualKey; + } + + /** + * Set the locale that should be used when obtaining translations. + * @param provider the locale for which translations should be retrieved. + */ + public void setLocaleProvider(LocaleProvider provider) { + this.localeProvider = provider; + } + + /** + * Set the {@link IQueryable} that should be used to obtain translation fragment + * IUs. Returns the previous translation source. + * + * @param queryable an {@link IQueryable} that can supply the appropriate NLS + * translation fragments + */ + public IQueryable setTranslationSource(IQueryable queryable) { + IQueryable previous = fragmentSource; + this.fragmentSource = queryable; + return previous; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/UpdateDescriptor.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/UpdateDescriptor.java index d93a4500d..232f3abc6 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/UpdateDescriptor.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/UpdateDescriptor.java @@ -8,7 +8,10 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.VersionRange; + +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IUpdateDescriptor; public class UpdateDescriptor implements IUpdateDescriptor { private String description; diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionFormat.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionFormat.java new file mode 100644 index 000000000..3582ad18b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionFormat.java @@ -0,0 +1,345 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata; + +import java.io.Serializable; +import java.util.*; +import org.eclipse.equinox.internal.p2.metadata.VersionFormatParser.Fragment; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.osgi.util.NLS; + +/** + *

    The VersionFormat represents the Omni Version Format in compiled form. It + * is also a parser for versions of that format.

    + *

    An instance of VersionFormat is immutable and thus thread safe. The parser + * does not maintain any state.

    + * + * @Immutable + * @noextend This class is not intended to be subclassed by clients. + */ +public class VersionFormat implements IVersionFormat, Serializable { + + /** + * The string representation of the Omni Version format used for parsing OSGi versions. + */ + public static final String OSGI_FORMAT_STRING = "n[.n=0;[.n=0;[.S='';=[A-Za-z0-9_-];]]]"; //$NON-NLS-1$ + + /** + * The string representation of the Omni Version format used for parsing raw versions. + */ + public static final String RAW_FORMAT_STRING = "r(.r)*p?"; //$NON-NLS-1$ + + private static final long serialVersionUID = -5689435955091405520L; + + private static class StateInfo { + Fragment fragment; + int position; + int segmentCount; + + StateInfo(int position, int segmentCount, Fragment fragment) { + this.fragment = fragment; + this.position = position; + this.segmentCount = segmentCount; + } + } + + static class TreeInfo extends ArrayList { + private static final long serialVersionUID = 4474591345244587260L; + + private Comparable padValue; + private int top; + + TreeInfo(Fragment frag, int pos) { + add(new StateInfo(pos, 0, frag)); + top = 0; + } + + Comparable getPadValue() { + return padValue; + } + + int getPosition() { + return get(top).position; + } + + void popState(List> segments, Fragment frag) { + int idx = top; + while (idx > 0) { + StateInfo si = get(idx); + if (si.fragment == frag) { + int nsegs = segments.size(); + int segMax = si.segmentCount; + while (nsegs > segMax) + segments.remove(--nsegs); + top = idx - 1; + break; + } + } + } + + void pushState(int segCount, Fragment fragment) { + int pos = get(top).position; + if (++top == size()) + add(new StateInfo(pos, segCount, fragment)); + else { + StateInfo si = get(top); + si.fragment = fragment; + si.position = pos; + si.segmentCount = segCount; + } + } + + void setPadValue(Comparable pad) { + padValue = pad; + } + + void setPosition(int pos) { + get(top).position = pos; + } + } + + private static final Map formatCache = Collections.synchronizedMap(new HashMap()); + + /** + * The predefined OSGi format that is used when parsing OSGi + * versions. + */ + public static final VersionFormat OSGI_FORMAT; + + /** + * The predefined OSGi format that is used when parsing raw + * versions. + */ + public static final VersionFormat RAW_FORMAT; + + static { + try { + VersionFormatParser parser = new VersionFormatParser(); + OSGI_FORMAT = new VersionFormat(parser.compile(OSGI_FORMAT_STRING, 0, OSGI_FORMAT_STRING.length())); + formatCache.put(OSGI_FORMAT_STRING, OSGI_FORMAT); + RAW_FORMAT = new RawFormat(parser.compile(RAW_FORMAT_STRING, 0, RAW_FORMAT_STRING.length())); + formatCache.put(RAW_FORMAT_STRING, RAW_FORMAT); + } catch (VersionFormatException e) { + // If this happens, something is wrong with the actual + // implementation of the FormatCompiler. + // + throw new ExceptionInInitializerError(e); + } + } + + /** + * Compile a version format string into a compiled format. This method is + * shorthand for:
    CompiledFormat.compile(format, 0, format.length())
    . + * + * @param format The format to compile. + * @return The compiled format + * @throws VersionFormatException If the format could not be compiled + */ + public static IVersionFormat compile(String format) throws VersionFormatException { + return compile(format, 0, format.length()); + } + + /** + * Compile a version format string into a compiled format. The parsing starts + * at position start and ends at position end. The returned format is cached so + * subsequent calls to this method using the same format string will yield the + * same compiled format instance. + * + * @param format The format string to compile. + * @param start Start position in the format string + * @param end End position in the format string + * @return The compiled format + * @throws VersionFormatException If the format could not be compiled + */ + public static VersionFormat compile(String format, int start, int end) throws VersionFormatException { + String fmtString = format.substring(start, end).intern(); + synchronized (fmtString) { + VersionFormat fmt = formatCache.get(fmtString); + if (fmt == null) { + VersionFormatParser parser = new VersionFormatParser(); + fmt = new VersionFormat(parser.compile(format, start, end)); + formatCache.put(fmtString, fmt); + } + return fmt; + } + } + + /** + * Parse a version string using the {@link #RAW_FORMAT} parser. + * + * @param version The version to parse. + * @param originalFormat The original format to assign to the created version. Can be null. + * @param original The original version string to assign to the created version. Can be null. + * @return A created version + * @throws IllegalArgumentException If the version string could not be parsed. + */ + public static BasicVersion parseRaw(String version, IVersionFormat originalFormat, String original) { + Comparable[] padReturn = new Comparable[1]; + Comparable[] vector = RAW_FORMAT.parse(version, 0, version.length(), padReturn); + Comparable pad = padReturn[0]; + return (originalFormat == OSGI_FORMAT) ? OSGiVersion.fromVector(vector, pad) : OmniVersion.fromVector(vector, pad, originalFormat, original); + } + + static void rawToString(StringBuffer sb, boolean forRange, Comparable e) { + if (e instanceof String) { + writeQuotedString(sb, forRange, (String) e, '\'', 0, false); + } else if (e instanceof VersionVector) { + sb.append('<'); + ((VersionVector) e).toString(sb, forRange); + sb.append('>'); + } else + sb.append(e); + } + + /** + * Write a string within quotes. If the string is found to contain the quote, an attempt is made + * to flip quote character (single quote becomes double quote and vice versa). A string that contains + * both will be written as several adjacent quoted strings so that each string is quoted with a + * quote character that it does not contain. + * @param sb The buffer that will receive the string + * @param rangeSafe Set to true if the resulting string will be used in a range string + * and hence need to escape the range delimiter characters + * @param s The string to be written + * @param quote The quote character to start with. Must be the single or double quote character. + * @param startPos The start position + * @param didFlip True if the call is recursive and thus, cannot switch quotes in the first string. + */ + private static void writeQuotedString(StringBuffer sb, boolean rangeSafe, String s, char quote, int startPos, boolean didFlip) { + int quotePos = sb.length(); + sb.append(quote); + boolean otherSeen = false; + int top = s.length(); + for (int idx = startPos; idx < top; ++idx) { + char c = s.charAt(idx); + if (c == '\'' || c == '"') { + if (c == quote) { + char otherQuote = quote == '\'' ? '"' : '\''; + if (didFlip || otherSeen) { + // We can only flip once + sb.append(quote); + writeQuotedString(sb, rangeSafe, s, otherQuote, idx, true); + return; + } + quote = otherQuote; + sb.setCharAt(quotePos, quote); + didFlip = true; + } else + otherSeen = true; + } + if (rangeSafe && (c == '\\' || c == '[' || c == '(' || c == ']' || c == ')' || c == ',' || c <= ' ')) + sb.append('\\'); + sb.append(c); + } + sb.append(quote); + } + + private String fmtString; + + private final Fragment topFragment; + + VersionFormat(Fragment topFragment) { + this.topFragment = topFragment; + } + + TreeInfo createInfo(int start) { + return new TreeInfo(topFragment, start); + } + + public boolean equals(Object o) { + return this == o || o instanceof VersionFormat && toString().equals(o.toString()); + } + + public int hashCode() { + return 11 * toString().hashCode(); + } + + public Version parse(String version) { + Comparable[] padReturn = new Comparable[1]; + Comparable[] vector = parse(version, 0, version.length(), padReturn); + Comparable pad = padReturn[0]; + return (this == OSGI_FORMAT) ? OSGiVersion.fromVector(vector, pad) : OmniVersion.fromVector(vector, pad, this, version); + } + + Comparable[] parse(String version, int start, int maxPos, Comparable[] padReturn) { + if (start == maxPos) + throw new IllegalArgumentException(NLS.bind(Messages.format_0_unable_to_parse_empty_version, this, version.substring(start, maxPos))); + TreeInfo info = new TreeInfo(topFragment, start); + ArrayList> entries = new ArrayList>(); + if (!(topFragment.parse(entries, version, maxPos, info) && info.getPosition() == maxPos)) + throw new IllegalArgumentException(NLS.bind(Messages.format_0_unable_to_parse_1, this, version.substring(start, maxPos))); + padReturn[0] = VersionParser.removeRedundantTrail(entries, info.getPadValue()); + return entries.toArray(new Comparable[entries.size()]); + } + + // Preserve cache during deserialization + private Object readResolve() { + synchronized (formatCache) { + String string = toString(); + VersionFormat fmt = formatCache.put(string, this); + if (fmt == null) + fmt = this; + else + // Put old format back + formatCache.put(string, fmt); + return fmt; + } + } + + /** + * Returns the string representation of this compiled format + */ + public synchronized String toString() { + if (fmtString == null) { + StringBuffer sb = new StringBuffer(); + toString(sb); + } + return fmtString; + } + + public synchronized void toString(StringBuffer sb) { + if (fmtString != null) + sb.append(fmtString); + else { + int start = sb.length(); + sb.append("format"); //$NON-NLS-1$ + if (topFragment.getPadValue() != null) { + sb.append('('); + topFragment.toString(sb); + sb.append(')'); + } else + topFragment.toString(sb); + fmtString = sb.substring(start); + } + } +} + +class RawFormat extends VersionFormat { + private static final long serialVersionUID = -6070590518921019745L; + + RawFormat(Fragment topFragment) { + super(topFragment); + } + + /** + * Parse but do not assign this format as the Version format nor the version + * string as the original. + */ + public Version parse(String version, int start, int maxPos) { + Comparable[] padReturn = new Comparable[1]; + Comparable[] vector = parse(version, start, maxPos, padReturn); + return OmniVersion.fromVector(vector, padReturn[0], null, null); + } + + // Preserve singleton when deserialized + private Object readResolve() { + return RAW_FORMAT; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionFormatParser.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionFormatParser.java new file mode 100644 index 000000000..83170c9a7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionFormatParser.java @@ -0,0 +1,1548 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata; + +import org.eclipse.equinox.p2.metadata.VersionFormatException; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import org.eclipse.equinox.internal.p2.metadata.VersionFormat.TreeInfo; +import org.eclipse.osgi.util.NLS; + +/** + * This is the Omni Version Format parser. It will parse a version format in string form + * into a group of {@link VersionFormatParser.Fragment} elements. That group, wrapped in a + * {@link VersionFormat}, becomes the parser for versions corresponding to the format. + * + * The class is not intended to included in a public API. Instead VersionFormats should + * be created using {@link VersionFormat#parse(String)} + * + */ +class VersionFormatParser { + + static class Instructions { + char[] characters = null; + Comparable defaultValue = null; + char oppositeTranslationChar = 0; + int oppositeTranslationRepeat = 0; + boolean ignore = false; + boolean inverted = false; + Comparable padValue = null; + int rangeMax = Integer.MAX_VALUE; + int rangeMin = 0; + } + + static final Qualifier EXACT_ONE_QUALIFIER = new Qualifier(1, 1); + + static final Qualifier ONE_OR_MANY_QUALIFIER = new Qualifier(1, Integer.MAX_VALUE); + + static final Qualifier ZERO_OR_MANY_QUALIFIER = new Qualifier(0, Integer.MAX_VALUE); + + static final Qualifier ZERO_OR_ONE_QUALIFIER = new Qualifier(0, 1); + + /** + * Represents one fragment of a format (i.e. auto, number, string, delimiter, etc.) + */ + static abstract class Fragment implements Serializable { + private static final long serialVersionUID = 4109185333058622681L; + + private final Qualifier qualifier; + + Fragment(Qualifier qualifier) { + this.qualifier = qualifier; + } + + public final boolean equals(Object f) { + return f == this || getClass().equals(f.getClass()) && qualifier.equals(((Fragment) f).qualifier); + } + + public final int hashCode() { + return 11 * qualifier.hashCode(); + } + + public boolean isGroup() { + return false; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + toString(sb); + return sb.toString(); + } + + Comparable getDefaultValue() { + return null; + } + + Fragment getFirstLeaf() { + return this; + } + + Comparable getPadValue() { + return null; + } + + Qualifier getQualifier() { + return qualifier; + } + + boolean parse(List> segments, String version, int maxPos, TreeInfo info) { + return qualifier.parse(new Fragment[] {this}, 0, segments, version, maxPos, info); + } + + abstract boolean parseOne(List> segments, String version, int maxPos, TreeInfo info); + + void setDefaults(List> segments) { + // No-op at this level + } + + void toString(StringBuffer sb) { + if (!(qualifier == VersionFormatParser.EXACT_ONE_QUALIFIER || (qualifier == VersionFormatParser.ZERO_OR_ONE_QUALIFIER && this.isGroup()))) + qualifier.toString(sb); + } + } + + /** + * Specifies the min and max occurrences of a fragment + */ + static class Qualifier implements Serializable { + private static final long serialVersionUID = 7494021832824671685L; + + private final int max; + private final int min; + + Qualifier(int min, int max) { + this.min = min; + this.max = max; + } + + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof Qualifier)) + return false; + Qualifier oq = (Qualifier) o; + return min == oq.min && max == oq.max; + } + + public int hashCode() { + return 31 * min + 67 * max; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + toString(sb); + return sb.toString(); + } + + int getMax() { + return max; + } + + int getMin() { + return min; + } + + boolean parse(Fragment[] fragments, int fragIdx, List> segments, String version, int maxPos, TreeInfo info) { + Fragment fragment = fragments[fragIdx++]; + int idx = 0; + + // Do the required parsing. I.e. iterate this fragment + // min number of times. + // + for (; idx < min; ++idx) + if (!fragment.parseOne(segments, version, maxPos, info)) + return false; + + for (; idx < max; ++idx) { + // We are greedy. Continue parsing until we get an exception + // and remember the state before each parse is performed. + // + info.pushState(segments.size(), fragment); + if (!fragment.parseOne(segments, version, maxPos, info)) { + info.popState(segments, fragment); + break; + } + } + int maxParsed = idx; + + for (;;) { + // Pad with default values unless the max is unbounded + // + if (idx < max) { + if (max != Integer.MAX_VALUE) { + for (; idx < max; ++idx) + fragment.setDefaults(segments); + } + } else { + if (fragment instanceof StringFragment) { + // Check for translations if we default to for MINS or MAXS + StringFragment stringFrag = (StringFragment) fragment; + Comparable opposite = stringFrag.getOppositeDefaultValue(); + if (opposite != null) { + idx = segments.size() - 1; + if (stringFrag.isOppositeTranslation(segments.get(idx))) + segments.set(idx, opposite); + } + } + } + + if (fragIdx == fragments.length) + // We are the last segment + // + return true; + + // Try to parse the next segment. If it fails, pop the state of + // this segment (or a child thereof) and try again + // + if (fragments[fragIdx].getQualifier().parse(fragments, fragIdx, segments, version, maxPos, info)) + return true; + + // Be less greedy, step back one position and try again. + // + if (maxParsed <= min) + // We have no more states to pop. Tell previous that we failed. + // + return false; + + info.popState(segments, fragment); + idx = --maxParsed; // segments now have room for one more default value + } + } + + void toString(StringBuffer sb) { + if (min == 0) { + if (max == 1) + sb.append('?'); + else if (max == Integer.MAX_VALUE) + sb.append('*'); + else { + sb.append('{'); + sb.append(min); + sb.append(','); + sb.append(max); + sb.append('}'); + } + } else if (max == Integer.MAX_VALUE) { + if (min == 1) + sb.append('+'); + else { + sb.append('{'); + sb.append(min); + sb.append(",}"); //$NON-NLS-1$ + } + } else { + sb.append('{'); + sb.append(min); + if (min != max) { + sb.append(','); + sb.append(max); + } + sb.append('}'); + } + } + + // Preserve singleton when deserialized + private Object readResolve() { + Qualifier q = this; + if (min == 0) { + if (max == 1) + q = VersionFormatParser.ZERO_OR_ONE_QUALIFIER; + else if (max == Integer.MAX_VALUE) + q = VersionFormatParser.ZERO_OR_MANY_QUALIFIER; + } else if (min == 1) { + if (max == 1) + q = VersionFormatParser.EXACT_ONE_QUALIFIER; + else if (max == Integer.MAX_VALUE) + q = VersionFormatParser.ONE_OR_MANY_QUALIFIER; + } + return q; + } + } + + private static class AutoFragment extends RangeFragment { + private static final long serialVersionUID = -1016534328164247755L; + + AutoFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { + super(instr, qualifier); + } + + boolean parseOne(List> segments, String version, int maxPos, TreeInfo info) { + int pos = info.getPosition(); + maxPos = checkRange(pos, maxPos); + if (maxPos < 0) + return false; + + char c = version.charAt(pos); + if (VersionParser.isDigit(c) && isAllowed(c)) { + // Parse to next non-digit + // + int start = pos; + int value = c - '0'; + while (++pos < maxPos) { + c = version.charAt(pos); + if (!(VersionParser.isDigit(c) && isAllowed(c))) + break; + value *= 10; + value += (c - '0'); + } + int len = pos - start; + if (rangeMin > len || len > rangeMax) + return false; + + if (!isIgnored()) + segments.add(VersionParser.valueOf(value)); + info.setPosition(pos); + return true; + } + + if (!(VersionParser.isLetter(c) && isAllowed(c))) + return false; + + // Parse to next non-letter or next delimiter + // + int start = pos++; + for (; pos < maxPos; ++pos) { + c = version.charAt(pos); + if (!(VersionParser.isLetter(c) && isAllowed(c))) + break; + } + int len = pos - start; + if (rangeMin > len || len > rangeMax) + return false; + + if (!isIgnored()) + segments.add(version.substring(start, pos)); + info.setPosition(pos); + return true; + } + + void toString(StringBuffer sb) { + sb.append('a'); + super.toString(sb); + } + } + + private static class DelimiterFragment extends Fragment { + private static final long serialVersionUID = 8173654376143370605L; + private final char[] delimChars; + private final boolean inverted; + + DelimiterFragment(VersionFormatParser.Instructions ep, Qualifier qualifier) { + super(qualifier); + if (ep == null) { + delimChars = null; + inverted = false; + } else { + inverted = ep.inverted; + delimChars = ep.characters; + } + } + + boolean isMatch(String version, int pos) { + char c = version.charAt(pos); + if (delimChars != null) { + for (int idx = 0; idx < delimChars.length; ++idx) + if (c == delimChars[idx]) + return !inverted; + return inverted; + } else if (VersionParser.isLetterOrDigit(c)) + return false; + + return true; + } + + boolean parseOne(List> segments, String version, int maxPos, TreeInfo info) { + int pos = info.getPosition(); + if (pos < maxPos && isMatch(version, pos)) { + // Just swallow, a delimiter does not contribute to the vector. + // + info.setPosition(pos + 1); + return true; + } + return false; + } + + void toString(StringBuffer sb) { + sb.append('d'); + if (delimChars != null) + appendCharacterRange(sb, delimChars, inverted); + super.toString(sb); + } + } + + static void appendCharacterRange(StringBuffer sb, char[] range, boolean inverted) { + sb.append('='); + sb.append('['); + if (inverted) + sb.append('^'); + int top = range.length; + for (int idx = 0; idx < top; ++idx) { + char b = range[idx]; + if (b == '\\' || b == ']' || (b == '-' && idx + 1 < top)) + sb.append('\\'); + + sb.append(b); + int ndx = idx + 1; + if (ndx + 2 < top) { + char c = b; + for (; ndx < top; ++ndx) { + char n = range[ndx]; + if (c + 1 != n) + break; + c = n; + } + if (ndx <= idx + 3) + continue; + + sb.append('-'); + if (c == '\\' || c == ']' || (c == '-' && idx + 1 < top)) + sb.append('\\'); + sb.append(c); + idx = ndx - 1; + } + } + sb.append(']'); + sb.append(';'); + } + + static Fragment createAutoFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { + return new AutoFragment(instr, qualifier); + } + + static Fragment createDelimiterFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { + return new DelimiterFragment(instr, qualifier); + } + + static Fragment createGroupFragment(VersionFormatParser.Instructions instr, Qualifier qualifier, Fragment[] fragments, boolean array) { + return new GroupFragment(instr, qualifier, fragments, array); + } + + static Fragment createLiteralFragment(Qualifier qualifier, String literal) { + return new LiteralFragment(qualifier, literal); + } + + static Fragment createNumberFragment(VersionFormatParser.Instructions instr, Qualifier qualifier, boolean signed) { + return new NumberFragment(instr, qualifier, signed); + } + + static Fragment createPadFragment(Qualifier qualifier) { + return new PadFragment(qualifier); + } + + static Fragment createQuotedFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { + return new QuotedFragment(instr, qualifier); + } + + static Fragment createRawFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { + return new RawFragment(instr, qualifier); + } + + static Fragment createStringFragment(VersionFormatParser.Instructions instr, Qualifier qualifier, boolean unbound) { + return new StringFragment(instr, qualifier, unbound); + } + + static boolean equalsAllowNull(Object a, Object b) { + return (a == null) ? (b == null) : (b != null && a.equals(b)); + } + + private static abstract class ElementFragment extends Fragment { + private static final long serialVersionUID = -6834591415456539713L; + private final Comparable defaultValue; + private final boolean ignored; + private final Comparable padValue; + + ElementFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { + super(qualifier); + if (instr != null) { + ignored = instr.ignore; + defaultValue = instr.defaultValue; + padValue = instr.padValue; + } else { + ignored = false; + defaultValue = null; + padValue = null; + } + } + + Comparable getDefaultValue() { + return defaultValue; + } + + Comparable getPadValue() { + return padValue; + } + + boolean isIgnored() { + return ignored; + } + + void setDefaults(List> segments) { + Comparable defaultVal = getDefaultValue(); + if (defaultVal != null) + segments.add(defaultVal); + } + + void toString(StringBuffer sb) { + if (ignored) { + sb.append('='); + sb.append('!'); + sb.append(';'); + } + if (defaultValue != null) { + sb.append('='); + VersionFormat.rawToString(sb, false, defaultValue); + sb.append(';'); + } + if (padValue != null) { + sb.append('='); + sb.append('p'); + VersionFormat.rawToString(sb, false, padValue); + sb.append(';'); + } + super.toString(sb); + } + } + + private static class GroupFragment extends ElementFragment { + private static final long serialVersionUID = 9219978678087669699L; + private final boolean array; + private final Fragment[] fragments; + + GroupFragment(VersionFormatParser.Instructions instr, Qualifier qualifier, Fragment[] fragments, boolean array) { + super(instr, qualifier); + this.fragments = fragments; + this.array = array; + } + + public boolean isGroup() { + return !array; + } + + Fragment getFirstLeaf() { + return fragments[0].getFirstLeaf(); + } + + boolean parseOne(List> segments, String version, int maxPos, TreeInfo info) { + if (array) { + ArrayList> subSegs = new ArrayList>(); + boolean success = fragments[0].getQualifier().parse(fragments, 0, subSegs, version, maxPos, info); + if (!success || subSegs.isEmpty()) + return false; + + Comparable padValue = info.getPadValue(); + if (padValue != null) + info.setPadValue(null); // Prevent outer group from getting this. + else + padValue = getPadValue(); + + padValue = VersionParser.removeRedundantTrail(segments, padValue); + segments.add(new VersionVector(subSegs.toArray(new Comparable[subSegs.size()]), padValue)); + return true; + } + + if (fragments[0].getQualifier().parse(fragments, 0, segments, version, maxPos, info)) { + Comparable padValue = getPadValue(); + if (padValue != null) + info.setPadValue(padValue); + return true; + } + return false; + } + + void setDefaults(List> segments) { + Comparable dflt = getDefaultValue(); + if (dflt != null) { + // A group default overrides any defaults within the + // group fragments + super.setDefaults(segments); + } else { + // Assign defaults for all fragments + for (int idx = 0; idx < fragments.length; ++idx) + fragments[idx].setDefaults(segments); + } + } + + void toString(StringBuffer sb) { + if (array) { + sb.append('<'); + for (int idx = 0; idx < fragments.length; ++idx) + fragments[idx].toString(sb); + sb.append('>'); + } else { + if (getQualifier() == VersionFormatParser.ZERO_OR_ONE_QUALIFIER) { + sb.append('['); + for (int idx = 0; idx < fragments.length; ++idx) + fragments[idx].toString(sb); + sb.append(']'); + } else { + sb.append('('); + for (int idx = 0; idx < fragments.length; ++idx) + fragments[idx].toString(sb); + sb.append(')'); + } + } + super.toString(sb); + } + } + + private static class LiteralFragment extends Fragment { + private static final long serialVersionUID = 6210696245839471802L; + private final String string; + + LiteralFragment(Qualifier qualifier, String string) { + super(qualifier); + this.string = string; + } + + boolean parseOne(List> segments, String version, int maxPos, TreeInfo info) { + int pos = info.getPosition(); + int litLen = string.length(); + if (pos + litLen > maxPos) + return false; + + for (int idx = 0; idx < litLen; ++idx, ++pos) { + if (string.charAt(idx) != version.charAt(pos)) + return false; + } + info.setPosition(pos); + return true; + } + + void toString(StringBuffer sb) { + String str = string; + if (str.length() != 1) { + sb.append('\''); + VersionFormatParser.toStringEscaped(sb, str, "\'"); //$NON-NLS-1$ + sb.append('\''); + } else { + char c = str.charAt(0); + switch (c) { + case '\'' : + case '\\' : + case '<' : + case '[' : + case '(' : + case '{' : + case '?' : + case '*' : + case '+' : + case '=' : + sb.append('\\'); + sb.append(c); + break; + default : + if (VersionParser.isLetterOrDigit(c)) { + sb.append('\\'); + sb.append(c); + } else + sb.append(c); + } + } + super.toString(sb); + } + } + + private static class NumberFragment extends RangeFragment { + private static final long serialVersionUID = -8552754381106711507L; + private final boolean signed; + + NumberFragment(VersionFormatParser.Instructions instr, Qualifier qualifier, boolean signed) { + super(instr, qualifier); + this.signed = signed; + } + + boolean parseOne(List> segments, String version, int maxPos, TreeInfo info) { + int pos = info.getPosition(); + maxPos = checkRange(pos, maxPos); + if (maxPos < 0) + return false; + + // Parse to next non-digit + // + int start = pos; + int value; + + char c = version.charAt(pos); + if (signed || characters != null) { + boolean negate = false; + if (signed && c == '-' && pos + 1 < maxPos) { + negate = true; + c = version.charAt(++pos); + } + + if (!(c >= '0' && c <= '9' && isAllowed(c))) + return false; + + // Parse to next non-digit + // + value = c - '0'; + while (++pos < maxPos) { + c = version.charAt(pos); + if (!(c >= '0' && c <= '9' && isAllowed(c))) + break; + value *= 10; + value += (c - '0'); + } + if (negate) + value = -value; + } else { + if (c < '0' || c > '9') + return false; + + // Parse to next non-digit + // + value = c - '0'; + while (++pos < maxPos) { + c = version.charAt(pos); + if (c < '0' || c > '9') + break; + value *= 10; + value += (c - '0'); + } + } + + int len = pos - start; + if (rangeMin > len || len > rangeMax) + return false; + + if (!isIgnored()) + segments.add(VersionParser.valueOf(value)); + info.setPosition(pos); + return true; + } + + void toString(StringBuffer sb) { + sb.append(signed ? 'N' : 'n'); + super.toString(sb); + } + } + + private static class PadFragment extends ElementFragment { + private static final long serialVersionUID = 5052010199974380170L; + + PadFragment(Qualifier qualifier) { + super(null, qualifier); + } + + boolean parseOne(List> segments, String version, int maxPos, TreeInfo info) { + int pos = info.getPosition(); + if (pos >= maxPos || version.charAt(pos) != 'p') + return false; + + int[] position = new int[] {++pos}; + Comparable v = VersionParser.parseRawElement(version, position, maxPos); + if (v == null) + return false; + + if (!isIgnored()) + info.setPadValue(v); + info.setPosition(position[0]); + return true; + } + + void toString(StringBuffer sb) { + sb.append('p'); + super.toString(sb); + } + } + + private static class QuotedFragment extends RangeFragment { + private static final long serialVersionUID = 6057751133533608969L; + + QuotedFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { + super(instr, qualifier); + } + + boolean parseOne(List> segments, String version, int maxPos, TreeInfo info) { + int pos = info.getPosition(); + if (pos >= maxPos) + return false; + + char endQuote; + char quote = version.charAt(pos); + switch (quote) { + case '<' : + endQuote = '>'; + break; + case '{' : + endQuote = '}'; + break; + case '(' : + endQuote = ')'; + break; + case '[' : + endQuote = ']'; + break; + case '>' : + endQuote = '<'; + break; + case '}' : + endQuote = '{'; + break; + case ')' : + endQuote = '('; + break; + case ']' : + endQuote = '['; + break; + default : + if (VersionParser.isLetterOrDigit(quote)) + return false; + endQuote = quote; + } + int start = ++pos; + char c = version.charAt(pos); + while (c != endQuote && isAllowed(c) && ++pos < maxPos) + c = version.charAt(pos); + + if (c != endQuote || rangeMin > pos - start) + // End quote not found + return false; + + int len = pos - start; + if (rangeMin > len || len > rangeMax) + return false; + + if (!isIgnored()) + segments.add(version.substring(start, pos)); + info.setPosition(++pos); // Skip quote + return true; + } + + void toString(StringBuffer sb) { + sb.append('q'); + super.toString(sb); + } + } + + private static abstract class RangeFragment extends ElementFragment { + private static final long serialVersionUID = -6680402803630334708L; + final char[] characters; + final boolean inverted; + final int rangeMax; + final int rangeMin; + + RangeFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { + super(instr, qualifier); + if (instr == null) { + characters = null; + inverted = false; + rangeMin = 0; + rangeMax = Integer.MAX_VALUE; + } else { + characters = instr.characters; + inverted = instr.inverted; + rangeMin = instr.rangeMin; + rangeMax = instr.rangeMax; + } + } + + /** + * Checks that pos is at a valid character position, that we + * have at least the required minimum characters left, and + * if a maximum number of characters is set, limits the + * returned value to a maxPos that reflects that maximum. + * @param pos the current position + * @param maxPos the current maxPos + * @return maxPos, possibly limited by rangeMax + */ + int checkRange(int pos, int maxPos) { + int check = pos; + if (rangeMin == 0) + check++; // Verify one character + else + check += rangeMin; + + if (check > maxPos) + // Less then min characters left + maxPos = -1; + else { + if (rangeMax != Integer.MAX_VALUE) { + check = pos + rangeMax; + if (check < maxPos) + maxPos = check; + } + } + return maxPos; + } + + boolean isAllowed(char c) { + char[] crs = characters; + if (crs != null) { + int idx = crs.length; + while (--idx >= 0) + if (c == crs[idx]) + return !inverted; + return inverted; + } + return true; + } + + void toString(StringBuffer sb) { + if (characters != null) + appendCharacterRange(sb, characters, inverted); + if (rangeMin != 0 || rangeMax != Integer.MAX_VALUE) { + sb.append('='); + sb.append('{'); + sb.append(rangeMin); + if (rangeMin != rangeMax) { + sb.append(','); + if (rangeMax != Integer.MAX_VALUE) + sb.append(rangeMax); + } + sb.append('}'); + sb.append(';'); + } + super.toString(sb); + } + } + + private static class RawFragment extends ElementFragment { + private static final long serialVersionUID = 4107448125256042602L; + + RawFragment(VersionFormatParser.Instructions processing, Qualifier qualifier) { + super(processing, qualifier); + } + + boolean parseOne(List> segments, String version, int maxPos, TreeInfo info) { + int[] position = new int[] {info.getPosition()}; + Comparable v = VersionParser.parseRawElement(version, position, maxPos); + if (v == null) + return false; + + if (!isIgnored()) + segments.add(v); + info.setPosition(position[0]); + return true; + } + + void toString(StringBuffer sb) { + sb.append('r'); + super.toString(sb); + } + } + + private static class StringFragment extends RangeFragment { + private static final long serialVersionUID = -2265924553606430164L; + final boolean anyChar; + private final char oppositeTranslationChar; + private final int oppositeTranslationRepeat; + + StringFragment(VersionFormatParser.Instructions instr, Qualifier qualifier, boolean noLimit) { + super(instr, qualifier); + anyChar = noLimit; + char otc = 0; + int otr = 0; + if (instr != null) { + otc = instr.oppositeTranslationChar; + otr = instr.oppositeTranslationRepeat; + if (instr.defaultValue == VersionVector.MINS_VALUE) { + if (otc == 0) + otc = 'z'; + if (otr == 0) + otr = 3; + } else if (instr.defaultValue == VersionVector.MAXS_VALUE) { + if (otc == 0) + otc = '-'; + otr = 1; + } + } + oppositeTranslationChar = otc; + oppositeTranslationRepeat = otr; + } + + Comparable getOppositeDefaultValue() { + Comparable dflt = getDefaultValue(); + return dflt == VersionVector.MAXS_VALUE ? VersionVector.MINS_VALUE : (dflt == VersionVector.MINS_VALUE ? VersionVector.MAXS_VALUE : null); + } + + public boolean isOppositeTranslation(Object val) { + if (val instanceof String) { + String str = (String) val; + int idx = oppositeTranslationRepeat; + if (str.length() == idx) { + while (--idx >= 0) + if (str.charAt(idx) != oppositeTranslationChar) + break; + return idx < 0; + } + } + return false; + } + + boolean parseOne(List> segments, String version, int maxPos, TreeInfo info) { + int pos = info.getPosition(); + maxPos = checkRange(pos, maxPos); + if (maxPos < 0) + return false; + + // Parse to next delimiter or end of string + // + int start = pos; + if (characters != null) { + if (anyChar) { + // Swallow everything that matches the allowed characters + for (; pos < maxPos; ++pos) { + if (!isAllowed(version.charAt(pos))) + break; + } + } else { + // Swallow letters that matches the allowed characters + for (; pos < maxPos; ++pos) { + char c = version.charAt(pos); + if (!(VersionParser.isLetter(c) && isAllowed(c))) + break; + } + } + } else { + if (anyChar) + // Swallow all characters + pos = maxPos; + else { + // Swallow all letters + for (; pos < maxPos; ++pos) { + if (!VersionParser.isLetter(version.charAt(pos))) + break; + } + } + } + int len = pos - start; + if (len == 0 || rangeMin > len || len > rangeMax) + return false; + + if (!isIgnored()) + segments.add(version.substring(start, pos)); + info.setPosition(pos); + return true; + } + + void toString(StringBuffer sb) { + sb.append(anyChar ? 'S' : 's'); + super.toString(sb); + } + } + + private int current; + + private List currentList; + + private int eos; + + private String format; + + private int start; + + Fragment compile(String fmt, int pos, int maxPos) throws VersionFormatException { + format = fmt; + if (start >= maxPos) + throw new VersionFormatException(Messages.format_is_empty); + + start = pos; + current = pos; + eos = maxPos; + currentList = new ArrayList(); + while (current < eos) + parseFragment(); + + Fragment topFrag; + switch (currentList.size()) { + case 0 : + throw new VersionFormatException(Messages.format_is_empty); + case 1 : + Fragment frag = currentList.get(0); + if (frag.isGroup()) { + topFrag = frag; + break; + } + // Fall through to default + default : + topFrag = createGroupFragment(null, EXACT_ONE_QUALIFIER, currentList.toArray(new Fragment[currentList.size()]), false); + } + currentList = null; + return topFrag; + } + + private void assertChar(char expected) throws VersionFormatException { + if (current >= eos) + throw formatException(NLS.bind(Messages.premature_end_of_format_expected_0, new String(new char[] {expected}))); + + char c = format.charAt(current); + if (c != expected) + throw formatException(c, new String(new char[] {expected})); + ++current; + } + + private VersionFormatException formatException(char found, String expected) { + return formatException(new String(new char[] {found}), expected); + } + + private VersionFormatException formatException(String message) { + return new VersionFormatException(NLS.bind(Messages.syntax_error_in_version_format_0_1_2, new Object[] {format.substring(start, eos), new Integer(current), message})); + } + + private VersionFormatException formatException(String found, String expected) { + return new VersionFormatException(NLS.bind(Messages.syntax_error_in_version_format_0_1_found_2_expected_3, new Object[] {format.substring(start, eos), new Integer(current), found, expected})); + } + + private VersionFormatException illegalControlCharacter(char c) { + return formatException(NLS.bind(Messages.illegal_character_encountered_ascii_0, VersionParser.valueOf(c))); + } + + private String parseAndConsiderEscapeUntil(char endChar) throws VersionFormatException { + StringBuffer sb = new StringBuffer(); + while (current < eos) { + char c = format.charAt(current++); + if (c == endChar) + break; + + if (c < 32) + throw illegalControlCharacter(c); + + if (c == '\\') { + if (current == eos) + throw formatException(Messages.EOS_after_escape); + c = format.charAt(current++); + if (c < 32) + throw illegalControlCharacter(c); + } + sb.append(c); + } + return sb.toString(); + } + + private void parseAuto() throws VersionFormatException { + VersionFormatParser.Instructions ep = parseProcessing(); + if (ep != null) { + if (ep.padValue != null) + throw formatException(Messages.auto_can_not_have_pad_value); + } + currentList.add(createAutoFragment(ep, parseQualifier())); + } + + private void parseBracketGroup() throws VersionFormatException { + List saveList = currentList; + currentList = new ArrayList(); + while (current < eos && format.charAt(current) != ']') + parseFragment(); + + if (current == eos) + throw formatException(NLS.bind(Messages.premature_end_of_format_expected_0, "]")); //$NON-NLS-1$ + + ++current; + VersionFormatParser.Instructions ep = parseProcessing(); + saveList.add(createGroupFragment(ep, ZERO_OR_ONE_QUALIFIER, currentList.toArray(new Fragment[currentList.size()]), false)); + currentList = saveList; + } + + private void parseCharacterGroup(VersionFormatParser.Instructions ep) throws VersionFormatException { + assertChar('['); + + StringBuffer sb = new StringBuffer(); + outer: for (; current < eos; ++current) { + char c = format.charAt(current); + switch (c) { + case '\\' : + if (current + 1 < eos) { + sb.append(format.charAt(++current)); + continue; + } + throw formatException(Messages.premature_end_of_format); + case '^' : + if (sb.length() == 0) + ep.inverted = true; + else + sb.append(c); + continue; + case ']' : + break outer; + case '-' : + if (sb.length() > 0 && current + 1 < eos) { + char rangeEnd = format.charAt(++current); + if (rangeEnd == ']') { + // Use dash verbatim when last in range + sb.append(c); + break outer; + } + + char rangeStart = sb.charAt(sb.length() - 1); + if (rangeEnd < rangeStart) + throw formatException(Messages.negative_character_range); + while (++rangeStart <= rangeEnd) + sb.append(rangeStart); + continue; + } + // Fall through to default + default : + if (c < 32) + throw illegalControlCharacter(c); + sb.append(c); + } + } + assertChar(']'); + int top = sb.length(); + char[] chars = new char[top]; + sb.getChars(0, top, chars, 0); + ep.characters = chars; + } + + private void parseDelimiter() throws VersionFormatException { + VersionFormatParser.Instructions ep = parseProcessing(); + if (ep != null) { + if (ep.rangeMin != 0 || ep.rangeMax != Integer.MAX_VALUE) + throw formatException(Messages.delimiter_can_not_have_range); + if (ep.ignore) + throw formatException(Messages.delimiter_can_not_be_ignored); + if (ep.defaultValue != null) + throw formatException(Messages.delimiter_can_not_have_default_value); + if (ep.padValue != null) + throw formatException(Messages.delimiter_can_not_have_pad_value); + } + currentList.add(createDelimiterFragment(ep, parseQualifier())); + } + + private void parseFragment() throws VersionFormatException { + if (current == eos) + throw formatException(Messages.premature_end_of_format); + char c = format.charAt(current++); + switch (c) { + case '(' : + parseGroup(false); + break; + case '<' : + parseGroup(true); + break; + case '[' : + parseBracketGroup(); + break; + case 'a' : + parseAuto(); + break; + case 'r' : + parseRaw(); + break; + case 'n' : + parseNumber(false); + break; + case 'N' : + parseNumber(true); + break; + case 's' : + parseString(false); + break; + case 'S' : + parseString(true); + break; + case 'd' : + parseDelimiter(); + break; + case 'q' : + parseQuotedString(); + break; + case 'p' : + parsePad(); + break; + default : + parseLiteral(c); + } + } + + private void parseGroup(boolean array) throws VersionFormatException { + List saveList = currentList; + currentList = new ArrayList(); + char expectedEnd = array ? '>' : ')'; + while (current < eos && format.charAt(current) != expectedEnd) + parseFragment(); + assertChar(expectedEnd); + + VersionFormatParser.Instructions ep = parseProcessing(); + if (ep != null) { + if (ep.characters != null) + throw formatException(Messages.array_can_not_have_character_group); + if (ep.rangeMax != Integer.MAX_VALUE && ep.padValue != null) { + throw formatException(Messages.cannot_combine_range_upper_bound_with_pad_value); + } + } + + if (currentList.isEmpty()) + throw formatException(array ? Messages.array_can_not_be_empty : Messages.group_can_not_be_empty); + saveList.add(createGroupFragment(ep, parseQualifier(), currentList.toArray(new Fragment[currentList.size()]), array)); + currentList = saveList; + } + + private int parseIntegerLiteral() throws VersionFormatException { + if (current == eos) + throw formatException(NLS.bind(Messages.premature_end_of_format_expected_0, "")); //$NON-NLS-1$ + + char c = format.charAt(current); + if (!VersionParser.isDigit(c)) + throw formatException(c, ""); //$NON-NLS-1$ + + int value = c - '0'; + while (++current < eos) { + c = format.charAt(current); + if (!VersionParser.isDigit(c)) + break; + value *= 10; + value += (c - '0'); + } + return value; + } + + private void parseLiteral(char c) throws VersionFormatException { + String value; + switch (c) { + case '\'' : + value = parseAndConsiderEscapeUntil(c); + break; + case ')' : + case ']' : + case '{' : + case '}' : + case '?' : + case '*' : + throw formatException(c, ""); //$NON-NLS-1$ + default : + if (VersionParser.isLetterOrDigit(c)) + throw formatException(c, ""); //$NON-NLS-1$ + + if (c < 32) + throw illegalControlCharacter(c); + + if (c == '\\') { + if (current == eos) + throw formatException(Messages.EOS_after_escape); + c = format.charAt(current++); + if (c < 32) + throw illegalControlCharacter(c); + } + value = new String(new char[] {c}); + } + currentList.add(createLiteralFragment(parseQualifier(), value)); + } + + private int[] parseMinMax() throws VersionFormatException { + + int max = Integer.MAX_VALUE; + ++current; + int min = parseIntegerLiteral(); + char c = format.charAt(current); + if (c == '}') { + max = min; + if (max == 0) + throw formatException(Messages.range_max_cannot_be_zero); + ++current; + } else if (c == ',' && current + 1 < eos) { + if (format.charAt(++current) != '}') { + max = parseIntegerLiteral(); + if (max == 0) + throw formatException(Messages.range_max_cannot_be_zero); + if (max < min) + throw formatException(Messages.range_max_cannot_be_less_then_range_min); + } + assertChar('}'); + } else + throw formatException(c, "},"); //$NON-NLS-1$ + return new int[] {min, max}; + } + + private void parseNumber(boolean signed) throws VersionFormatException { + VersionFormatParser.Instructions ep = parseProcessing(); + if (ep != null) { + if (ep.padValue != null) + throw formatException(Messages.number_can_not_have_pad_value); + } + currentList.add(createNumberFragment(ep, parseQualifier(), signed)); + } + + private void parsePad() throws VersionFormatException { + currentList.add(createPadFragment(parseQualifier())); + } + + private VersionFormatParser.Instructions parseProcessing() throws VersionFormatException { + if (current >= eos) + return null; + + char c = format.charAt(current); + if (c != '=') + return null; + + VersionFormatParser.Instructions ep = new VersionFormatParser.Instructions(); + do { + current++; + parseProcessingInstruction(ep); + } while (current < eos && format.charAt(current) == '='); + return ep; + } + + private void parseProcessingInstruction(VersionFormatParser.Instructions processing) throws VersionFormatException { + if (current == eos) + throw formatException(Messages.premature_end_of_format); + + char c = format.charAt(current); + if (c == 'p') { + // =pad(); + // + if (processing.padValue != null) + throw formatException(Messages.pad_defined_more_then_once); + if (processing.ignore) + throw formatException(Messages.cannot_combine_ignore_with_other_instruction); + ++current; + processing.padValue = parseRawElement(); + } else if (c == '!') { + // =ignore; + // + if (processing.ignore) + throw formatException(Messages.ignore_defined_more_then_once); + if (processing.padValue != null || processing.characters != null || processing.rangeMin != 0 || processing.rangeMax != Integer.MAX_VALUE || processing.defaultValue != null) + throw formatException(Messages.cannot_combine_ignore_with_other_instruction); + ++current; + processing.ignore = true; + } else if (c == '[') { + // =[; + if (processing.defaultValue != null) + throw formatException(Messages.default_defined_more_then_once); + if (processing.ignore) + throw formatException(Messages.cannot_combine_ignore_with_other_instruction); + Comparable dflt = parseRawElement(); + processing.defaultValue = dflt; + if (current < eos && format.charAt(current) == '{') { + // =m{} + // =''{,} + if (++current == eos) + throw formatException(Messages.premature_end_of_format); + processing.oppositeTranslationChar = format.charAt(current++); + if (current == eos) + throw formatException(Messages.premature_end_of_format); + + if (dflt == VersionVector.MINS_VALUE) { + processing.oppositeTranslationRepeat = 3; + if (format.charAt(current) == ',') { + ++current; + processing.oppositeTranslationRepeat = parseIntegerLiteral(); + } + } else if (dflt != VersionVector.MAXS_VALUE) { + current -= 2; + throw formatException(Messages.only_max_and_empty_string_defaults_can_have_translations); + } + assertChar('}'); + } + } + assertChar(';'); + } + + private Qualifier parseQualifier() throws VersionFormatException { + if (current >= eos) + return EXACT_ONE_QUALIFIER; + + char c = format.charAt(current); + if (c == '?') { + ++current; + return ZERO_OR_ONE_QUALIFIER; + } + + if (c == '*') { + ++current; + return ZERO_OR_MANY_QUALIFIER; + } + + if (c == '+') { + ++current; + return ONE_OR_MANY_QUALIFIER; + } + + if (c != '{') + return EXACT_ONE_QUALIFIER; + + int[] minMax = parseMinMax(); + int min = minMax[0]; + int max = minMax[1]; + + // Use singletons for commonly used ranges + // + if (min == 0) { + if (max == 1) + return ZERO_OR_ONE_QUALIFIER; + if (max == Integer.MAX_VALUE) + return ZERO_OR_MANY_QUALIFIER; + } else if (min == 1) { + if (max == 1) + return EXACT_ONE_QUALIFIER; + if (max == Integer.MAX_VALUE) + return ONE_OR_MANY_QUALIFIER; + } + return new Qualifier(min, max); + } + + private void parseQuotedString() throws VersionFormatException { + VersionFormatParser.Instructions ep = parseProcessing(); + if (ep != null) { + if (ep.padValue != null) + throw formatException(Messages.string_can_not_have_pad_value); + } + currentList.add(createQuotedFragment(ep, parseQualifier())); + } + + private void parseRaw() throws VersionFormatException { + VersionFormatParser.Instructions ep = parseProcessing(); + if (ep != null) { + if (ep.padValue != null) + throw formatException(Messages.raw_element_can_not_have_pad_value); + } + currentList.add(createRawFragment(ep, parseQualifier())); + } + + private Comparable parseRawElement() throws VersionFormatException { + int[] position = new int[] {current}; + Comparable v = VersionParser.parseRawElement(format, position, eos); + if (v == null) + throw new VersionFormatException(NLS.bind(Messages.raw_element_expected_0, format)); + current = position[0]; + return v; + } + + private void parseString(boolean unlimited) throws VersionFormatException { + VersionFormatParser.Instructions ep = parseProcessing(); + if (ep != null) { + if (ep.padValue != null) + throw formatException(Messages.string_can_not_have_pad_value); + } + currentList.add(createStringFragment(ep, parseQualifier(), unlimited)); + } + + static void toStringEscaped(StringBuffer sb, String value, String escapes) { + for (int idx = 0; idx < value.length(); ++idx) { + char c = value.charAt(idx); + if (c == '\\' || escapes.indexOf(c) >= 0) + sb.append('\\'); + sb.append(c); + } + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionParser.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionParser.java new file mode 100644 index 000000000..0ef47d9bc --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionParser.java @@ -0,0 +1,388 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata; + +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionFormatException; + +import java.util.ArrayList; +import java.util.List; +import org.eclipse.osgi.util.NLS; + +/** + * The Omni Version parser. Not intended for public API. Instead use + * {@link Version#create(String)} or {@link Version#parseVersion(String)}. + * + * The class also contains some general purpose parser support methods + * + * @noextend This class is not intended to be subclassed by clients. + */ +public abstract class VersionParser { + public static final Integer ZERO_INT = new Integer(0); + + public static final Integer MAX_INT_OBJ = new Integer(Integer.MAX_VALUE); + + private static final Integer cache[] = new Integer[100]; + + static { + cache[0] = ZERO_INT; + for (int i = 1; i < cache.length; i++) + cache[i] = new Integer(i); + } + + public static Integer valueOf(int i) { + try { + return cache[i]; + } catch (ArrayIndexOutOfBoundsException e) { + return (i == Integer.MAX_VALUE) ? MAX_INT_OBJ : new Integer(i); + } + } + + static Comparable removeRedundantTrail(List> segments, Comparable padValue) { + Comparable redundantTrail; + if (padValue == null) + redundantTrail = VersionVector.MIN_VALUE; + else { + redundantTrail = padValue; + if (padValue == VersionVector.MIN_VALUE) + padValue = null; + } + + int idx = segments.size(); + while (--idx >= 0 && segments.get(idx).equals(redundantTrail)) + segments.remove(idx); + + return padValue; + } + + private VersionParser() { + // Prevent class from being instantiated + } + + /** + * Parse the version string and assing the parsed portions to the receiver. + * This method is called from the version string constructor. + * + * @param version The string to be parsed + * @param start Start position in the version string + * @param maxPos End position in the version string + * @returns a version if one indeed was parsed or null if the string + * contained only whitespace. + * @throws IllegalArgumentException if the version is malformed + */ + public static Version parse(String version, int start, int maxPos) throws IllegalArgumentException { + // trim leading and trailing whitespace + int pos = skipWhite(version, start); + maxPos = skipTrailingWhite(version, start, maxPos); + if (pos == maxPos) + return null; + + Comparable[] padReturn = new Comparable[1]; + Comparable[] vector = null; + Comparable pad = null; + VersionFormat fmt = null; + char c = version.charAt(pos); + if (isDigit(c)) { + vector = VersionFormat.OSGI_FORMAT.parse(version, pos, maxPos, padReturn); + return OSGiVersion.fromVector(vector, padReturn[0]); + } + + if (!isLetter(c)) + throw new IllegalArgumentException(); + + if (version.startsWith(Version.RAW_PREFIX, pos)) { + VersionFormat rawFmt = VersionFormat.RAW_FORMAT; + pos += 4; + + // Find ending '/' that is neither quoted or escaped + int end = maxPos; + for (int idx = pos; idx < maxPos; ++idx) { + c = version.charAt(idx); + switch (c) { + case '/' : + end = idx; + break; + case '\\' : + ++idx; + continue; + case '\'' : + case '"' : + for (++idx; idx < maxPos; ++idx) { + char e = version.charAt(idx); + if (e == c) { + break; + } + if (e == '\\') + ++idx; + } + // fall through to default + default : + continue; + } + break; + } + + vector = rawFmt.parse(version, pos, end, padReturn); + pad = padReturn[0]; + pos = end; + if (pos == maxPos) + // This was a pure raw version + // + return OmniVersion.fromVector(vector, pad, null, null); + + if (version.charAt(pos) != '/') + throw new IllegalArgumentException(NLS.bind(Messages.expected_slash_after_raw_vector_0, version.substring(start, maxPos))); + ++pos; + + if (pos == maxPos) + throw new IllegalArgumentException(NLS.bind(Messages.expected_orignal_after_slash_0, version.substring(start, maxPos))); + } + + if (version.startsWith("format(", pos)) { //$NON-NLS-1$ + // Parse the format + // + pos += 7; + try { + // Find matching ')' that is neither quoted or escaped + // + int end = findEndOfFormat(version, pos, maxPos); + fmt = VersionFormat.compile(version, pos, end); + pos = end + 1; + } catch (VersionFormatException e) { + throw new IllegalArgumentException(e.getMessage()); + } + if (pos == maxPos) { + // This was a raw version with format but no original + // + if (vector == null) + throw new IllegalArgumentException(NLS.bind(Messages.only_format_specified_0, version.substring(start, maxPos))); + return fmt == VersionFormat.OSGI_FORMAT ? OSGiVersion.fromVector(vector, pad) : OmniVersion.fromVector(vector, pad, fmt, null); + } + } + + if (fmt == null && vector == null) + throw new IllegalArgumentException(NLS.bind(Messages.neither_raw_vector_nor_format_specified_0, version.substring(start, maxPos))); + + if (version.charAt(pos) != ':') + throw new IllegalArgumentException(NLS.bind(Messages.colon_expected_before_original_version_0, version.substring(start, maxPos))); + + pos++; + if (pos == maxPos) + throw new IllegalArgumentException(NLS.bind(Messages.expected_orignal_after_colon_0, version.substring(start, maxPos))); + + if (vector == null) { + // Vector and pad must be created by parsing the original + // + vector = fmt.parse(version, pos, maxPos, padReturn); + pad = padReturn[0]; + } + return fmt == VersionFormat.OSGI_FORMAT ? OSGiVersion.fromVector(vector, pad) : OmniVersion.fromVector(vector, pad, fmt, version.substring(pos)); + } + + static boolean isDigit(char c) { + return c >= '0' && c <= '9'; + } + + public static boolean isLetter(char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); + } + + static boolean isLetterOrDigit(char c) { + return isDigit(c) || isLetter(c); + } + + public static int findEndOfFormat(String string, int pos, int maxPos) { + int end = -1; + int depth = 1; + for (int idx = pos; idx < maxPos; ++idx) { + char c = string.charAt(idx); + switch (c) { + case ')' : + if (--depth == 0) { + end = idx; + break; + } + continue; + case '(' : + ++depth; + continue; + case '\\' : + ++idx; + continue; + case '\'' : + case '"' : + for (++idx; idx < maxPos; ++idx) { + char e = string.charAt(idx); + if (e == c) { + break; + } + if (e == '\\') + ++idx; + } + // fall through to default + default : + continue; + } + break; + } + if (depth != 0) + throw new IllegalArgumentException(NLS.bind(Messages.unbalanced_format_parenthesis, string.substring(pos - 1, maxPos))); + return end; + } + + static Comparable parseRawElement(String value, int[] position, int maxPos) { + int current = position[0]; + if (current >= maxPos) + return null; + + boolean negate = false; + char c = value.charAt(current); + Comparable v; + switch (c) { + case '\'' : + case '"' : { + StringBuffer sb = new StringBuffer(); + for (;;) { + char q = c; + if (++current == maxPos) + return null; + c = value.charAt(current); + while (c != q) { + if (c < 32) + return null; + sb.append(c); + if (++current == maxPos) + return null; + c = value.charAt(current); + } + if (++current == maxPos) + break; + c = value.charAt(current); + if (c != '\'' && c != '"') + break; + } + v = sb.length() == 0 ? VersionVector.MINS_VALUE : sb.toString(); + break; + } + case '<' : { + if (++current == maxPos) + return null; + + position[0] = current; + v = parseRawVector(value, position, maxPos); + if (v == null) + return null; + current = position[0]; + break; + } + case 'm' : + v = VersionVector.MAXS_VALUE; + ++current; + break; + case 'M' : + v = VersionVector.MAX_VALUE; + ++current; + break; + case '-' : + if (++current >= maxPos) + return null; + + c = value.charAt(current); + if (c == 'M') { + ++current; + v = VersionVector.MIN_VALUE; + break; + } + negate = true; + // Fall through to default + default : { + if (isDigit(c)) { + int start = current++; + while (current < maxPos && isDigit(value.charAt(current))) + ++current; + int val = Integer.parseInt(value.substring(start, current)); + if (negate) + val = -val; + v = valueOf(val); + break; + } + return null; + } + } + position[0] = current; + return v; + } + + private static Comparable parseRawVector(String value, int[] position, int maxPos) { + int pos = position[0]; + if (pos >= maxPos) + return null; + + char c = value.charAt(pos); + if (c == '>') + return null; + + ArrayList> rawList = new ArrayList>(); + boolean padMarkerSeen = (c == 'p'); + if (padMarkerSeen) { + if (++pos >= maxPos) + return null; + position[0] = pos; + } + + Comparable pad = null; + for (;;) { + Comparable elem = parseRawElement(value, position, maxPos); + if (elem == null) + return null; + + if (padMarkerSeen) + pad = elem; + else + rawList.add(elem); + + pos = position[0]; + if (pos >= maxPos) + return null; + + c = value.charAt(pos); + position[0] = ++pos; + if (c == '>') + break; + + if (padMarkerSeen || pos >= maxPos) + return null; + + if (c == 'p') { + padMarkerSeen = true; + continue; + } + + if (c != '.') + return null; + } + pad = removeRedundantTrail(rawList, pad); + return new VersionVector(rawList.toArray(new Comparable[rawList.size()]), pad); + } + + public static int skipWhite(String string, int pos) { + int top = string.length(); + while (pos < top && string.charAt(pos) <= ' ') + ++pos; + return pos; + } + + public static int skipTrailingWhite(String string, int start, int end) { + while (end > start && string.charAt(end - 1) <= ' ') + --end; + return end; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionVector.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionVector.java new file mode 100644 index 000000000..c723c8e6b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionVector.java @@ -0,0 +1,325 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata; + +import java.io.Serializable; + +/** + * The VersionVector represents an array of Comparable objects. The array can be + * nested since a VersionVector is Comparable in itself. + * + * @Immutable + */ +public class VersionVector implements Comparable, Serializable { + + interface MinMaxComparable extends Comparable, Serializable { + // + } + + private static final class MaxStringValue implements MinMaxComparable { + private static final long serialVersionUID = -4936252230441132767L; + + MaxStringValue() { + // Empty constructor + } + + public int compareTo(Object o) { + return o == this ? 0 : (o == MAX_VALUE || o instanceof Integer || o instanceof VersionVector ? -1 : 1); + } + + // For singleton deserialization + private Object readResolve() { + return MAXS_VALUE; + } + + public String toString() { + return "m"; //$NON-NLS-1$ + } + } + + private static final class MaxValue implements MinMaxComparable { + private static final long serialVersionUID = -5889641741635253589L; + + MaxValue() { + // Empty constructor + } + + public int compareTo(Object o) { + return o == this ? 0 : 1; + } + + // For singleton deserialization + private Object readResolve() { + return MAX_VALUE; + } + + public String toString() { + return "M"; //$NON-NLS-1$ + } + } + + private static class MinValue implements MinMaxComparable { + private static final long serialVersionUID = -1066323980049812226L; + + MinValue() { + // Empty constructor + } + + public int compareTo(Object o) { + return o == this ? 0 : -1; + } + + private Object readResolve() { + return MIN_VALUE; + } + + public String toString() { + return "-M"; //$NON-NLS-1$ + } + } + + /** + * A value that is greater then any other value + */ + public static final Comparable MAX_VALUE = new MaxValue(); + + /** + * A value that is greater then any string but less then {@link #MAX_VALUE} and + * any Integer or VersionVector. + */ + public static final Comparable MAXS_VALUE = new MaxStringValue(); + + /** + * A value that is less then any other value + */ + public static final Comparable MIN_VALUE = new MinValue(); + + /** + * A value that is greater then {@link #MIN_VALUE} and less then any string, + * Integer, or VersionVector (a.k.a. empty_string) + */ + public static final String MINS_VALUE = ""; //$NON-NLS-1$ + + private static final long serialVersionUID = -8385373304298723744L; + + static int compare(Comparable[] vectorA, Comparable padA, Comparable[] vectorB, Comparable padB) { + int top = vectorA.length; + if (top > vectorB.length) + top = vectorB.length; + + for (int idx = 0; idx < top; ++idx) { + int cmp = compareSegments(vectorA[idx], vectorB[idx]); + if (cmp != 0) + return cmp; + } + + // All elements compared equal up to this point. Check + // pad values + if (top < vectorA.length) + return (padB == null) ? 1 : compareReminder(top, vectorA, padA, padB); + + if (top < vectorB.length) + return (padA == null) ? -1 : -compareReminder(top, vectorB, padB, padA); + + // Lengths are equal. Compare pad values + return padA == null ? (padB == null ? 0 : -1) : (padB == null ? 1 : compareSegments(padA, padB)); + } + + static boolean equals(Comparable[] vectorA, Comparable padValueA, Comparable[] vectorB, Comparable padValueB) { + // We compare pad first since it is impossible for versions with + // different pad to be equal (versions are padded to infinity) + if (padValueA == null) { + if (padValueB != null) + return false; + } else { + if (padValueB == null || !padValueA.equals(padValueB)) + return false; + } + + int idx = vectorA.length; + + // If the length of the vector differs, the versions cannot be equal + // since segments equal to pad are stripped by the parser + if (idx != vectorB.length) + return false; + + while (--idx >= 0) + if (!vectorA[idx].equals(vectorB[idx])) + return false; + + return true; + } + + static int hashCode(Comparable[] vector, Comparable padValue) { + int hashCode = padValue == null ? 31 : padValue.hashCode(); + int idx = vector.length; + while (--idx >= 0) { + Object elem = vector[idx]; + if (elem != null) + hashCode += elem.hashCode(); + hashCode = hashCode * 31; + } + return hashCode; + } + + static void toString(StringBuffer sb, Comparable[] vector, Comparable padValue, boolean rangeSafe) { + int top = vector.length; + if (top == 0) + // Write one pad value as explicit. It will be considered + // redundant and removed by the parser but the raw format + // does not allow zero elements + VersionFormat.rawToString(sb, rangeSafe, padValue == null ? MIN_VALUE : padValue); + else { + for (int idx = 0; idx < top; ++idx) { + if (idx > 0) + sb.append('.'); + VersionFormat.rawToString(sb, rangeSafe, vector[idx]); + } + } + if (padValue != null) { + sb.append('p'); + VersionFormat.rawToString(sb, rangeSafe, padValue); + } + } + + private static int compareReminder(int idx, Comparable[] vector, Comparable padValue, Comparable othersPad) { + int cmp; + for (cmp = 0; idx < vector.length && cmp == 0; ++idx) + cmp = compareSegments(vector[idx], othersPad); + if (cmp == 0) + cmp = (padValue == null) ? -1 : compareSegments(padValue, othersPad); + return cmp; + } + + static int compareSegments(Comparable a, Comparable b) { + if (a == b) + return 0; + + if (a instanceof Integer && b instanceof Integer) { + int ai = ((Integer) a).intValue(); + int bi = ((Integer) b).intValue(); + return ai > bi ? 1 : (ai < bi ? -1 : 0); + } + + if (a instanceof String && b instanceof String) + return ((String) a).compareTo((String) b); + + if (a == MAX_VALUE || a == MIN_VALUE || a == MAXS_VALUE) + return ((MinMaxComparable) a).compareTo(b); + + if (b == MAX_VALUE || b == MIN_VALUE || b == MAXS_VALUE) + return -((MinMaxComparable) b).compareTo(a); + + if (a instanceof Integer) + return 1; + if (b instanceof Integer) + return -1; + if (a instanceof VersionVector) + return (b instanceof VersionVector) ? ((VersionVector) a).compareTo((VersionVector) b) : 1; + + if (b instanceof VersionVector) + return -1; + + throw new IllegalArgumentException(); + } + + private final Comparable padValue; + + private final Comparable[] vector; + + public VersionVector(Comparable[] vector, Comparable pad) { + this.vector = vector; + this.padValue = (pad == MIN_VALUE) ? null : pad; + } + + public int compareTo(VersionVector ov) { + if (ov == this) + return 0; + + return compare(vector, padValue, ov.vector, ov.padValue); + } + + public boolean equals(Object o) { + if (o == this) + return true; + + if (!(o instanceof VersionVector)) + return false; + + VersionVector ov = (VersionVector) o; + return equals(vector, padValue, ov.vector, ov.padValue); + } + + /** + * Returns the pad value used when comparing this versions to + * versions that has a raw vector with a larger number of elements + * @return The pad value or null if not set. + */ + public Comparable getPad() { + return padValue; + } + + /** + * An element from the raw vector + * @param index The zero based index of the desired element + * @return An element from the raw vector + */ + public Comparable getSegment(int index) { + return vector[index]; + } + + /** + * Returns the number of elements in the raw vector + * @return The element count + */ + public int getSegmentCount() { + return vector.length; + } + + /** + * This method is package protected since it violates the immutable + * contract. + * @return The raw vector. Must be treated as read-only + */ + Comparable[] getVector() { + return vector; + } + + public int hashCode() { + return hashCode(vector, padValue); + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + toString(sb); + return sb.toString(); + } + + /** + * Append the string representation of this instance to the + * sb buffer. + * @param sb The buffer to append to + */ + public void toString(StringBuffer sb) { + toString(sb, vector, padValue, false); + } + + /** + * Append the string representation of this instance to the + * sb buffer. + * @param sb The buffer to append to + * @param rangeSafe If true, the range delimiters will be escaped + * with backslash. + */ + void toString(StringBuffer sb, boolean rangeSafe) { + toString(sb, vector, padValue, rangeSafe); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionedId.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionedId.java new file mode 100644 index 000000000..1bf5ebd44 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/VersionedId.java @@ -0,0 +1,104 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 Code 9 and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Code 9 - initial API and implementation + * EclipseSource - ongoing development + * Thomas Hallgren - Fix for bug 268659 + * IBM - ongoing development + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata; + +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.internal.p2.core.helpers.StringHelper; +import org.eclipse.equinox.p2.metadata.IVersionedId; + +/** + * An object representing a (id,version) pair. + * + * @noextend This class is not intended to be subclassed by clients. + */ +public class VersionedId implements IVersionedId { + private final String id; + private final Version version; + + /** + * Creates and returns a new {@link VersionedId} from the given string specification. + * The specification must be of the form "id/version", or just "id" if the version is absent + *

    + * This factory method can be used to reconstruct a {@link VersionedId} + * instance from the string representation produced by a previous invocation of + * {@link #toString()}. + * + * @param spec the specification for the versioned id to create + * @return the parsed versioned id + * @throws IllegalArgumentException If spec is improperly + * formatted. + */ + public static IVersionedId parse(String spec) { + String[] segments = StringHelper.getArrayFromString(spec, '/'); + return new VersionedId(segments[0], segments.length == 1 ? null : segments[1]); + } + + /** + * Creates a new versioned id with the given id and version. + * + * @param id The identifier + * @param version The version + * @throws IllegalArgumentException If version is improperly + * formatted. + */ + public VersionedId(String id, String version) { + this.id = id; + this.version = Version.parseVersion(version); + } + + /** + * Creates a new versioned id with the given id and version. + * + * @param id The identifier + * @param version The version + */ + public VersionedId(String id, Version version) { + this.id = id; + this.version = (version == null) ? Version.emptyVersion : version; + } + + public boolean equals(Object obj) { + if (this == obj) + return true; + + if (!(obj instanceof VersionedId)) + return false; + + VersionedId vname = (VersionedId) obj; + return id.equals(vname.id) && version.equals(vname.version); + } + + public int hashCode() { + return id.hashCode() * 31 + version.hashCode(); + } + + public String getId() { + return id; + } + + public Version getVersion() { + return version; + } + + /** + * Returns a string representation of this versioned id. + * The result can be used to later construct an equal {@link VersionedId} + * instance using {{@link #parse(String)}. + * @return A string representation of this versioned id + */ + public String toString() { + return Version.emptyVersion.equals(version) ? id : id + '/' + version.toString(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/All.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/All.java new file mode 100644 index 000000000..4de975525 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/All.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.util.Iterator; +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; + +/** + * A collection filter that yields true if the filter yields true for + * all of the elements of the collection + */ +final class All extends CollectionFilter { + All(Expression collection, LambdaExpression lambda) { + super(collection, lambda); + } + + protected Object evaluate(IEvaluationContext context, Iterator itor) { + Variable variable = lambda.getItemVariable(); + while (itor.hasNext()) { + variable.setValue(context, itor.next()); + if (lambda.evaluate(context) != Boolean.TRUE) + return Boolean.FALSE; + } + return Boolean.TRUE; + } + + public int getExpressionType() { + return TYPE_ALL; + } + + public String getOperator() { + return KEYWORD_ALL; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/And.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/And.java new file mode 100644 index 000000000..7e8adf20e --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/And.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (c) 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; + +/** + * n-ary AND operator. The full evaluation is true if all its operands evaluate to + * true. + */ +final class And extends NAry { + And(Expression[] operands) { + super(assertLength(operands, 2, OPERATOR_AND)); + } + + public Object evaluate(IEvaluationContext context) { + for (int idx = 0; idx < operands.length; ++idx) { + if (operands[idx].evaluate(context) != Boolean.TRUE) + return Boolean.FALSE; + } + return Boolean.TRUE; + } + + public int getExpressionType() { + return TYPE_AND; + } + + public String getOperator() { + return OPERATOR_AND; + } + + public int getPriority() { + return PRIORITY_AND; + } + + public void toLDAPString(StringBuffer buf) { + buf.append("(&"); //$NON-NLS-1$ + for (int idx = 0; idx < operands.length; ++idx) + operands[idx].toLDAPString(buf); + buf.append(')'); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/At.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/At.java new file mode 100644 index 000000000..e089c1dbc --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/At.java @@ -0,0 +1,96 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.util.*; +import org.eclipse.equinox.internal.p2.metadata.expression.Member.DynamicMember; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; + +/** + * This class represents indexed or keyed access to an indexed collection + * or a map. + */ +public class At extends Binary { + protected At(Expression lhs, Expression rhs) { + super(lhs, rhs); + } + + protected Object handleMember(IEvaluationContext context, Member member, Object instance, boolean[] handled) { + if (instance instanceof IInstallableUnit) { + if ("properties".equals(member.getName())) { //$NON-NLS-1$ + // Avoid full copy of the properties map just to get one member + handled[0] = true; + return ((IInstallableUnit) instance).getProperty((String) rhs.evaluate(context)); + } + } + return null; + } + + public Object evaluate(org.eclipse.equinox.p2.metadata.expression.IEvaluationContext context) { + Object lval; + if (lhs instanceof DynamicMember) { + DynamicMember lm = (DynamicMember) lhs; + Object instance = lm.operand.evaluate(context); + boolean[] handled = new boolean[] {false}; + Object result = handleMember(context, lm, instance, handled); + if (handled[0]) + return result; + lval = lm.invoke(instance); + } else + lval = lhs.evaluate(context); + + Object rval = rhs.evaluate(context); + if (lval == null) + throw new IllegalArgumentException("Unable to use [] on null"); //$NON-NLS-1$ + + if (lval instanceof Map) + return ((Map) lval).get(rval); + + if (rval instanceof Number) { + if (lval instanceof List) + return ((List) lval).get(((Number) rval).intValue()); + if (lval != null && lval.getClass().isArray()) + return ((Object[]) lval)[((Number) rval).intValue()]; + } + + if (lval instanceof Dictionary) + return ((Dictionary) lval).get(rval); + + throw new IllegalArgumentException("Unable to use [] on a " + lval.getClass().getName()); //$NON-NLS-1$ + } + + public Iterator evaluateAsIterator(IEvaluationContext context) { + Object value = evaluate(context); + if (!(value instanceof Iterator)) + value = RepeatableIterator.create(value); + return (Iterator) value; + } + + public int getExpressionType() { + return TYPE_AT; + } + + public void toString(StringBuffer bld, Variable rootVariable) { + appendOperand(bld, rootVariable, lhs, getPriority()); + bld.append('['); + appendOperand(bld, rootVariable, rhs, PRIORITY_MAX); + bld.append(']'); + } + + public String getOperator() { + return OPERATOR_AT; + } + + public int getPriority() { + return PRIORITY_MEMBER; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Binary.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Binary.java new file mode 100644 index 000000000..f4f7da504 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Binary.java @@ -0,0 +1,135 @@ +/******************************************************************************* + * Copyright (c) 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import org.eclipse.equinox.internal.p2.metadata.expression.Member.DynamicMember; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.expression.IExpressionVisitor; + +/** + * The abstract base class for all binary operations + */ +public abstract class Binary extends Expression { + public final Expression lhs; + + public final Expression rhs; + + protected Binary(Expression lhs, Expression rhs) { + this.lhs = lhs; + this.rhs = rhs; + } + + public boolean accept(IExpressionVisitor visitor) { + return super.accept(visitor) && lhs.accept(visitor) && rhs.accept(visitor); + } + + public int compareTo(Expression e) { + int cmp = super.compareTo(e); + if (cmp == 0) { + Binary be = (Binary) e; + cmp = lhs.compareTo(be.lhs); + if (cmp == 0) + cmp = rhs.compareTo(be.rhs); + } + return cmp; + } + + public boolean equals(Object o) { + if (super.equals(o)) { + Binary bo = (Binary) o; + return lhs.equals(bo.lhs) && rhs.equals(bo.rhs); + } + return false; + } + + public int getPriority() { + return PRIORITY_BINARY; // Default priority + } + + public int hashCode() { + int result = 31 + lhs.hashCode(); + return 31 * result + rhs.hashCode(); + } + + public void toString(StringBuffer bld, Variable rootVariable) { + appendOperand(bld, rootVariable, lhs, getPriority()); + bld.append(' '); + bld.append(getOperator()); + bld.append(' '); + appendOperand(bld, rootVariable, rhs, getPriority()); + } + + /** + * Appends the LDAP filter attribute name from the lhs expression if + * possible. + * @throws UnsupportedOperationException when this expression does not conform to an + * LDAP filter binary expression + */ + void appendLDAPAttribute(StringBuffer buf) { + if (lhs instanceof DynamicMember) { + DynamicMember attr = (DynamicMember) lhs; + if (attr.operand instanceof Variable) { + buf.append(attr.getName()); + return; + } + } + throw new UnsupportedOperationException(); + } + + private static char hexChar(int value) { + return (char) (value < 10 ? ('0' + value) : ('a' + (value - 10))); + } + + static void appendLDAPEscaped(StringBuffer bld, String str) { + appendLDAPEscaped(bld, str, true); + } + + static void appendLDAPEscaped(StringBuffer bld, String str, boolean escapeWild) { + int top = str.length(); + for (int idx = 0; idx < top; ++idx) { + char c = str.charAt(idx); + if (!escapeWild) { + if (c == '*') { + bld.append(c); + continue; + } else if (c == '\\' && idx + 1 < top && str.charAt(idx + 1) == '*') { + bld.append("\\2a"); //$NON-NLS-1$ + ++idx; + continue; + } + } + if (c == '(' || c == ')' || c == '*' || c == '\\' || c < ' ' || c > 127) { + short cs = (short) c; + bld.append('\\'); + bld.append(hexChar((cs & 0x00f0) >> 4)); + bld.append(hexChar(cs & 0x000f)); + } else + bld.append(c); + } + } + + /** + * Appends the LDAP filter value from the rhs expression if + * possible. + * @throws UnsupportedOperationException when this expression does not conform to an + * LDAP filter binary expression + */ + void appendLDAPValue(StringBuffer buf) { + if (rhs instanceof Literal) { + Object value = rhs.evaluate(null); + if (value instanceof String || value instanceof Version) { + appendLDAPEscaped(buf, value.toString()); + return; + } + } + throw new UnsupportedOperationException(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/CoercingComparator.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/CoercingComparator.java new file mode 100644 index 000000000..c69e75e32 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/CoercingComparator.java @@ -0,0 +1,392 @@ +/******************************************************************************* + * Copyright (c) 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Constructor; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Comparator; +import org.eclipse.equinox.internal.p2.metadata.MetadataActivator; +import org.eclipse.equinox.p2.metadata.Version; + +/** + * A comparator that performs coercion if needed before comparison. + * @param The type for the comparator. + */ +public abstract class CoercingComparator { + static class BooleanCoercer extends CoercingComparator { + public int compare(Boolean o1, Boolean o2) { + return o1.booleanValue() == o2.booleanValue() ? 0 : (o1.booleanValue() ? 1 : -1); + } + + @Override + Boolean coerce(Object v) { + if (v instanceof Boolean) + return (Boolean) v; + if (v instanceof String) { + String sv = ((String) v).trim(); + if (sv.equalsIgnoreCase("true")) //$NON-NLS-1$ + return Boolean.TRUE; + if (sv.equalsIgnoreCase("false")) //$NON-NLS-1$ + return Boolean.FALSE; + } + throw uncoercable(v); + } + + @Override + Class getCoerceClass() { + return Boolean.class; + } + + @Override + int getCoercePrio() { + return 7; + } + } + + static class ClassCoercer extends CoercingComparator> { + public int compare(Class o1, Class o2) { + return o1.getName().compareTo(o2.getName()); + } + + @Override + Class coerce(Object v) { + if (v instanceof Class) + return (Class) v; + if (v instanceof String) { + try { + return MetadataActivator.context.getBundle().loadClass(((String) v).trim()); + } catch (Exception e) { + // + } + } + throw uncoercable(v); + } + + @SuppressWarnings("unchecked") + @Override + Class> getCoerceClass() { + Class cls = Class.class; + return (Class>) cls; + } + + @Override + int getCoercePrio() { + return 11; + } + } + + static class FromStringCoercer> extends CoercingComparator { + private final Class coerceClass; + private final Constructor constructor; + + public FromStringCoercer(Class coerceClass, Constructor constructor) { + this.coerceClass = coerceClass; + this.constructor = constructor; + } + + @Override + T coerce(Object v) { + if (v instanceof String) { + try { + return constructor.newInstance(new Object[] {((String) v).trim()}); + } catch (Exception e) { + // + } + } + throw uncoercable(v); + } + + @Override + int compare(T o1, T o2) { + return o1.compareTo(o2); + } + + @Override + Class getCoerceClass() { + return coerceClass; + } + + @Override + int getCoercePrio() { + return 0; + } + } + + static class IntegerCoercer extends CoercingComparator { + public int compare(Integer o1, Integer o2) { + return o1.compareTo(o2); + } + + @Override + Integer coerce(Object v) { + if (v instanceof Integer) + return (Integer) v; + if (v instanceof Number) + return new Integer(((Number) v).intValue()); + if (v instanceof String) { + try { + return Integer.valueOf(((String) v).trim()); + } catch (NumberFormatException e) { + // + } + } + throw uncoercable(v); + } + + @Override + Class getCoerceClass() { + return Integer.class; + } + + @Override + int getCoercePrio() { + return 6; + } + } + + static class LongCoercer extends CoercingComparator { + public int compare(Long o1, Long o2) { + return o1.compareTo(o2); + } + + @Override + Long coerce(Object v) { + if (v instanceof Long) + return (Long) v; + if (v instanceof Number) + return new Long(((Number) v).longValue()); + if (v instanceof String) { + try { + return Long.valueOf(((String) v).trim()); + } catch (NumberFormatException e) { + // + } + } + throw uncoercable(v); + } + + @Override + Class getCoerceClass() { + return Long.class; + } + + @Override + int getCoercePrio() { + return 5; + } + } + + static class StringCoercer extends CoercingComparator { + public int compare(String o1, String o2) { + return o1.compareTo(o2); + } + + @Override + String coerce(Object v) { + if (v instanceof Class) + return ((Class) v).getName(); + return v.toString(); + } + + @Override + Class getCoerceClass() { + return String.class; + } + + @Override + int getCoercePrio() { + return 10; + } + } + + static class VersionCoercer extends CoercingComparator { + public int compare(Version o1, Version o2) { + return o1.compareTo(o2); + } + + boolean canCoerceTo(Class cls) { + return Version.class.isAssignableFrom(cls); + } + + @Override + Version coerce(Object v) { + if (v instanceof Version) + return (Version) v; + if (v instanceof String) + return Version.create((String) v); + if (v instanceof String) { + try { + return Version.create((String) v); + } catch (NumberFormatException e) { + // + } + } + throw uncoercable(v); + } + + @Override + Class getCoerceClass() { + return Version.class; + } + + @Override + int getCoercePrio() { + return 1; + } + } + + private static class SetAccessibleAction implements PrivilegedAction { + private final AccessibleObject accessible; + + SetAccessibleAction(AccessibleObject accessible) { + this.accessible = accessible; + } + + public Object run() { + accessible.setAccessible(true); + return null; + } + } + + private static CoercingComparator[] coercers = {new ClassCoercer(), new BooleanCoercer(), new LongCoercer(), new IntegerCoercer(), new VersionCoercer(), new StringCoercer()}; + + private static final Class[] constructorType = new Class[] {String.class}; + + /** + * Finds the comparator for a and b and delegates the coercion/comparison to the comparator + * according to priority. + * @param o1 the first object to be compared. + * @param o2 the second object to be compared. + * @return The result of the comparison + * @throws IllegalArgumentException if no comparator was found or if coercion was impossible + * @see Comparator#compare(Object, Object) + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + public static int coerceAndCompare(TA o1, TB o2) throws IllegalArgumentException { + if (o1 == null || o2 == null) + throw new IllegalArgumentException("Cannot compare null to anything"); //$NON-NLS-1$ + + if (o1 instanceof Comparable && o1.getClass().isAssignableFrom(o2.getClass())) + return ((Comparable) o1).compareTo(o2); + + if (o2 instanceof Comparable && o2.getClass().isAssignableFrom(o1.getClass())) + return -((Comparable) o2).compareTo(o1); + + CoercingComparator ca = getComparator(o1, o2); + CoercingComparator cb = getComparator(o2, o1); + return ca.getCoercePrio() <= cb.getCoercePrio() ? ca.compare(o1, ca.coerce(o2)) : cb.compare(cb.coerce(o1), o2); + } + + /** + * Finds the comparator for a and b and delegates the coercion/equal to the comparator + * according to priority. + * @param o1 the first object to be compared. + * @param o2 the second object to be compared. + * @return The result of the equality test + * @throws IllegalArgumentException if no comparator was found or if coercion was impossible + * @see Object#equals(Object) + */ + public static boolean coerceAndEquals(TA o1, TB o2) throws IllegalArgumentException { + if (o1 == o2) + return true; + + if (o1 == null || o2 == null) + return false; + + if (o1.getClass() != o2.getClass()) { + if (o1.getClass().isAssignableFrom(o2.getClass())) + return o1.equals(o2); + if (o2.getClass().isAssignableFrom(o1.getClass())) + return o2.equals(o1); + try { + CoercingComparator ca = getComparator(o1, o2); + CoercingComparator cb = getComparator(o2, o1); + return ca.getCoercePrio() <= cb.getCoercePrio() ? o1.equals(ca.coerce(o2)) : o2.equals(cb.coerce(o1)); + } catch (IllegalArgumentException e) { + // + } + } + return o1.equals(o2); + } + + /** + * Obtains the coercing comparator for the given value. + * @param value The value + * @return The coercing comparator + */ + @SuppressWarnings("unchecked") + public static CoercingComparator getComparator(V value, Object v2) { + Class vClass = (Class) value.getClass(); + CoercingComparator[] carr = coercers; + int idx = carr.length; + while (--idx >= 0) { + CoercingComparator c = carr[idx]; + if (c.canCoerceTo(vClass)) { + CoercingComparator cv = (CoercingComparator) c; + return cv; + } + } + + if (value instanceof Comparable && v2 instanceof String) { + Class> cClass = (Class>) vClass; + Constructor> constructor; + try { + constructor = cClass.getConstructor(constructorType); + if (!constructor.isAccessible()) + AccessController.doPrivileged(new SetAccessibleAction(constructor)); + synchronized (CoercingComparator.class) { + int top = coercers.length; + CoercingComparator[] nc = new CoercingComparator[top + 1]; + System.arraycopy(coercers, 0, nc, 1, top); + CoercingComparator cv = (CoercingComparator) new FromStringCoercer>(cClass, constructor); + nc[0] = cv; + coercers = nc; + return cv; + } + } catch (Exception e) { + // + } + } + throw new IllegalArgumentException("No comparator for " + vClass.getName()); //$NON-NLS-1$ + } + + protected IllegalArgumentException uncoercable(Object v) { + StringBuffer sb = new StringBuffer("Cannot coerce "); //$NON-NLS-1$ + if (v instanceof String) { + sb.append('\''); + sb.append(v); + sb.append('\''); + } else if (v instanceof Number) { + sb.append("number "); //$NON-NLS-1$ + sb.append(v); + } else { + sb.append("an object of instance "); //$NON-NLS-1$ + sb.append(v.getClass().getName()); + } + sb.append(" into a "); //$NON-NLS-1$ + sb.append(getCoerceClass().getName()); + return new IllegalArgumentException(sb.toString()); + } + + boolean canCoerceTo(Class cls) { + return cls == getCoerceClass(); + } + + abstract T coerce(Object v); + + abstract int compare(T o1, T o2); + + abstract Class getCoerceClass(); + + abstract int getCoercePrio(); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/CollectionFilter.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/CollectionFilter.java new file mode 100644 index 000000000..bb845d373 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/CollectionFilter.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.util.Iterator; +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; +import org.eclipse.equinox.p2.metadata.expression.IExpressionVisitor; + +/** + * Some kind of operation that is performed for each element of a collection. I.e. + * x.<operation>(y | <expression&rt;) + */ +public abstract class CollectionFilter extends Unary { + public static void appendProlog(StringBuffer bld, Variable rootVariable, Expression lhs, String operator) { + if (lhs != rootVariable) { + appendOperand(bld, rootVariable, lhs, PRIORITY_COLLECTION); + bld.append('.'); + } + bld.append(operator); + bld.append('('); + } + + public final LambdaExpression lambda; + + protected CollectionFilter(Expression collection, LambdaExpression lambda) { + super(collection); + this.lambda = lambda; + } + + public boolean accept(IExpressionVisitor visitor) { + return super.accept(visitor) && lambda.accept(visitor); + } + + public int compareTo(Expression e) { + int cmp = super.compareTo(e); + if (cmp == 0) + cmp = lambda.compareTo(((CollectionFilter) e).lambda); + return cmp; + } + + public boolean equals(Object o) { + return super.equals(o) && lambda.equals(((CollectionFilter) o).lambda); + } + + public final Object evaluate(IEvaluationContext context) { + Iterator lval = operand.evaluateAsIterator(context); + context = lambda.prolog(context); + return evaluate(context, lval); + } + + public final Iterator evaluateAsIterator(IEvaluationContext context) { + Iterator lval = operand.evaluateAsIterator(context); + context = lambda.prolog(context); + return evaluateAsIterator(context, lval); + } + + public void toString(StringBuffer bld, Variable rootVariable) { + appendProlog(bld, rootVariable, operand, getOperator()); + appendOperand(bld, rootVariable, lambda, PRIORITY_LAMBDA); + bld.append(')'); + } + + public int hashCode() { + int result = 31 + operand.hashCode(); + return 31 * result + lambda.hashCode(); + } + + public int getPriority() { + return PRIORITY_COLLECTION; + } + + protected abstract Object evaluate(final IEvaluationContext context, Iterator iterator); + + protected Iterator evaluateAsIterator(IEvaluationContext context, Iterator iterator) { + throw new UnsupportedOperationException(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Compare.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Compare.java new file mode 100644 index 000000000..7e958e41d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Compare.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; + +/** + * Comparisons for magnitude. + */ +final class Compare extends Binary { + static IllegalArgumentException uncomparable(Object lval, Object rval) { + return new IllegalArgumentException("Cannot compare a " + lval.getClass().getName() + " to a " + rval.getClass().getName()); //$NON-NLS-1$//$NON-NLS-2$ + } + + final boolean compareLess; + + final boolean equalOK; + + Compare(Expression lhs, Expression rhs, boolean compareLess, boolean equalOK) { + super(lhs, rhs); + this.compareLess = compareLess; + this.equalOK = equalOK; + } + + public Object evaluate(IEvaluationContext context) { + int cmpResult = CoercingComparator.coerceAndCompare(lhs.evaluate(context), rhs.evaluate(context)); + return Boolean.valueOf(cmpResult == 0 ? equalOK : (cmpResult < 0 ? compareLess : !compareLess)); + } + + public int getExpressionType() { + return compareLess ? (equalOK ? TYPE_LESS_EQUAL : TYPE_LESS) : (equalOK ? TYPE_GREATER_EQUAL : TYPE_GREATER); + } + + public String getOperator() { + return compareLess ? (equalOK ? OPERATOR_LT_EQUAL : OPERATOR_LT) : (equalOK ? OPERATOR_GT_EQUAL : OPERATOR_GT); + } + + public void toLDAPString(StringBuffer buf) { + if (!equalOK) + buf.append("(!"); //$NON-NLS-1$ + buf.append('('); + appendLDAPAttribute(buf); + if (equalOK) + buf.append(compareLess ? OPERATOR_LT_EQUAL : OPERATOR_GT_EQUAL); + else + buf.append(compareLess ? OPERATOR_GT_EQUAL : OPERATOR_LT_EQUAL); + appendLDAPValue(buf); + buf.append(')'); + if (!equalOK) + buf.append(')'); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Equals.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Equals.java new file mode 100644 index 000000000..7452c3165 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Equals.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; + +/** + * An expression that performs the == and != comparisons + */ +final class Equals extends Binary { + final boolean negate; + + Equals(Expression lhs, Expression rhs, boolean negate) { + super(lhs, rhs); + this.negate = negate; + } + + public Object evaluate(IEvaluationContext context) { + boolean result = CoercingComparator.coerceAndEquals(lhs.evaluate(context), rhs.evaluate(context)); + if (negate) + result = !result; + return Boolean.valueOf(result); + } + + public int getExpressionType() { + return negate ? TYPE_NOT_EQUALS : TYPE_EQUALS; + } + + public String getOperator() { + return negate ? OPERATOR_NOT_EQUALS : OPERATOR_EQUALS; + } + + public void toLDAPString(StringBuffer buf) { + if (negate) + buf.append("(!"); //$NON-NLS-1$ + buf.append('('); + appendLDAPAttribute(buf); + buf.append('='); + appendLDAPValue(buf); + buf.append(')'); + if (negate) + buf.append(')'); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/EvaluationContext.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/EvaluationContext.java new file mode 100644 index 000000000..8fb3665bc --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/EvaluationContext.java @@ -0,0 +1,161 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; +import org.eclipse.equinox.p2.metadata.expression.IExpression; + +/** + * Highly specialized evaluation contexts optimized for misc purposes + */ +public class EvaluationContext implements IEvaluationContext { + public static class Parameters extends EvaluationContext { + private static final Object[] noParameters = new Object[0]; + + private final Object[] parameters; + + public Parameters(IEvaluationContext parentContext, Object[] parameters) { + super(parentContext); + this.parameters = parameters == null ? noParameters : parameters; + } + + public Object getParameter(int position) { + return position >= 0 && position < parameters.length ? parameters[position] : super.getParameter(position); + } + } + + public static class SingleVariableContext implements IEvaluationContext { + private final IEvaluationContext parentContext; + + private Object value; + + private final IExpression variable; + + public SingleVariableContext(IEvaluationContext parentContext, IExpression variable) { + this.parentContext = parentContext; + this.variable = variable; + } + + public Object getParameter(int position) { + return parentContext.getParameter(position); + } + + public Object getValue(IExpression var) { + return variable == var ? value : parentContext.getValue(var); + } + + public void setValue(IExpression var, Object val) { + if (variable == var) + value = val; + else + parentContext.setValue(var, val); + } + } + + static class MultiVariableContext implements IEvaluationContext { + private final IEvaluationContext parentContext; + + private final Object[] values; + + public MultiVariableContext(IEvaluationContext parentContext, IExpression[] variables) { + this.parentContext = parentContext; + values = new Object[variables.length * 2]; + for (int idx = 0, ndx = 0; ndx < variables.length; ++ndx, idx += 2) + values[idx] = variables[ndx]; + } + + public Object getParameter(int position) { + return parentContext.getParameter(position); + } + + public Object getValue(IExpression variable) { + for (int idx = 0; idx < values.length; ++idx) + if (values[idx++] == variable) + return values[idx]; + return parentContext.getValue(variable); + } + + public void setValue(IExpression variable, Object value) { + for (int idx = 0; idx < values.length; ++idx) + if (values[idx++] == variable) { + values[idx] = value; + return; + } + parentContext.setValue(variable, value); + } + } + + public static final EvaluationContext INSTANCE = new EvaluationContext(null); + + public static IEvaluationContext create() { + return INSTANCE; + } + + public static IEvaluationContext create(IEvaluationContext parent, IExpression variable) { + return new SingleVariableContext(parent, variable); + } + + public static IEvaluationContext create(IEvaluationContext parent, IExpression[] variables) { + return variables.length == 1 ? new SingleVariableContext(parent, variables[0]) : new MultiVariableContext(parent, variables); + } + + public static IEvaluationContext create(IEvaluationContext parent, Object[] parameters) { + return new Parameters(parent, parameters); + } + + public static IEvaluationContext create(IExpression variable) { + return new SingleVariableContext(null, variable); + } + + public static IEvaluationContext create(IExpression[] variables) { + if (variables == null || variables.length == 0) + return INSTANCE; + return variables.length == 1 ? create(variables[0]) : new MultiVariableContext(INSTANCE, variables); + } + + public static IEvaluationContext create(Object[] parameters, IExpression variable) { + return parameters == null || parameters.length == 0 ? create(variable) : new SingleVariableContext(new Parameters(null, parameters), variable); + } + + public static IEvaluationContext create(Object[] parameters, IExpression[] variables) { + if (parameters == null || parameters.length == 0) + return create(variables); + + Parameters pctx = new Parameters(null, parameters); + if (variables == null || variables.length == 0) + return pctx; + return create(pctx, variables); + } + + protected EvaluationContext(IEvaluationContext parentContext) { + this.parentContext = parentContext; + } + + private final IEvaluationContext parentContext; + + public Object getParameter(int position) { + if (parentContext == null) + throw new IllegalArgumentException("No such parameter: $" + position); //$NON-NLS-1$ + return parentContext.getParameter(position); + } + + public Object getValue(IExpression variable) { + if (parentContext == null) + throw new IllegalArgumentException("No such variable: " + variable); //$NON-NLS-1$ + return parentContext.getValue(variable); + } + + public void setValue(IExpression variable, Object value) { + if (parentContext == null) + throw new IllegalArgumentException("No such variable: " + variable); //$NON-NLS-1$ + parentContext.setValue(variable, value); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Exists.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Exists.java new file mode 100644 index 000000000..14fbc5df4 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Exists.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.util.Iterator; +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; + +/** + * A collection filter that yields true if the filter yields true for + * any of the elements of the collection + */ +final class Exists extends CollectionFilter { + Exists(Expression collection, LambdaExpression lambda) { + super(collection, lambda); + } + + protected Object evaluate(IEvaluationContext context, Iterator itor) { + Variable variable = lambda.getItemVariable(); + while (itor.hasNext()) { + variable.setValue(context, itor.next()); + if (lambda.evaluate(context) == Boolean.TRUE) + return Boolean.TRUE; + } + return Boolean.FALSE; + } + + public int getExpressionType() { + return TYPE_EXISTS; + } + + public String getOperator() { + return KEYWORD_EXISTS; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Expression.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Expression.java new file mode 100644 index 000000000..75f47dd94 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Expression.java @@ -0,0 +1,341 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.util.*; +import org.eclipse.equinox.p2.metadata.expression.*; + +/** + * The base class of the expression tree. + */ +public abstract class Expression implements IExpression, Comparable, IExpressionConstants { + + static final Expression[] emptyArray = new Expression[0]; + + public static void appendOperand(StringBuffer bld, Variable rootVariable, Expression operand, int priority) { + if (priority < operand.getPriority()) { + bld.append('('); + operand.toString(bld, rootVariable); + bld.append(')'); + } else + operand.toString(bld, rootVariable); + } + + public static Expression[] assertLength(Expression[] operands, int minLength, int maxLength, String operand) { + if (operands == null) + operands = emptyArray; + if (operands.length < minLength) + throw new IllegalArgumentException("Not enough operands for " + operand); //$NON-NLS-1$ + if (operands.length > maxLength) + throw new IllegalArgumentException("Too many operands for " + operand); //$NON-NLS-1$ + return operands; + } + + public static Expression[] assertLength(Expression[] operands, int length, String operand) { + if (operands == null) + operands = emptyArray; + if (operands.length < length) + throw new IllegalArgumentException("Not enough operands for " + operand); //$NON-NLS-1$ + return operands; + } + + public static int compare(Expression[] arr1, Expression[] arr2) { + int max = arr1.length; + if (max > arr2.length) + max = arr2.length; + for (int idx = 0; idx < max; ++idx) { + int cmp = arr1[idx].compareTo(arr2[idx]); + if (cmp != 0) + return cmp; + } + if (max == arr2.length) { + if (max < arr1.length) + return 1; + return 0; + } + return -1; + } + + public static boolean equals(Expression[] arr1, Expression[] arr2) { + int idx = arr1.length; + if (idx != arr2.length) + return false; + while (--idx >= 0) + if (!arr1[idx].equals(arr2[idx])) + return false; + return true; + } + + public static int hashCode(Expression[] arr) { + int idx = arr.length; + int result = 1; + while (--idx >= 0) + result = 31 * result + arr[idx].hashCode(); + return result; + } + + public static void elementsToString(StringBuffer bld, Variable rootVariable, Expression[] elements) { + int top = elements.length; + if (top > 0) { + elements[0].toString(bld, rootVariable); + for (int idx = 1; idx < top; ++idx) { + bld.append(", "); //$NON-NLS-1$ + appendOperand(bld, rootVariable, elements[idx], PRIORITY_MAX); + } + } + } + + /** + * Let the visitor visit this instance and all expressions that this + * instance contains. + * @param visitor The visiting visitor. + * @return true if the visitor should continue visiting, false otherwise. + */ + public boolean accept(IExpressionVisitor visitor) { + return visitor.visit(this); + } + + public int compareTo(Expression e) { + int cmp = getPriority() - e.getPriority(); + if (cmp == 0) { + int e1 = getExpressionType(); + int e2 = e.getExpressionType(); + cmp = e1 > e2 ? 1 : (e1 == e2 ? 0 : -1); + } + return cmp; + } + + public boolean equals(Object e) { + if (e == this) + return true; + if (e == null || getClass() != e.getClass()) + return false; + return getExpressionType() == ((Expression) e).getExpressionType(); + } + + /** + * Evaluate this expression with given context and variables. + * @param context The evaluation context + * @return The result of the evaluation. + */ + public abstract Object evaluate(IEvaluationContext context); + + public Iterator evaluateAsIterator(IEvaluationContext context) { + Object value = evaluate(context); + if (!(value instanceof Iterator)) + value = RepeatableIterator.create(value); + return (Iterator) value; + } + + public abstract String getOperator(); + + public abstract int getPriority(); + + public boolean isRootVariable() { + return false; + } + + public final String toLDAPString() { + StringBuffer bld = new StringBuffer(); + toLDAPString(bld); + return bld.toString(); + } + + public void toLDAPString(StringBuffer buf) { + throw new UnsupportedOperationException(); + } + + public final String toString() { + StringBuffer bld = new StringBuffer(); + toString(bld); + return bld.toString(); + } + + public void toString(StringBuffer bld) { + toString(bld, ExpressionFactory.THIS); + } + + public abstract void toString(StringBuffer bld, Variable rootVariable); + + private static class Compacter { + private Expression base; + + private List parts; + + private int op; + + Compacter(Expression base, int op) { + this.base = base; + this.op = op; + } + + Expression getResultingFilter() { + if (parts == null) + return base; + + int partsOp = op == TYPE_AND ? TYPE_OR : TYPE_AND; + return addFilter(base, normalize(parts, partsOp), op); + } + + boolean merge(Expression b) { + Expression[] aArr; + Expression[] bArr; + if (base.getExpressionType() == op) + aArr = getFilterImpls(base); + else + aArr = new Expression[] {base}; + + if (b.getExpressionType() == op) + bArr = getFilterImpls(b); + else + bArr = new Expression[] {b}; + + List common = null; + List onlyA = null; + + int atop = aArr.length; + int btop = bArr.length; + int aidx; + int bidx; + for (aidx = 0; aidx < atop; ++aidx) { + Expression af = aArr[aidx]; + for (bidx = 0; bidx < btop; ++bidx) { + Expression bf = bArr[bidx]; + if (af.equals(bf)) { + if (common == null) + common = new ArrayList(); + common.add(af); + break; + } + } + if (bidx == btop) { + if (onlyA == null) + onlyA = new ArrayList(); + onlyA.add(af); + } + } + if (common == null) + // Nothing in common + return false; + + if (onlyA == null && parts == null) + return true; + + List onlyB = null; + for (bidx = 0; bidx < btop; ++bidx) { + Expression bf = bArr[bidx]; + for (aidx = 0; aidx < atop; ++aidx) + if (bf.equals(aArr[aidx])) + break; + if (aidx == atop) { + if (onlyB == null) + onlyB = new ArrayList(); + onlyB.add(bf); + } + } + + if (onlyB == null && parts == null) { + // All of B is already covered by base + base = b; + return true; + } + + if (parts == null) + parts = new ArrayList(); + + if (onlyA != null) { + base = normalize(common, op); + Expression af = normalize(onlyA, op); + if (!parts.contains(af)) + parts.add(af); + } + Expression bf = normalize(onlyB, op); + if (!parts.contains(bf)) + parts.add(bf); + return true; + } + } + + static Expression addFilter(Expression base, Expression subFilter, int expressionType) { + if (base.equals(subFilter)) + return base; + + ArrayList filters = new ArrayList(2); + filters.add(base); + filters.add(subFilter); + return normalize(filters, expressionType); + } + + static Expression normalize(List operands, int op) { + int top = operands.size(); + if (top == 1) + return operands.get(0); + + // a | (b | c) becomes a | b | c + // a & (b & c) becomes a & b & c + // + for (int idx = 0; idx < top; ++idx) { + Expression f = operands.get(idx); + if (f.getExpressionType() != op) + continue; + + Expression[] sfs = getFilterImpls(f); + operands.remove(idx); + --top; + for (int ndx = 0; ndx < sfs.length; ++ndx) { + Expression nf = sfs[ndx]; + if (!operands.contains(nf)) + operands.add(nf); + } + } + top = operands.size(); + if (top == 1) + return operands.get(0); + + Collections.sort(operands); + List splits = new ArrayList(); + int reverseOp = op == TYPE_AND ? TYPE_OR : TYPE_AND; + + for (int idx = 0; idx < top; ++idx) + merge(splits, operands.get(idx), reverseOp); + + operands.clear(); + top = splits.size(); + for (int idx = 0; idx < top; ++idx) { + Expression filter = splits.get(idx).getResultingFilter(); + if (!operands.contains(filter)) + operands.add(filter); + } + top = operands.size(); + if (top == 1) + return operands.get(0); + + Collections.sort(operands); + Expression[] expArray = operands.toArray(new Expression[top]); + return op == TYPE_AND ? new And(expArray) : new Or(expArray); + } + + static void merge(List splits, Expression base, int op) { + int top = splits.size(); + for (int idx = 0; idx < top; ++idx) { + Compacter split = splits.get(idx); + if (split.merge(base)) + return; + } + splits.add(new Compacter(base, op)); + } + + static Expression[] getFilterImpls(Expression expression) { + if (expression instanceof NAry) + return ((NAry) expression).operands; + throw new IllegalArgumentException(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/ExpressionFactory.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/ExpressionFactory.java new file mode 100644 index 000000000..a9e70e311 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/ExpressionFactory.java @@ -0,0 +1,125 @@ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.util.List; +import org.eclipse.equinox.p2.metadata.expression.*; + +public class ExpressionFactory implements IExpressionFactory, IExpressionConstants { + public static final IExpressionFactory INSTANCE = new ExpressionFactory(); + public static final Variable THIS = new Variable(VARIABLE_THIS); + + protected static Expression[] convertArray(IExpression[] operands) { + Expression[] ops = new Expression[operands.length]; + System.arraycopy(operands, 0, ops, 0, operands.length); + return ops; + } + + protected ExpressionFactory() { + // Maintain singleton + } + + public IExpression all(IExpression collection, IExpression lambda) { + return new All((Expression) collection, (LambdaExpression) lambda); + } + + public IExpression and(IExpression... operands) { + return new And(convertArray(operands)); + } + + public IExpression at(IExpression target, IExpression key) { + return new At((Expression) target, (Expression) key); + } + + @SuppressWarnings("unchecked") + public IExpression normalize(List operands, int expressionType) { + return Expression.normalize((List) operands, expressionType); + } + + public IExpression constant(Object value) { + return Literal.create(value); + } + + public IEvaluationContext createContext(Object... parameters) { + return EvaluationContext.create(parameters, (Variable[]) null); + } + + public IEvaluationContext createContext(IExpression[] variables, Object... parameters) { + return EvaluationContext.create(parameters, variables); + } + + public IFilterExpression filterExpression(IExpression expression) { + return new LDAPFilter((Expression) expression); + } + + public IExpression equals(IExpression lhs, IExpression rhs) { + return new Equals((Expression) lhs, (Expression) rhs, false); + } + + public IExpression exists(IExpression collection, IExpression lambda) { + return new Exists((Expression) collection, (LambdaExpression) lambda); + } + + public IExpression greater(IExpression lhs, IExpression rhs) { + return new Compare((Expression) lhs, (Expression) rhs, false, false); + } + + public IExpression greaterEqual(IExpression lhs, IExpression rhs) { + return new Compare((Expression) lhs, (Expression) rhs, false, true); + } + + public IExpression indexedParameter(int index) { + return new Parameter(index); + } + + public IExpression lambda(IExpression variable, IExpression body) { + return new LambdaExpression((Variable) variable, (Expression) body); + } + + public IExpression less(IExpression lhs, IExpression rhs) { + return new Compare((Expression) lhs, (Expression) rhs, true, false); + } + + public IExpression lessEqual(IExpression lhs, IExpression rhs) { + return new Compare((Expression) lhs, (Expression) rhs, true, true); + } + + public IExpression matches(IExpression lhs, IExpression rhs) { + return new Matches((Expression) lhs, (Expression) rhs); + } + + public IMatchExpression matchExpression(IExpression expression, Object... parameters) { + return new MatchExpression((Expression) expression, parameters); + } + + public IExpression member(IExpression target, String name) { + return new Member.DynamicMember((Expression) target, name); + } + + public IExpression not(IExpression operand) { + if (operand instanceof Equals) { + Equals eq = (Equals) operand; + return new Equals(eq.lhs, eq.rhs, !eq.negate); + } + if (operand instanceof Compare) { + Compare cmp = (Compare) operand; + return new Compare(cmp.lhs, cmp.rhs, !cmp.compareLess, !cmp.equalOK); + } + if (operand instanceof Not) + return ((Not) operand).operand; + + return new Not((Expression) operand); + } + + public IExpression or(IExpression... operands) { + return new Or(convertArray(operands)); + } + + public IExpression thisVariable() { + return THIS; + } + + public IExpression variable(String name) { + if (VARIABLE_THIS.equals(name)) + return THIS; + return new Variable(name); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/IExpressionConstants.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/IExpressionConstants.java new file mode 100644 index 000000000..3da1dbfac --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/IExpressionConstants.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +public interface IExpressionConstants { + String KEYWORD_ALL = "all"; //$NON-NLS-1$ + + String KEYWORD_BOOLEAN = "boolean"; //$NON-NLS-1$ + String KEYWORD_CLASS = "class"; //$NON-NLS-1$ + String KEYWORD_EXISTS = "exists"; //$NON-NLS-1$ + String KEYWORD_FALSE = "false"; //$NON-NLS-1$ + String KEYWORD_FILTER = "filter"; //$NON-NLS-1$ + String KEYWORD_NULL = "null"; //$NON-NLS-1$ + String KEYWORD_RANGE = "range"; //$NON-NLS-1$ + String KEYWORD_TRUE = "true"; //$NON-NLS-1$ + + String KEYWORD_VERSION = "version"; //$NON-NLS-1$ + String OPERATOR_AND = "&&"; //$NON-NLS-1$ + String OPERATOR_AT = "[]"; //$NON-NLS-1$ + String OPERATOR_EQUALS = "=="; //$NON-NLS-1$ + String OPERATOR_GT = ">"; //$NON-NLS-1$ + String OPERATOR_GT_EQUAL = ">="; //$NON-NLS-1$ + String OPERATOR_LT = "<"; //$NON-NLS-1$ + String OPERATOR_LT_EQUAL = "<="; //$NON-NLS-1$ + String OPERATOR_MATCHES = "~="; //$NON-NLS-1$ + String OPERATOR_MEMBER = "."; //$NON-NLS-1$ + String OPERATOR_NOT = "!"; //$NON-NLS-1$ + String OPERATOR_NOT_EQUALS = "!="; //$NON-NLS-1$ + + String OPERATOR_OR = "||"; //$NON-NLS-1$ + String OPERATOR_PARAMETER = "$"; //$NON-NLS-1$ + + int PRIORITY_LITERAL = 1; + int PRIORITY_VARIABLE = 1; + int PRIORITY_FUNCTION = 2; // for extend query expressions + int PRIORITY_MEMBER = 3; + int PRIORITY_COLLECTION = 4; + int PRIORITY_NOT = 5; + int PRIORITY_BINARY = 6; + int PRIORITY_AND = 7; + int PRIORITY_OR = 8; + int PRIORITY_CONDITION = 9; + int PRIORITY_ASSIGNMENT = 10; + int PRIORITY_LAMBDA = 11; + int PRIORITY_COMMA = 12; + int PRIORITY_MAX = 20; + + String VARIABLE_EVERYTHING = "everything"; //$NON-NLS-1$ + String VARIABLE_THIS = "this"; //$NON-NLS-1$ +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/IRepeatableIterator.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/IRepeatableIterator.java new file mode 100644 index 000000000..f20e266bf --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/IRepeatableIterator.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.util.Iterator; + +public interface IRepeatableIterator extends Iterator { + /** + * Returns a copy that will iterate over the same elements + * as this iterator. The contents or position of this iterator + * is left unchanged. + * @return A re-initialized copy of this iterator. + */ + IRepeatableIterator getCopy(); + + Object getIteratorProvider(); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/LDAPApproximation.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/LDAPApproximation.java new file mode 100644 index 000000000..291a6ef6c --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/LDAPApproximation.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (c) 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.io.Serializable; + +/** + * Map a string for an LDAP APPROX (~=) comparison. + * This implementation removes white spaces and transforms everything to lower case. + */ +public final class LDAPApproximation implements Serializable, Comparable { + private static final long serialVersionUID = 4782295637798543587L; + private final String pattern; + private transient String approxPattern; + + public LDAPApproximation(String pattern) { + this.pattern = pattern; + } + + public int compareTo(LDAPApproximation o) { + return pattern.compareTo(o.pattern); + } + + public boolean equals(Object o) { + return o == this || (o instanceof LDAPApproximation && ((LDAPApproximation) o).pattern.equals(pattern)); + } + + public int hashCode() { + return 3 * pattern.hashCode(); + } + + /** + * Matches the value with the compiled expression. The value + * is considered matching if all characters are matched by the expression. A + * partial match is not enough. + * @param value The value to match + * @return true if the value was a match. + */ + public boolean isMatch(CharSequence value) { + if (value == null) + return false; + if (approxPattern == null) + approxPattern = approxString(pattern); + return approxString(value).equals(approxPattern); + } + + public String toString() { + return pattern; + } + + private static String approxString(CharSequence input) { + boolean changed = false; + char[] output = new char[input.length()]; + int cursor = 0; + for (int i = 0, length = output.length; i < length; i++) { + char c = input.charAt(i); + if (Character.isWhitespace(c)) { + changed = true; + continue; + } + if (Character.isUpperCase(c)) { + changed = true; + c = Character.toLowerCase(c); + } + output[cursor++] = c; + } + return changed ? new String(output, 0, cursor) : input.toString(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/LDAPFilter.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/LDAPFilter.java new file mode 100644 index 000000000..607334bea --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/LDAPFilter.java @@ -0,0 +1,69 @@ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.util.Dictionary; +import java.util.Map; +import org.eclipse.equinox.p2.metadata.expression.*; +import org.osgi.framework.Filter; +import org.osgi.framework.ServiceReference; + +public class LDAPFilter extends Unary implements IFilterExpression { + + LDAPFilter(Expression expression) { + super(expression); + } + + public boolean accept(IExpressionVisitor visitor) { + return operand.accept(visitor); + } + + public boolean equals(Object o) { + return (o instanceof Filter && !(o instanceof LDAPFilter)) ? equals(ExpressionUtil.parseLDAP(o.toString())) : super.equals(o); + } + + @Override + public String getOperator() { + return operand.getOperator(); + } + + @Override + public int getPriority() { + return operand.getPriority(); + } + + public int getExpressionType() { + return 0; + } + + public boolean match(Map map) { + return isMatch(MemberProvider.create(map, true)); + } + + @SuppressWarnings("rawtypes") + public boolean match(Dictionary dictionary) { + return isMatch(dictionary == null ? MemberProvider.emptyProvider() : MemberProvider.create(dictionary, true)); + } + + private boolean isMatch(Object candidate) { + Variable self = ExpressionFactory.THIS; + IEvaluationContext ctx = EvaluationContext.create(self); + self.setValue(ctx, candidate); + return Boolean.TRUE == operand.evaluate(ctx); + } + + public boolean match(ServiceReference reference) { + return isMatch(reference == null ? MemberProvider.emptyProvider() : MemberProvider.create(reference, true)); + } + + public boolean matchCase(Map map) { + return isMatch(map == null ? MemberProvider.emptyProvider() : MemberProvider.create(map, false)); + } + + @SuppressWarnings("rawtypes") + public boolean matchCase(Dictionary dictionary) { + return isMatch(dictionary == null ? MemberProvider.emptyProvider() : MemberProvider.create(dictionary, false)); + } + + public void toString(StringBuffer bld, Variable rootVariable) { + operand.toLDAPString(bld); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/LambdaExpression.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/LambdaExpression.java new file mode 100644 index 000000000..c5bacf0ab --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/LambdaExpression.java @@ -0,0 +1,72 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; +import org.eclipse.equinox.p2.metadata.expression.IExpressionVisitor; + +/** + * A function that executes some code + */ +public class LambdaExpression extends Unary { + protected final Variable each; + + protected LambdaExpression(Variable each, Expression body) { + super(body); + this.each = each; + } + + public boolean accept(IExpressionVisitor visitor) { + return super.accept(visitor) && each.accept(visitor); + } + + public int compareTo(Expression e) { + int cmp = super.compareTo(e); + if (cmp == 0) + cmp = each.compareTo(((LambdaExpression) e).each); + return cmp; + } + + public boolean equals(Object o) { + return super.equals(o) && each.equals(((LambdaExpression) o).each); + } + + public int hashCode() { + int result = 31 + operand.hashCode(); + return 31 * result + each.hashCode(); + } + + public int getExpressionType() { + return TYPE_LAMBDA; + } + + public void toString(StringBuffer bld, Variable rootVariable) { + each.toString(bld, rootVariable); + bld.append(" | "); //$NON-NLS-1$ + appendOperand(bld, rootVariable, operand, IExpressionConstants.PRIORITY_COMMA); + } + + public Variable getItemVariable() { + return each; + } + + public String getOperator() { + return "|"; //$NON-NLS-1$ + } + + public int getPriority() { + return IExpressionConstants.PRIORITY_LAMBDA; + } + + public IEvaluationContext prolog(IEvaluationContext context) { + return EvaluationContext.create(context, each); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Literal.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Literal.java new file mode 100644 index 000000000..2884fb757 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Literal.java @@ -0,0 +1,123 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; +import org.eclipse.equinox.p2.metadata.expression.SimplePattern; +import org.osgi.framework.Filter; + +/** + * An expression that represents a constant value. + */ +public final class Literal extends Expression { + public static final Literal FALSE_CONSTANT = new Literal(Boolean.FALSE); + + public static final Literal NULL_CONSTANT = new Literal(null); + + public static final Literal TRUE_CONSTANT = new Literal(Boolean.TRUE); + + static Literal create(Object value) { + if (value == null) + return NULL_CONSTANT; + if (value == Boolean.TRUE) + return TRUE_CONSTANT; + if (value == Boolean.FALSE) + return FALSE_CONSTANT; + return new Literal(value); + } + + public final Object value; + + private Literal(Object value) { + this.value = value; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public int compareTo(Expression e) { + int cmp = super.compareTo(e); + if (cmp != 0) + return cmp; + + Object eValue = ((Literal) e).value; + if (value == null) + return eValue == null ? 0 : -1; + + if (eValue == null) + return 1; + + if (eValue.getClass() == value.getClass()) + return ((Comparable) value).compareTo(eValue); + + return eValue.getClass().getName().compareTo(value.getClass().getName()); + } + + public boolean equals(Object o) { + if (super.equals(o)) { + Literal bo = (Literal) o; + return value == null ? bo.value == null : value.equals(bo.value); + } + return false; + } + + public Object evaluate(IEvaluationContext context) { + return value; + } + + public int getExpressionType() { + return TYPE_LITERAL; + } + + public String getOperator() { + return ""; //$NON-NLS-1$ + } + + public int getPriority() { + return PRIORITY_LITERAL; + } + + public int hashCode() { + return 31 + value.hashCode(); + } + + public void toLDAPString(StringBuffer buf) { + if (!(value instanceof Filter)) + throw new UnsupportedOperationException(); + buf.append(value.toString()); + } + + public void toString(StringBuffer bld, Variable rootVariable) { + if (value == null) + bld.append("null"); //$NON-NLS-1$ + else if (value instanceof String || value instanceof Version) { + String str = value.toString(); + char sep = str.indexOf('\'') >= 0 ? '"' : '\''; + bld.append(sep); + bld.append(str); + bld.append(sep); + } else if (value instanceof SimplePattern) { + appendEscaped(bld, '/', value.toString()); + } else + bld.append(value); + } + + private void appendEscaped(StringBuffer bld, char delimiter, String str) { + bld.append(delimiter); + int top = str.length(); + for (int idx = 0; idx < top; ++idx) { + char c = str.charAt(idx); + if (c == delimiter) + bld.append('\\'); + bld.append(c); + } + bld.append(delimiter); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/MatchExpression.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/MatchExpression.java new file mode 100644 index 000000000..efb636bb9 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/MatchExpression.java @@ -0,0 +1,83 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.util.Arrays; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; +import org.eclipse.equinox.p2.metadata.expression.*; + +/** + * The MatchExpression is a wrapper for an {@link IExpression} that is expected + * to return a boolean value. The wrapper provides the evaluation context needed + * to evaluate the expression. + */ +class MatchExpression extends Unary implements IMatchExpression { + private static final Object[] noParams = new Object[0]; + private final Object[] parameters; + + MatchExpression(Expression expression, Object[] parameters) { + super(expression); + this.parameters = parameters == null ? noParams : parameters; + } + + public boolean accept(IExpressionVisitor visitor) { + return operand.accept(visitor); + } + + public IEvaluationContext createContext() { + return EvaluationContext.create(parameters, ExpressionFactory.THIS); + } + + public boolean equals(Object o) { + return super.equals(o) && Arrays.equals(parameters, ((MatchExpression) o).parameters); + } + + public Object evaluate(IEvaluationContext context) { + return operand.evaluate(parameters.length == 0 ? context : EvaluationContext.create(context, parameters)); + } + + public int getExpressionType() { + return 0; + } + + public String getOperator() { + throw new UnsupportedOperationException(); + } + + public Object[] getParameters() { + return parameters; + } + + public int getPriority() { + return operand.getPriority(); + } + + public int hashCode() { + return operand.hashCode() * 31 + CollectionUtils.hashCode(parameters); + } + + public boolean isMatch(IEvaluationContext context, T value) { + ExpressionFactory.THIS.setValue(context, value); + return Boolean.TRUE == operand.evaluate(context); + } + + public boolean isMatch(T value) { + return isMatch(createContext(), value); + } + + public void toLDAPString(StringBuffer bld) { + operand.toLDAPString(bld); + } + + public void toString(StringBuffer bld, Variable rootVariable) { + operand.toString(bld, rootVariable); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Matches.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Matches.java new file mode 100644 index 000000000..da041b398 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Matches.java @@ -0,0 +1,95 @@ +/******************************************************************************* + * Copyright (c) 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.expression.*; + +/** + *

    A class that performs "matching" The actual algorithm used for + * performing the match varies depending on the types of the items to match.

    + *

    The following things can be matched:

    + * + * + * + * + * + * + *
    LHSRHSImplemented as
    {@link String}{@link SimplePattern}rhs.isMatch(lhs)
    {@link String}{@link LDAPApproximation}rhs.isMatch(lhs)
    <any>{@link Class}rhs.isInstance(lhs)
    {@link Class}{@link Class}rhs.isAssignableFrom(lhs)
    + */ +public class Matches extends Binary { + protected Matches(Expression lhs, Expression rhs) { + super(lhs, rhs); + } + + public Object evaluate(IEvaluationContext context) { + return Boolean.valueOf(match(lhs.evaluate(context), rhs.evaluate(context))); + } + + protected boolean match(Object lval, Object rval) { + if (rval instanceof VersionRange) { + VersionRange range = (VersionRange) rval; + if (lval instanceof Version) + return range.isIncluded((Version) lval); + if (lval instanceof String) + return range.isIncluded(Version.create((String) lval)); + } + if (rval instanceof SimplePattern) { + if (lval instanceof CharSequence) + return ((SimplePattern) rval).isMatch((CharSequence) lval); + if (lval instanceof Character || lval instanceof Number || lval instanceof Boolean) + return ((SimplePattern) rval).isMatch(lval.toString()); + + } else if (rval instanceof LDAPApproximation) { + if (lval instanceof CharSequence) + return ((LDAPApproximation) rval).isMatch((CharSequence) lval); + if (lval instanceof Character || lval instanceof Number || lval instanceof Boolean) + return ((LDAPApproximation) rval).isMatch(lval.toString()); + + } else if (rval instanceof Class) { + Class rclass = (Class) rval; + return lval instanceof Class ? rclass.isAssignableFrom((Class) lval) : rclass.isInstance(lval); + } + + if (lval == null || rval == null) + return false; + + throw new IllegalArgumentException("Cannot match a " + lval.getClass().getName() + " with a " + rval.getClass().getName()); //$NON-NLS-1$//$NON-NLS-2$ + } + + public int getExpressionType() { + return TYPE_MATCHES; + } + + public String getOperator() { + return OPERATOR_MATCHES; + } + + public void toLDAPString(StringBuffer buf) { + if (!(rhs instanceof Literal)) + throw new UnsupportedOperationException(); + + boolean escapeWild = true; + Object val = rhs.evaluate(null); + buf.append('('); + appendLDAPAttribute(buf); + if (val instanceof LDAPApproximation) { + buf.append(getOperator()); + } else if (val instanceof SimplePattern) { + buf.append('='); + escapeWild = false; + } else + throw new UnsupportedOperationException(); + appendLDAPEscaped(buf, val.toString(), escapeWild); + buf.append(')'); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Member.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Member.java new file mode 100644 index 000000000..5d442f62c --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Member.java @@ -0,0 +1,178 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.lang.reflect.*; +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; +import org.eclipse.equinox.p2.metadata.expression.IExpressionVisitor; + +/** + *

    An expression that performs member calls to obtain some value + * from some object instance. It uses standard bean semantics so + * that an attempt to obtain "value" will cause an + * attempt to call getValue() and if no such method + * exists, isValue() and if that doesn't work either, + * value().

    + */ +public abstract class Member extends Unary { + + public static final class DynamicMember extends Member { + private static final String GET_PREFIX = "get"; //$NON-NLS-1$ + private static final String IS_PREFIX = "is"; //$NON-NLS-1$ + private static final Class[] NO_ARG_TYPES = new Class[0]; + + private Class lastClass; + + private Method method; + private String methodName; + + DynamicMember(Expression operand, String name) { + super(operand, name, Expression.emptyArray); + if (!(name.startsWith(GET_PREFIX) || name.startsWith(IS_PREFIX))) + name = GET_PREFIX + Character.toUpperCase(name.charAt(0)) + name.substring(1); + this.methodName = name; + } + + public Object evaluate(IEvaluationContext context) { + return invoke(operand.evaluate(context)); + } + + public Object invoke(Object self) { + if (self == null) + throw new IllegalArgumentException("Cannot access member \'" + name + "\' in null"); //$NON-NLS-1$//$NON-NLS-2$ + + if (self instanceof MemberProvider) + return ((MemberProvider) self).getMember(name); + + Class c = self.getClass(); + if (lastClass == null || !lastClass.isAssignableFrom(c)) { + Method m; + for (;;) { + try { + m = c.getMethod(methodName, NO_ARG_TYPES); + if (!Modifier.isPublic(m.getModifiers())) + throw new NoSuchMethodException(); + break; + } catch (NoSuchMethodException e) { + if (methodName.startsWith(GET_PREFIX)) + // Switch from using getXxx() to isXxx() + methodName = IS_PREFIX + Character.toUpperCase(name.charAt(0)) + name.substring(1); + else if (methodName.startsWith(IS_PREFIX)) + // Switch from using isXxx() to xxx() + methodName = name; + else + throw new IllegalArgumentException("Cannot find a public member \'" + name + "\' in a " + self.getClass().getName()); //$NON-NLS-1$//$NON-NLS-2$ + } + } + + // Since we already checked that it's public. This will speed + // up the calls a bit. + m.setAccessible(true); + lastClass = c; + method = m; + } + + Exception checked; + try { + return method.invoke(self, NO_ARGS); + } catch (IllegalArgumentException e) { + throw e; + } catch (IllegalAccessException e) { + checked = e; + } catch (InvocationTargetException e) { + Throwable cause = e.getTargetException(); + if (cause instanceof RuntimeException) + throw (RuntimeException) cause; + if (cause instanceof Error) + throw (Error) cause; + checked = (Exception) cause; + } + throw new RuntimeException("Problem invoking " + methodName + " on a " + self.getClass().getName(), checked); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + static final Object[] NO_ARGS = new Object[0]; + + static Member createDynamicMember(Expression operand, String name) { + return new DynamicMember(operand, name); + } + + protected final Expression[] argExpressions; + + final String name; + + protected Member(Expression operand, String name, Expression[] args) { + super(operand); + this.name = name; + this.argExpressions = args; + } + + public boolean accept(IExpressionVisitor visitor) { + if (super.accept(visitor)) + for (int idx = 0; idx < argExpressions.length; ++idx) + if (!argExpressions[idx].accept(visitor)) + return false; + return true; + } + + public int compareTo(Expression e) { + int cmp = super.compareTo(e); + if (cmp == 0) { + cmp = name.compareTo(((Member) e).name); + if (cmp == 0) + cmp = compare(argExpressions, ((Member) e).argExpressions); + } + return cmp; + } + + public boolean equals(Object o) { + if (super.equals(o)) { + Member mo = (Member) o; + return name.equals(mo.name) && equals(argExpressions, mo.argExpressions); + } + return false; + } + + public int getExpressionType() { + return TYPE_MEMBER; + } + + public String getName() { + return name; + } + + public String getOperator() { + return OPERATOR_MEMBER; + } + + public int getPriority() { + return PRIORITY_MEMBER; + } + + public int hashCode() { + int result = 31 + name.hashCode(); + result = 31 * result + operand.hashCode(); + return 31 * result + hashCode(argExpressions); + } + + public void toString(StringBuffer bld, Variable rootVariable) { + if (operand != rootVariable) { + appendOperand(bld, rootVariable, operand, getPriority()); + bld.append('.'); + } + bld.append(name); + if (argExpressions.length > 0) { + bld.append('('); + elementsToString(bld, rootVariable, argExpressions); + bld.append(')'); + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/MemberProvider.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/MemberProvider.java new file mode 100644 index 000000000..9eb460a8d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/MemberProvider.java @@ -0,0 +1,139 @@ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.util.*; +import java.util.Map.Entry; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; +import org.osgi.framework.ServiceReference; + +public abstract class MemberProvider { + + static class DictionaryMemberProvider extends MemberProvider { + private final Dictionary dictionary; + + public DictionaryMemberProvider(Dictionary dictionary) { + this.dictionary = dictionary; + } + + @Override + public Object getMember(String memberName) { + return dictionary.get(memberName); + } + } + + static class CIDictionaryMemberProvider extends DictionaryMemberProvider { + public CIDictionaryMemberProvider(Dictionary dictionary) { + super(lowerCaseKeys(dictionary)); + } + + @Override + public Object getMember(String memberName) { + return super.getMember(memberName == null ? null : memberName.toLowerCase()); + } + + private static Dictionary lowerCaseKeys(Dictionary dictionary) { + boolean hasUpperCase = false; + for (Enumeration keys = dictionary.keys(); keys.hasMoreElements();) { + String key = keys.nextElement(); + if (key.toLowerCase() != key) { + hasUpperCase = true; + break; + } + } + if (!hasUpperCase) + return dictionary; + + Dictionary lcMap = new Hashtable(dictionary.size()); + for (Enumeration keys = dictionary.keys(); keys.hasMoreElements();) { + String key = keys.nextElement(); + if (lcMap.put(key.toLowerCase(), dictionary.get(key)) != null) + throw new IllegalArgumentException("case variants of the same key name: '" + key + '\''); //$NON-NLS-1$ + } + return lcMap; + } + } + + static class MapMemberProvider extends MemberProvider { + private final Map map; + + public MapMemberProvider(Map map) { + this.map = map; + } + + @Override + public Object getMember(String memberName) { + return map.get(memberName); + } + } + + static class CIMapMemberProvider extends MapMemberProvider { + public CIMapMemberProvider(Map map) { + super(lowerCaseKeys(map)); + } + + @Override + public Object getMember(String memberName) { + return super.getMember(memberName == null ? null : memberName.toLowerCase()); + } + + private static Map lowerCaseKeys(Map map) { + boolean hasUpperCase = false; + Set> entrySet = map.entrySet(); + for (Entry entry : entrySet) { + String key = entry.getKey(); + String lowKey = key.toLowerCase(); + if (key != lowKey) { + hasUpperCase = true; + break; + } + } + if (!hasUpperCase) + return map; + + Map lcMap = new HashMap(map.size()); + for (Entry entry : entrySet) { + if (lcMap.put(entry.getKey().toLowerCase(), entry.getValue()) != null) + throw new IllegalArgumentException("case variants of the same key name: '" + entry.getKey() + '\''); //$NON-NLS-1$ + } + return lcMap; + } + } + + static class ServiceRefMemberProvider extends MemberProvider { + private final ServiceReference serviceRef; + + public ServiceRefMemberProvider(ServiceReference serviceRef) { + this.serviceRef = serviceRef; + } + + @Override + public Object getMember(String memberName) { + return serviceRef.getProperty(memberName); + } + } + + private static final MemberProvider emptyProvider = create(CollectionUtils.emptyMap(), false); + + /** + * Create a new member provider on the given value. The value can be an instance of a {@link Map}, {@link Dictionary}, + * or {@link ServiceReference}. + * @param value The value that provides the members + * @param caseInsensitive true if the members should be retrievable in a case insensitive way. + * @return A member provided that is backed by value. + */ + @SuppressWarnings("unchecked") + public static MemberProvider create(Object value, boolean caseInsensitive) { + if (value instanceof Map) + return caseInsensitive ? new CIMapMemberProvider((Map) value) : new MapMemberProvider((Map) value); + if (value instanceof Dictionary) + return caseInsensitive ? new CIDictionaryMemberProvider((Dictionary) value) : new DictionaryMemberProvider((Dictionary) value); + if (value instanceof ServiceReference) + return new ServiceRefMemberProvider((ServiceReference) value); + throw new IllegalArgumentException(); + } + + public abstract Object getMember(String memberName); + + public static MemberProvider emptyProvider() { + return emptyProvider; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/NAry.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/NAry.java new file mode 100644 index 000000000..805cff2ab --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/NAry.java @@ -0,0 +1,59 @@ +/******************************************************************************* + * Copyright (c) 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import org.eclipse.equinox.p2.metadata.expression.IExpressionVisitor; + +/** + * The abstract baseclass for all N-ary expressions + */ +public abstract class NAry extends Expression { + public final Expression[] operands; + + protected NAry(Expression[] operands) { + this.operands = operands; + } + + public boolean accept(IExpressionVisitor visitor) { + if (super.accept(visitor)) + for (int idx = 0; idx < operands.length; ++idx) + if (!operands[idx].accept(visitor)) + return false; + return true; + } + + public int compareTo(Expression e) { + int cmp = super.compareTo(e); + if (cmp == 0) + cmp = compare(operands, ((NAry) e).operands); + return cmp; + } + + public boolean equals(Object o) { + return super.equals(o) && equals(operands, ((NAry) o).operands); + } + + public abstract String getOperator(); + + public int hashCode() { + return hashCode(operands); + } + + public void toString(StringBuffer bld, Variable rootVariable) { + appendOperand(bld, rootVariable, operands[0], getPriority()); + for (int idx = 1; idx < operands.length; ++idx) { + bld.append(' '); + bld.append(getOperator()); + bld.append(' '); + appendOperand(bld, rootVariable, operands[idx], getPriority()); + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Not.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Not.java new file mode 100644 index 000000000..5246859a3 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Not.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; + +/** + * An expression that yields true when its operand does not. + */ +final class Not extends Unary { + Not(Expression operand) { + super(operand); + } + + public Object evaluate(IEvaluationContext context) { + return Boolean.valueOf(operand.evaluate(context) != Boolean.TRUE); + } + + public int getExpressionType() { + return TYPE_NOT; + } + + public String getOperator() { + return OPERATOR_NOT; + } + + public int getPriority() { + return PRIORITY_NOT; + } + + public int hashCode() { + return 3 * operand.hashCode(); + } + + public void toLDAPString(StringBuffer buf) { + buf.append("(!"); //$NON-NLS-1$ + operand.toLDAPString(buf); + buf.append(')'); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Or.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Or.java new file mode 100644 index 000000000..32805042e --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Or.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; + +/** + * n-ary OR operator. The full evaluation is false if none of its operands + * evaluate to true. + */ +final class Or extends NAry { + public Or(Expression[] operands) { + super(assertLength(operands, 2, OPERATOR_OR)); + } + + public Object evaluate(IEvaluationContext context) { + for (int idx = 0; idx < operands.length; ++idx) { + if (operands[idx].evaluate(context) == Boolean.TRUE) + return Boolean.TRUE; + } + return Boolean.FALSE; + } + + public int getExpressionType() { + return TYPE_OR; + } + + public String getOperator() { + return OPERATOR_OR; + } + + public int getPriority() { + return PRIORITY_OR; + } + + public void toLDAPString(StringBuffer buf) { + buf.append("(|"); //$NON-NLS-1$ + for (int idx = 0; idx < operands.length; ++idx) + operands[idx].toLDAPString(buf); + buf.append(')'); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Parameter.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Parameter.java new file mode 100644 index 000000000..b4c56346e --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Parameter.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; + +/** + * The abstract base class for the indexed and keyed parameters + */ +public class Parameter extends Expression { + final int position; + + Parameter(int position) { + this.position = position; + } + + public int compareTo(Expression e) { + int cmp = super.compareTo(e); + if (cmp == 0) + cmp = position - ((Parameter) e).position; + return cmp; + } + + public boolean equals(Object o) { + if (o == this) + return true; + if (o == null) + return false; + return getClass() == o.getClass() && position == ((Parameter) o).position; + } + + public Object evaluate(IEvaluationContext context) { + return context.getParameter(position); + } + + public int getExpressionType() { + return TYPE_PARAMETER; + } + + public String getOperator() { + return OPERATOR_PARAMETER; + } + + public int getPriority() { + return PRIORITY_VARIABLE; + } + + public int hashCode() { + return 31 * (1 + position); + } + + public void toString(StringBuffer bld, Variable rootVariable) { + bld.append('$'); + bld.append(position); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/RepeatableIterator.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/RepeatableIterator.java new file mode 100644 index 000000000..e44a4e507 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/RepeatableIterator.java @@ -0,0 +1,237 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.util.*; +import org.eclipse.equinox.p2.query.IQueryResult; + +public class RepeatableIterator implements IRepeatableIterator { + private final List values; + private int position = -1; + + @SuppressWarnings("unchecked") + public static IRepeatableIterator create(Object unknown) { + if (unknown.getClass().isArray()) + return create((T[]) unknown); + if (unknown instanceof Iterator) + return create((Iterator) unknown); + if (unknown instanceof List) + return create((List) unknown); + if (unknown instanceof Collection) + return create((Collection) unknown); + if (unknown instanceof Map) + return create((Set) ((Map) unknown).entrySet()); + if (unknown instanceof IQueryResult) + return create((IQueryResult) unknown); + throw new IllegalArgumentException("Cannot convert a " + unknown.getClass().getName() + " into an iterator"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public static IRepeatableIterator create(Iterator iterator) { + return iterator instanceof IRepeatableIterator ? ((IRepeatableIterator) iterator).getCopy() : new ElementRetainingIterator(iterator); + } + + public static IRepeatableIterator create(List values) { + return new RepeatableIterator(values); + } + + public static IRepeatableIterator create(Collection values) { + return new CollectionIterator(values); + } + + public static IRepeatableIterator create(IQueryResult values) { + return new QueryResultIterator(values); + } + + public static IRepeatableIterator create(T[] values) { + return new ArrayIterator(values); + } + + RepeatableIterator(List values) { + this.values = values; + } + + public IRepeatableIterator getCopy() { + return new RepeatableIterator(values); + } + + public boolean hasNext() { + return position + 1 < values.size(); + } + + public T next() { + if (++position == values.size()) { + --position; + throw new NoSuchElementException(); + } + return values.get(position); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + + public Object getIteratorProvider() { + return values; + } + + void setPosition(int position) { + this.position = position; + } + + List getValues() { + return values; + } + + static class ArrayIterator implements IRepeatableIterator { + private final T[] array; + private int position = -1; + + public ArrayIterator(T[] array) { + this.array = array; + } + + public Object getIteratorProvider() { + return array; + } + + public boolean hasNext() { + return position + 1 < array.length; + } + + public T next() { + if (++position >= array.length) + throw new NoSuchElementException(); + return array[position]; + } + + public void remove() { + throw new UnsupportedOperationException(); + } + + public IRepeatableIterator getCopy() { + return new ArrayIterator(array); + } + } + + static class CollectionIterator implements IRepeatableIterator { + private final Collection collection; + + private final Iterator iterator; + + CollectionIterator(Collection collection) { + this.collection = collection; + this.iterator = collection.iterator(); + } + + public IRepeatableIterator getCopy() { + return new CollectionIterator(collection); + } + + public Object getIteratorProvider() { + return collection; + } + + public boolean hasNext() { + return iterator.hasNext(); + } + + public T next() { + return iterator.next(); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + } + + static class QueryResultIterator implements IRepeatableIterator { + private final IQueryResult queryResult; + + private final Iterator iterator; + + QueryResultIterator(IQueryResult queryResult) { + this.queryResult = queryResult; + this.iterator = queryResult.iterator(); + } + + public IRepeatableIterator getCopy() { + return new QueryResultIterator(queryResult); + } + + public Object getIteratorProvider() { + return queryResult; + } + + public boolean hasNext() { + return iterator.hasNext(); + } + + public T next() { + return iterator.next(); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + } + + static class ElementRetainingIterator extends RepeatableIterator { + + private Iterator innerIterator; + + ElementRetainingIterator(Iterator iterator) { + super(new ArrayList()); + innerIterator = iterator; + } + + public synchronized boolean hasNext() { + if (innerIterator != null) { + if (innerIterator.hasNext()) + return true; + innerIterator = null; + setPosition(getValues().size()); + } + return super.hasNext(); + } + + public synchronized T next() { + if (innerIterator != null) { + T val = innerIterator.next(); + getValues().add(val); + return val; + } + return super.next(); + } + + public synchronized IRepeatableIterator getCopy() { + // If the current iterator still exists, we must exhaust it first + // + exhaustInnerIterator(); + return super.getCopy(); + } + + public synchronized Object getIteratorProvider() { + exhaustInnerIterator(); + return super.getIteratorProvider(); + } + + private void exhaustInnerIterator() { + if (innerIterator != null) { + List values = getValues(); + int savePos = values.size() - 1; + while (innerIterator.hasNext()) + values.add(innerIterator.next()); + innerIterator = null; + setPosition(savePos); + } + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Unary.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Unary.java new file mode 100644 index 000000000..9c6b7d8a5 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Unary.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; +import org.eclipse.equinox.p2.metadata.expression.IExpressionVisitor; + +/** + * The abstract base class for all unary expressions + */ +public abstract class Unary extends Expression { + public final Expression operand; + + protected Unary(Expression operand) { + this.operand = operand; + } + + public boolean accept(IExpressionVisitor visitor) { + return super.accept(visitor) && operand.accept(visitor); + } + + public int compareTo(Expression e) { + int cmp = super.compareTo(e); + if (cmp == 0) + cmp = operand.compareTo(((Unary) e).operand); + return cmp; + } + + public boolean equals(Object o) { + return super.equals(o) && operand.equals(((Unary) o).operand); + } + + public Object evaluate(IEvaluationContext context) { + return operand.evaluate(context); + } + + public int hashCode() { + return operand.hashCode() * 3 + operand.getExpressionType(); + } + + public Expression getOperand() { + return operand; + } + + public void toString(StringBuffer bld, Variable rootVariable) { + bld.append(getOperator()); + appendOperand(bld, rootVariable, operand, getPriority()); + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Variable.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Variable.java new file mode 100644 index 000000000..a7adfb738 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/Variable.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression; + +import java.util.Iterator; +import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext; + +/** + * An expression representing a variable stack in the current thread. + */ +public class Variable extends Expression { + + private final String name; + + public Variable(String name) { + this.name = name; + } + + public int compareTo(Expression e) { + int cmp = super.compareTo(e); + if (cmp == 0) + cmp = name.compareTo(((Variable) e).name); + return cmp; + } + + public boolean equals(Object o) { + return super.equals(o) && name.equals(((Variable) o).name); + } + + public final Object evaluate(IEvaluationContext context) { + return context.getValue(this); + } + + public Iterator evaluateAsIterator(IEvaluationContext context) { + Object value = context.getValue(this); + if (value instanceof IRepeatableIterator) + return ((IRepeatableIterator) value).getCopy(); + + Iterator itor = RepeatableIterator.create(value); + setValue(context, itor); + return itor; + } + + public int getExpressionType() { + return TYPE_VARIABLE; + } + + public String getName() { + return name; + } + + public String getOperator() { + return ""; //$NON-NLS-1$ + } + + public int getPriority() { + return PRIORITY_VARIABLE; + } + + public int hashCode() { + return name.hashCode(); + } + + public final void setValue(IEvaluationContext context, Object value) { + context.setValue(this, value); + } + + public void toString(StringBuffer bld, Variable rootVariable) { + bld.append(name); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/parser/ExpressionParser.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/parser/ExpressionParser.java new file mode 100644 index 000000000..905d0927c --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/parser/ExpressionParser.java @@ -0,0 +1,617 @@ +/******************************************************************************* + * Copyright (c) 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression.parser; + +import org.eclipse.equinox.internal.p2.metadata.expression.LDAPApproximation; + +import java.util.*; +import org.eclipse.equinox.internal.p2.metadata.expression.IExpressionConstants; +import org.eclipse.equinox.p2.metadata.expression.*; + +public class ExpressionParser extends Stack implements IExpressionConstants, IExpressionParser { + private static final long serialVersionUID = 5481439062356612378L; + + protected static final int TOKEN_OR = 1; + protected static final int TOKEN_AND = 2; + + protected static final int TOKEN_EQUAL = 10; + protected static final int TOKEN_NOT_EQUAL = 11; + protected static final int TOKEN_LESS = 12; + protected static final int TOKEN_LESS_EQUAL = 13; + protected static final int TOKEN_GREATER = 14; + protected static final int TOKEN_GREATER_EQUAL = 15; + protected static final int TOKEN_MATCHES = 16; + + protected static final int TOKEN_NOT = 20; + protected static final int TOKEN_DOT = 21; + protected static final int TOKEN_COMMA = 22; + protected static final int TOKEN_PIPE = 23; + protected static final int TOKEN_DOLLAR = 24; + protected static final int TOKEN_IF = 25; + protected static final int TOKEN_ELSE = 26; + + protected static final int TOKEN_LP = 30; + protected static final int TOKEN_RP = 31; + protected static final int TOKEN_LB = 32; + protected static final int TOKEN_RB = 33; + protected static final int TOKEN_LC = 34; + protected static final int TOKEN_RC = 35; + + protected static final int TOKEN_IDENTIFIER = 40; + protected static final int TOKEN_LITERAL = 41; + + protected static final int TOKEN_NULL = 50; + protected static final int TOKEN_TRUE = 51; + protected static final int TOKEN_FALSE = 52; + + private static final int TOKEN_ALL = 60; + private static final int TOKEN_EXISTS = 61; + + protected static final int TOKEN_END = 0; + protected static final int TOKEN_ERROR = -1; + + protected static final Map keywords; + static { + keywords = new HashMap(); + keywords.put(KEYWORD_FALSE, new Integer(TOKEN_FALSE)); + keywords.put(KEYWORD_NULL, new Integer(TOKEN_NULL)); + keywords.put(KEYWORD_TRUE, new Integer(TOKEN_TRUE)); + keywords.put(KEYWORD_ALL, new Integer(TOKEN_ALL)); + keywords.put(KEYWORD_EXISTS, new Integer(TOKEN_EXISTS)); + } + + protected final IExpressionFactory factory; + + protected String expression; + protected int tokenPos; + protected int currentToken; + protected int lastTokenPos; + protected Object tokenValue; + protected String rootVariable; + + public ExpressionParser(IExpressionFactory factory) { + this.factory = factory; + } + + public synchronized IExpression parse(String exprString) { + expression = exprString; + tokenPos = 0; + currentToken = 0; + tokenValue = null; + IExpression thisVariable = factory.thisVariable(); + rootVariable = ExpressionUtil.getName(thisVariable); + push(thisVariable); + try { + nextToken(); + IExpression expr = currentToken == TOKEN_END ? factory.constant(Boolean.TRUE) : parseCondition(); + assertToken(TOKEN_END); + return expr; + } finally { + if (thisVariable != null) + popVariable(); // pop item + } + } + + protected Map keywordToTokenMap() { + return keywords; + } + + protected IExpression parseCondition() { + // Just a hook in this parser. Conditions are not supported + return parseOr(); + } + + protected IExpression parseOr() { + IExpression expr = parseAnd(); + if (currentToken != TOKEN_OR) + return expr; + + ArrayList exprs = new ArrayList(); + exprs.add(expr); + do { + nextToken(); + exprs.add(parseAnd()); + } while (currentToken == TOKEN_OR); + return factory.or(exprs.toArray(new IExpression[exprs.size()])); + } + + protected IExpression parseAnd() { + IExpression expr = parseBinary(); + if (currentToken != TOKEN_AND) + return expr; + + ArrayList exprs = new ArrayList(); + exprs.add(expr); + do { + nextToken(); + exprs.add(parseBinary()); + } while (currentToken == TOKEN_AND); + return factory.and(exprs.toArray(new IExpression[exprs.size()])); + } + + protected IExpression parseBinary() { + IExpression expr = parseNot(); + for (;;) { + switch (currentToken) { + case TOKEN_OR : + case TOKEN_AND : + case TOKEN_RP : + case TOKEN_RB : + case TOKEN_RC : + case TOKEN_COMMA : + case TOKEN_IF : + case TOKEN_ELSE : + case TOKEN_END : + break; + case TOKEN_EQUAL : + case TOKEN_NOT_EQUAL : + case TOKEN_GREATER : + case TOKEN_GREATER_EQUAL : + case TOKEN_LESS : + case TOKEN_LESS_EQUAL : + case TOKEN_MATCHES : + int realToken = currentToken; + nextToken(); + IExpression rhs; + if (realToken == TOKEN_MATCHES && currentToken == TOKEN_LITERAL && tokenValue instanceof String) + rhs = factory.constant(new LDAPApproximation((String) tokenValue)); + else + rhs = parseNot(); + switch (realToken) { + case TOKEN_EQUAL : + expr = factory.equals(expr, rhs); + break; + case TOKEN_NOT_EQUAL : + expr = factory.not(factory.equals(expr, rhs)); + break; + case TOKEN_GREATER : + expr = factory.greater(expr, rhs); + break; + case TOKEN_GREATER_EQUAL : + expr = factory.greaterEqual(expr, rhs); + break; + case TOKEN_LESS : + expr = factory.less(expr, rhs); + break; + case TOKEN_LESS_EQUAL : + expr = factory.lessEqual(expr, rhs); + break; + default : + expr = factory.matches(expr, rhs); + } + continue; + default : + throw syntaxError(); + } + break; + } + return expr; + } + + protected IExpression parseNot() { + if (currentToken == TOKEN_NOT) { + nextToken(); + IExpression expr = parseNot(); + return factory.not(expr); + } + return parseCollectionExpression(); + } + + protected IExpression parseCollectionExpression() { + IExpression expr = parseCollectionLHS(); + if (expr == null) { + expr = parseMember(); + if (currentToken != TOKEN_DOT) + return expr; + nextToken(); + } + for (;;) { + int funcToken = currentToken; + nextToken(); + assertToken(TOKEN_LP); + nextToken(); + expr = parseCollectionRHS(expr, funcToken); + if (currentToken != TOKEN_DOT) + break; + nextToken(); + } + return expr; + } + + protected IExpression parseCollectionLHS() { + IExpression expr = null; + switch (currentToken) { + case TOKEN_EXISTS : + case TOKEN_ALL : + expr = getVariableOrRootMember(rootVariable); + break; + } + return expr; + } + + protected IExpression parseCollectionRHS(IExpression expr, int funcToken) { + switch (funcToken) { + case TOKEN_EXISTS : + expr = factory.exists(expr, parseLambdaDefinition()); + break; + case TOKEN_ALL : + expr = factory.all(expr, parseLambdaDefinition()); + break; + default : + throw syntaxError(); + } + return expr; + } + + protected IExpression parseLambdaDefinition() { + assertToken(TOKEN_IDENTIFIER); + IExpression each = factory.variable((String) tokenValue); + push(each); + try { + nextToken(); + assertToken(TOKEN_PIPE); + nextToken(); + IExpression body = parseCondition(); + assertToken(TOKEN_RP); + nextToken(); + return factory.lambda(each, body); + } finally { + pop(); + } + } + + protected IExpression parseMember() { + IExpression expr = parseUnary(); + String name; + while (currentToken == TOKEN_DOT || currentToken == TOKEN_LB) { + int savePos = tokenPos; + int saveToken = currentToken; + Object saveTokenValue = tokenValue; + nextToken(); + if (saveToken == TOKEN_DOT) { + switch (currentToken) { + case TOKEN_IDENTIFIER : + name = (String) tokenValue; + nextToken(); + expr = factory.member(expr, name); + break; + + default : + tokenPos = savePos; + currentToken = saveToken; + tokenValue = saveTokenValue; + return expr; + } + } else { + IExpression atExpr = parseMember(); + assertToken(TOKEN_RB); + nextToken(); + expr = factory.at(expr, atExpr); + } + } + return expr; + } + + protected IExpression parseUnary() { + IExpression expr; + switch (currentToken) { + case TOKEN_LP : + nextToken(); + expr = parseCondition(); + assertToken(TOKEN_RP); + nextToken(); + break; + case TOKEN_LITERAL : + expr = factory.constant(tokenValue); + nextToken(); + break; + case TOKEN_IDENTIFIER : + expr = getVariableOrRootMember((String) tokenValue); + nextToken(); + break; + case TOKEN_NULL : + expr = factory.constant(null); + nextToken(); + break; + case TOKEN_TRUE : + expr = factory.constant(Boolean.TRUE); + nextToken(); + break; + case TOKEN_FALSE : + expr = factory.constant(Boolean.FALSE); + nextToken(); + break; + case TOKEN_DOLLAR : + expr = parseParameter(); + break; + default : + throw syntaxError(); + } + return expr; + } + + private IExpression parseParameter() { + if (currentToken == TOKEN_DOLLAR) { + nextToken(); + if (currentToken == TOKEN_LITERAL && tokenValue instanceof Integer) { + IExpression param = factory.indexedParameter(((Integer) tokenValue).intValue()); + nextToken(); + return param; + } + } + throw syntaxError(); + } + + protected IExpression[] parseArray() { + IExpression expr = parseCondition(); + if (currentToken != TOKEN_COMMA) + return new IExpression[] {expr}; + + ArrayList operands = new ArrayList(); + operands.add(expr); + do { + nextToken(); + if (currentToken == TOKEN_LC) + // We don't allow lambdas in the array + break; + operands.add(parseCondition()); + } while (currentToken == TOKEN_COMMA); + return operands.toArray(new IExpression[operands.size()]); + } + + protected void assertToken(int token) { + if (currentToken != token) + throw syntaxError(); + } + + protected IExpression getVariableOrRootMember(String id) { + int idx = size(); + while (--idx >= 0) { + IExpression v = get(idx); + if (id.equals(v.toString())) + return v; + } + + if (rootVariable == null || rootVariable.equals(id)) + throw syntaxError("No such variable: " + id); //$NON-NLS-1$ + + return factory.member(getVariableOrRootMember(rootVariable), id); + } + + protected void nextToken() { + tokenValue = null; + int top = expression.length(); + char c = 0; + while (tokenPos < top) { + c = expression.charAt(tokenPos); + if (!Character.isWhitespace(c)) + break; + ++tokenPos; + } + if (tokenPos >= top) { + lastTokenPos = top; + currentToken = TOKEN_END; + return; + } + + lastTokenPos = tokenPos; + switch (c) { + case '|' : + if (tokenPos + 1 < top && expression.charAt(tokenPos + 1) == '|') { + tokenValue = OPERATOR_OR; + currentToken = TOKEN_OR; + tokenPos += 2; + } else { + currentToken = TOKEN_PIPE; + ++tokenPos; + } + break; + + case '&' : + if (tokenPos + 1 < top && expression.charAt(tokenPos + 1) == '&') { + tokenValue = OPERATOR_AND; + currentToken = TOKEN_AND; + tokenPos += 2; + } else + currentToken = TOKEN_ERROR; + break; + + case '=' : + if (tokenPos + 1 < top && expression.charAt(tokenPos + 1) == '=') { + tokenValue = OPERATOR_EQUALS; + currentToken = TOKEN_EQUAL; + tokenPos += 2; + } else + currentToken = TOKEN_ERROR; + break; + + case '!' : + if (tokenPos + 1 < top && expression.charAt(tokenPos + 1) == '=') { + tokenValue = OPERATOR_NOT_EQUALS; + currentToken = TOKEN_NOT_EQUAL; + tokenPos += 2; + } else { + currentToken = TOKEN_NOT; + ++tokenPos; + } + break; + + case '~' : + if (tokenPos + 1 < top && expression.charAt(tokenPos + 1) == '=') { + tokenValue = OPERATOR_MATCHES; + currentToken = TOKEN_MATCHES; + tokenPos += 2; + } else + currentToken = TOKEN_ERROR; + break; + + case '>' : + if (tokenPos + 1 < top && expression.charAt(tokenPos + 1) == '=') { + tokenValue = OPERATOR_GT_EQUAL; + currentToken = TOKEN_GREATER_EQUAL; + tokenPos += 2; + } else { + currentToken = TOKEN_GREATER; + ++tokenPos; + } + break; + + case '<' : + if (tokenPos + 1 < top && expression.charAt(tokenPos + 1) == '=') { + tokenValue = OPERATOR_LT_EQUAL; + currentToken = TOKEN_LESS_EQUAL; + tokenPos += 2; + } else { + currentToken = TOKEN_LESS; + ++tokenPos; + } + break; + + case '?' : + currentToken = TOKEN_IF; + ++tokenPos; + break; + + case ':' : + currentToken = TOKEN_ELSE; + ++tokenPos; + break; + + case '.' : + currentToken = TOKEN_DOT; + ++tokenPos; + break; + + case '$' : + currentToken = TOKEN_DOLLAR; + ++tokenPos; + break; + + case '{' : + currentToken = TOKEN_LC; + ++tokenPos; + break; + + case '}' : + currentToken = TOKEN_RC; + ++tokenPos; + break; + + case '(' : + currentToken = TOKEN_LP; + ++tokenPos; + break; + + case ')' : + currentToken = TOKEN_RP; + ++tokenPos; + break; + + case '[' : + currentToken = TOKEN_LB; + ++tokenPos; + break; + + case ']' : + currentToken = TOKEN_RB; + ++tokenPos; + break; + + case ',' : + currentToken = TOKEN_COMMA; + ++tokenPos; + break; + + case '"' : + case '\'' : { + int start = ++tokenPos; + while (tokenPos < top && expression.charAt(tokenPos) != c) + ++tokenPos; + if (tokenPos == top) { + tokenPos = start - 1; + currentToken = TOKEN_ERROR; + } else { + tokenValue = expression.substring(start, tokenPos++); + currentToken = TOKEN_LITERAL; + } + break; + } + + case '/' : { + int start = ++tokenPos; + StringBuffer buf = new StringBuffer(); + while (tokenPos < top) { + c = expression.charAt(tokenPos); + if (c == '\\' && tokenPos + 1 < top) { + c = expression.charAt(++tokenPos); + if (c != '/') + buf.append('\\'); + } else if (c == '/') + break; + buf.append(c); + ++tokenPos; + } + if (tokenPos == top) { + tokenPos = start - 1; + currentToken = TOKEN_ERROR; + } else { + tokenValue = SimplePattern.compile(expression.substring(start, tokenPos++)); + currentToken = TOKEN_LITERAL; + } + break; + } + + default : + if (Character.isDigit(c)) { + int start = tokenPos++; + while (tokenPos < top && Character.isDigit(expression.charAt(tokenPos))) + ++tokenPos; + tokenValue = Integer.valueOf(expression.substring(start, tokenPos)); + currentToken = TOKEN_LITERAL; + break; + } + if (Character.isJavaIdentifierStart(c)) { + int start = tokenPos++; + while (tokenPos < top && Character.isJavaIdentifierPart(expression.charAt(tokenPos))) + ++tokenPos; + String word = expression.substring(start, tokenPos); + Integer token = keywordToTokenMap().get(word); + if (token == null) + currentToken = TOKEN_IDENTIFIER; + else + currentToken = token.intValue(); + tokenValue = word; + break; + } + throw syntaxError(); + } + } + + protected void popVariable() { + if (isEmpty()) + throw syntaxError(); + pop(); + } + + protected ExpressionParseException syntaxError() { + Object tv = tokenValue; + if (tv == null) { + if (lastTokenPos >= expression.length()) + return syntaxError("Unexpeced end of expression"); //$NON-NLS-1$ + tv = expression.substring(lastTokenPos, lastTokenPos + 1); + } + return syntaxError("Unexpected token \"" + tv + '"'); //$NON-NLS-1$ + } + + protected ExpressionParseException syntaxError(String message) { + return new ExpressionParseException(expression, message, tokenPos); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/parser/LDAPFilterParser.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/parser/LDAPFilterParser.java new file mode 100644 index 000000000..b5fd6714c --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/expression/parser/LDAPFilterParser.java @@ -0,0 +1,268 @@ +/******************************************************************************* + * Copyright (c) 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.expression.parser; + +import java.util.ArrayList; +import org.eclipse.equinox.internal.p2.metadata.Messages; +import org.eclipse.equinox.internal.p2.metadata.expression.IExpressionConstants; +import org.eclipse.equinox.internal.p2.metadata.expression.LDAPApproximation; +import org.eclipse.equinox.p2.metadata.expression.*; +import org.eclipse.osgi.util.NLS; + +/** + * Parser class for OSGi filter strings. This class parses the complete filter string and builds a tree of Filter + * objects rooted at the parent. + */ +public class LDAPFilterParser { + private final IExpressionFactory factory; + + private final IExpression self; + + private final StringBuffer sb = new StringBuffer(); + + private String filterString; + + private int position; + + public LDAPFilterParser(IExpressionFactory factory) { + this.factory = factory; + self = factory.variable(IExpressionConstants.VARIABLE_THIS); + position = 0; + } + + public synchronized IFilterExpression parse(String filter) { + filterString = filter; + position = 0; + try { + IExpression expr = parseFilter(); + if (position != filterString.length()) + throw syntaxException(Messages.filter_trailing_characters); + return factory.filterExpression(expr); + } catch (StringIndexOutOfBoundsException e) { + throw syntaxException(Messages.filter_premature_end); + } + } + + private IExpression parseAnd() { + skipWhiteSpace(); + char c = filterString.charAt(position); + if (c != '(') + throw syntaxException(Messages.filter_missing_leftparen); + + ArrayList operands = new ArrayList(); + while (c == '(') { + IExpression child = parseFilter(); + if (!operands.contains(child)) + operands.add(child); + c = filterString.charAt(position); + } + // int sz = operands.size(); + // return sz == 1 ? operands.get(0) : factory.and(operands.toArray(new IExpression[sz])); + return factory.normalize(operands, IExpression.TYPE_AND); + } + + private IExpression parseAttr() { + skipWhiteSpace(); + + int begin = position; + int end = position; + + char c = filterString.charAt(begin); + while (!(c == '~' || c == '<' || c == '>' || c == '=' || c == '(' || c == ')')) { + position++; + if (!Character.isWhitespace(c)) + end = position; + c = filterString.charAt(position); + } + if (end == begin) + throw syntaxException(Messages.filter_missing_attr); + return factory.member(self, filterString.substring(begin, end)); + } + + private IExpression parseFilter() { + IExpression filter; + skipWhiteSpace(); + + if (filterString.charAt(position) != '(') + throw syntaxException(Messages.filter_missing_leftparen); + + position++; + filter = parseFiltercomp(); + + skipWhiteSpace(); + + if (filterString.charAt(position) != ')') + throw syntaxException(Messages.filter_missing_rightparen); + + position++; + skipWhiteSpace(); + + return filter; + } + + private IExpression parseFiltercomp() { + skipWhiteSpace(); + + char c = filterString.charAt(position); + + switch (c) { + case '&' : { + position++; + return parseAnd(); + } + case '|' : { + position++; + return parseOr(); + } + case '!' : { + position++; + return parseNot(); + } + } + return parseItem(); + } + + private IExpression parseItem() { + IExpression attr = parseAttr(); + + skipWhiteSpace(); + String value; + + boolean[] hasWild = {false}; + char c = filterString.charAt(position); + switch (c) { + case '~' : + case '>' : + case '<' : + if (filterString.charAt(position + 1) != '=') + throw syntaxException(Messages.filter_invalid_operator); + position += 2; + int savePos = position; + value = parseValue(hasWild); + if (hasWild[0]) { + // Unescaped wildcard found. This is not legal for the given operator + position = savePos; + throw syntaxException(Messages.filter_invalid_value); + } + switch (c) { + case '>' : + return factory.greaterEqual(attr, factory.constant(value)); + case '<' : + return factory.lessEqual(attr, factory.constant(value)); + } + return factory.matches(attr, factory.constant(new LDAPApproximation(value))); + case '=' : + position++; + value = parseValue(hasWild); + return hasWild[0] ? factory.matches(attr, factory.constant(SimplePattern.compile(value))) : factory.equals(attr, factory.constant(value)); + } + throw syntaxException(Messages.filter_invalid_operator); + } + + private IExpression parseNot() { + skipWhiteSpace(); + + if (filterString.charAt(position) != '(') + throw syntaxException(Messages.filter_missing_leftparen); + return factory.not(parseFilter()); + } + + private IExpression parseOr() { + skipWhiteSpace(); + char c = filterString.charAt(position); + if (c != '(') + throw syntaxException(Messages.filter_missing_leftparen); + + ArrayList operands = new ArrayList(); + while (c == '(') { + IExpression child = parseFilter(); + operands.add(child); + c = filterString.charAt(position); + } + // int sz = operands.size(); + // return sz == 1 ? operands.get(0) : factory.or(operands.toArray(new IExpression[sz])); + return factory.normalize(operands, IExpression.TYPE_OR); + } + + private static int hexValue(char c) { + int v; + if (c <= '9') + v = c - '0'; + else if (c <= 'F') + v = (c - 'A') + 10; + else + v = (c - 'a') + 10; + return v; + } + + private String parseValue(boolean[] hasWildBin) { + sb.setLength(0); + int savePos = position; + boolean hasEscapedWild = false; + parseloop: while (true) { + char c = filterString.charAt(position); + switch (c) { + case '*' : + if (hasEscapedWild && !hasWildBin[0]) { + // We must redo the parse. + position = savePos; + hasWildBin[0] = true; + return parseValue(hasWildBin); + } + hasWildBin[0] = true; + sb.append(c); + position++; + break; + + case ')' : + break parseloop; + + case '(' : + throw syntaxException(Messages.filter_invalid_value); + + case '\\' : + c = filterString.charAt(++position); + if (c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f' && position + 1 < filterString.length()) { + char nc = filterString.charAt(position + 1); + if (nc >= '0' && nc <= '9' || nc >= 'A' && nc <= 'F' || nc >= 'a' && nc <= 'f') { + // Assume proper \xx escape where xx are hex digits + ++position; + c = (char) (((hexValue(c) << 4) & 0xf0) | (hexValue(nc) & 0x0f)); + if (c == '*' && hasWildBin != null) { + hasEscapedWild = true; + if (hasWildBin[0]) + sb.append('\\'); + } + } + } + /* fall through into default */ + + default : + sb.append(c); + position++; + break; + } + } + if (sb.length() == 0) + throw syntaxException(Messages.filter_missing_value); + return sb.toString(); + } + + private void skipWhiteSpace() { + for (int top = filterString.length(); position < top; ++position) + if (!Character.isWhitespace(filterString.charAt(position))) + break; + } + + protected ExpressionParseException syntaxException(String message) { + return new ExpressionParseException(NLS.bind(message, filterString, Integer.toString(position))); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/messages.properties b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/messages.properties index 2d675ff07..a70676f45 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/messages.properties +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/messages.properties @@ -8,8 +8,6 @@ # Contributors: # Cloudsmith Inc. - initial API and implementation ############################################################################### -_0_is_not_a_positive_integer_in_osgi_1=The {0} value is not a positive in OSGi version: "{1}" -_0_is_not_a_string_in_osgi_1=The {0} value is not a string in OSGi version: "{1}" _0_is_not_a_valid_qualifier_in_osgi_1=The {0} value is invalid in OSGi version: "{1}" array_can_not_be_empty=Array format can not be empty array_can_not_have_character_group=Array format can not have a character group @@ -27,6 +25,14 @@ EOS_after_escape=End of string was encountere after the escape character expected_orignal_after_colon_0=An original version was expected after colon: {0} expected_orignal_after_slash_0=A format or colon was expected after slash: {0} expected_slash_after_raw_vector_0=A slash was expected after a raw version: {0} +filter_missing_leftparen=Filter "{0}" Missing ''('' at position {1} +filter_missing_rightparen=Filter "{0}" Missing '')'' at position {1} +filter_trailing_characters=Filter "{0}" Extraneous trailing characters at position {1} +filter_invalid_operator=Filter "{0}" Invalid operator at position {1} +filter_missing_attr=Filter "{0}" Missing attr at position {1} +filter_missing_value=Filter "{0}" is missing value at position {1} +filter_invalid_value=Filter "{0}" has invalid value at position {1} +filter_premature_end=Filter "{0}" ends before it is complete format_0_unable_to_parse_1=Format "{0}" was unable to parse {1} format_0_unable_to_parse_empty_version=Format "{0}" was unable to parse an empty version format_is_empty=Format is empty @@ -34,16 +40,15 @@ format_must_be_delimited_by_colon_0=Format must be delimited by version range: { group_can_not_be_empty=A group can not be empty ignore_defined_more_then_once=More then one definition of ignore illegal_character_encountered_ascii_0=An illegal character was encountered. Code = {0} -illegal_number_of_entries_0_in_osgi_1=Illegal number of entries {0} in OSGi version: "{1}" missing_comma_in_range_0=Missing comma in range "{0}" negative_character_range=The character range is negative neither_raw_vector_nor_format_specified_0=Neither raw version nor format was specified: {0} number_can_not_have_pad_value=A number cannot have a pad value only_format_specified_0=Only a format was specified: {0} +only_max_and_empty_string_defaults_can_have_translations=Only max string and empty string defaults can have translations original_must_start_with_colon_0=Original version must start with colon: {0} original_stated_but_missing_0=Expected original version after colon: {0} pad_defined_more_then_once=Pad was defined more then once -pad_not_allowed_in_osgi_0=Pad is not allowed in an OSGi version: "{0}" performing_subquery=Performing subquery premature_end_of_format=Premature end of format premature_end_of_format_expected_0=Premature end of format, "{0}" expected diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/IUPropertyQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/IUPropertyQuery.java new file mode 100644 index 000000000..95f3f3375 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/IUPropertyQuery.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.query; + +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.MatchQuery; + +/** + * A query that searches for {@link IInstallableUnit} instances that have + * a property whose value matches the provided value. If no property name is + * specified, then all {@link IInstallableUnit} instances are accepted. + */ +public class IUPropertyQuery extends MatchQuery { + private String propertyName; + private String propertyValue; + + /** + * Creates a new query on the given property name and value. + */ + public IUPropertyQuery(String propertyName, String propertyValue) { + this.propertyName = propertyName; + this.propertyValue = propertyValue; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.query2.Query#isMatch(java.lang.Object) + */ + public boolean isMatch(IInstallableUnit candidate) { + if (propertyName == null) + return true; + String value = getProperty(candidate, propertyName); + if (value != null && (value.equals(propertyValue) || propertyValue == null)) + return true; + return false; + } + + protected String getProperty(IInstallableUnit iu, String name) { + return iu.getProperty(name); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/LatestIUVersionQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/LatestIUVersionQuery.java new file mode 100644 index 000000000..fe79d9404 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/LatestIUVersionQuery.java @@ -0,0 +1,48 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.query; + +import java.util.*; +import org.eclipse.equinox.p2.metadata.IVersionedId; +import org.eclipse.equinox.p2.query.*; + +/** + * This query returns the latest version for each unique VersionedID. + * All other elements are discarded. + */ +public class LatestIUVersionQuery extends ContextQuery { + + /** + * Performs the LatestIUVersionQuery + */ + public IQueryResult perform(Iterator iterator) { + HashMap greatestIUVersion = new HashMap(); + while (iterator.hasNext()) { + T versionedID = iterator.next(); + if (greatestIUVersion.containsKey(versionedID.getId())) { + T currentIU = greatestIUVersion.get(versionedID.getId()); + if (currentIU.getVersion().compareTo(versionedID.getVersion()) < 0) + greatestIUVersion.put(versionedID.getId(), versionedID); + } else + greatestIUVersion.put(versionedID.getId(), versionedID); + } + + Collection values = greatestIUVersion.values(); + Iterator valuesIterator = values.iterator(); + boolean continueGather = true; + + Collector result = new Collector(); + while (valuesIterator.hasNext() && continueGather) { + T nextIU = valuesIterator.next(); + continueGather = result.accept(nextIU); + } + return result; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/ObjectMatchQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/ObjectMatchQuery.java new file mode 100644 index 000000000..f48e50aac --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/ObjectMatchQuery.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.query; + +import org.eclipse.equinox.p2.query.MatchQuery; + +/** + * Special implementation for use without generic support + */ +public abstract class ObjectMatchQuery extends MatchQuery { + public boolean isMatch(Object candidate) { + return true; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/UpdateQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/UpdateQuery.java new file mode 100644 index 000000000..3ca68f9a0 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/metadata/query/UpdateQuery.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.metadata.query; + +import org.eclipse.equinox.p2.metadata.IUpdateDescriptor; + +import org.eclipse.equinox.p2.metadata.IInstallableUnitPatch; + +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; +import org.eclipse.equinox.p2.query.MatchQuery; + +/** + * A query that finds all IUs that are considered an "Update" of the + * specified IU. + */ +public class UpdateQuery extends MatchQuery { + private IInstallableUnit updateFrom; + + public UpdateQuery(IInstallableUnit updateFrom) { + this.updateFrom = updateFrom; + } + + public boolean isMatch(IInstallableUnit candidate) { + if (candidate instanceof IInstallableUnitPatch && !(updateFrom instanceof IInstallableUnitPatch)) { + IInstallableUnitPatch potentialPatch = (IInstallableUnitPatch) candidate; + IRequirement lifeCycle = potentialPatch.getLifeCycle(); + if (lifeCycle == null) + return false; + return updateFrom.satisfies(lifeCycle); + } + IUpdateDescriptor descriptor = candidate.getUpdateDescriptor(); + if (descriptor != null && descriptor.isUpdateOf(updateFrom)) { + if (!updateFrom.getId().equals(candidate.getId())) + return true; + return updateFrom.getVersion().compareTo(candidate.getVersion()) < 0; + } + return false; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/query/QueryHelpers.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/query/QueryHelpers.java new file mode 100644 index 000000000..794ceff2b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/p2/query/QueryHelpers.java @@ -0,0 +1,58 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.internal.p2.query; + + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import org.eclipse.equinox.p2.query.IQuery; + +/** + * Static helper methods for the Query API. + * + * @noextend This class is not intended to be subclassed by clients. + */ +public class QueryHelpers { + /** + * Gets the ID for a Query. + * + * @noreference This method is not intended to be referenced by clients. + */ + public static String getId(IQuery query) { + return query.getClass().getName(); + } + + /** + * Gets a particular property of a query. + * @param query The query to retrieve the property from + * @param property The property to retrieve + * + * @noreference This method is not intended to be referenced by clients. + */ + public static Object getProperty(IQuery query, String property) { + Class clazz = query.getClass(); + Object result = null; + try { + Method method = clazz.getMethod("get" + property, new Class[0]); //$NON-NLS-1$ + result = method.invoke(query, new Object[0]); + } catch (SecurityException e) { + return null; + } catch (NoSuchMethodException e) { + return null; + } catch (IllegalArgumentException e) { + return null; + } catch (IllegalAccessException e) { + return null; + } catch (InvocationTargetException e) { + return null; + } + return result; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/FormatException.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/FormatException.java deleted file mode 100644 index 3e9855f54..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/FormatException.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Cloudsmith Inc. and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Cloudsmith Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -/** - * Exception thrown by the {@link VersionFormatParser} - * - */ -public class FormatException extends Exception { - - private static final long serialVersionUID = -867104101610941043L; - - public FormatException(String message) { - super(message); - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IArtifactKey.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IArtifactKey.java deleted file mode 100644 index ee07d8176..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IArtifactKey.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - - - -/** - * Provide standardized artifact information to uniquely identify the - * corresponding bytes (perhaps not stored as a file). - *

    - * Artifact keys represent both a unique opaque identifier as well as structured - * and standardized pieces of information. - * - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface IArtifactKey { - - /** - * Returns the classifier for this artifact key. The returned value can be empty. - * @return the classifier segment of the key. - */ - public String getClassifier(); - - /** - * Returns the id for this artifact key. The returned value can be empty. - * @return the classifier segment of the key. - */ - public String getId(); - - /** - * Returns the version for this artifact key. - * @return the version segment of the key. - */ - public Version getVersion(); - - /** - * Returns the canonical string form of this artifact key. - * @return the canonical string representing this key - */ - public String toExternalForm(); -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ICopyright.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ICopyright.java deleted file mode 100644 index 990b87432..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ICopyright.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -import java.net.URI; - -/** - * The ICopyright interface represents a software copyright. A copyright has - * required body text which may be the full text or a summary. An optional location field can be specified - * which links to full text. - * - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface ICopyright { - - /** - * Returns the location of a document containing the copyright notice. - * - * @return The location of the copyright notice, or null - */ - public URI getLocation(); - - /** - * Returns the license body. - * - * @return the license body, never null - */ - public String getBody(); - -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IInstallableUnit.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IInstallableUnit.java deleted file mode 100644 index b06c7337a..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IInstallableUnit.java +++ /dev/null @@ -1,278 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. All rights reserved. This - * program and the accompanying materials are made available under the terms of - * the Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Genuitec, LLC - added license support - * EclipseSource - ongoing development - ******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -import java.util.Map; - -/** - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface IInstallableUnit extends IVersionedId, Comparable { - - /** - * A capability namespace representing a particular profile flavor. - */ - public static final String NAMESPACE_FLAVOR = "org.eclipse.equinox.p2.flavor"; //$NON-NLS-1$ - - /** - * A capability namespace representing a particular InstallableUnit by id. - * Each InstallableUnit automatically provides a capability in this namespace representing - * itself, and other InstallableUnits can require such a capability to state that they - * require a particular InstallableUnit to be present. - * - * @see IInstallableUnit#getId() - */ - public static final String NAMESPACE_IU_ID = "org.eclipse.equinox.p2.iu"; //$NON-NLS-1$ - - /** - * A property key (value "org.eclipse.equinox.p2.partial.iu") for a - * boolean property indicating the IU is generated from incomplete information and - * should be replaced by the complete IU if available. - * - * @see #getProperty(String) - */ - public static final String PROP_PARTIAL_IU = "org.eclipse.equinox.p2.partial.iu"; //$NON-NLS-1$ - - /** - * A property key (value "org.eclipse.equinox.p2.type.profile") for a - * boolean property indicating that an installable unit is a profile. - * - * @see #getProperty(String) - */ - public static final String PROP_TYPE_PROFILE = "org.eclipse.equinox.p2.type.profile"; //$NON-NLS-1$ - - /** - * A property key (value "org.eclipse.equinox.p2.type.category") for a - * boolean property indicating that an installable unit is a category. - * - * @see #getProperty(String) - */ - public static final String PROP_TYPE_CATEGORY = "org.eclipse.equinox.p2.type.category"; //$NON-NLS-1$ - - /** - * A property key (value "org.eclipse.equinox.p2.type.fragment") for a - * boolean property indicating that an installable unit is a fragment. - * - * @see #getProperty(String) - */ - public static final String PROP_TYPE_FRAGMENT = "org.eclipse.equinox.p2.type.fragment"; //$NON-NLS-1$ - - /** - * A property key (value "org.eclipse.equinox.p2.type.group") for a - * boolean property indicating that an installable unit is a group. - * - * @see #getProperty(String) - */ - public static final String PROP_TYPE_GROUP = "org.eclipse.equinox.p2.type.group"; //$NON-NLS-1$ - - /** - * A property key (value "org.eclipse.equinox.p2.type.patch") for a - * boolean property indicating that an installable unit is a group. - * - * @see #getProperty(String) - */ - public static final String PROP_TYPE_PATCH = "org.eclipse.equinox.p2.type.patch"; //$NON-NLS-1$ - - /** - * A property key (value "org.eclipse.equinox.p2.type.lock") for an - * integer property indicating how an installable unit is locked in its profile. - * The integer is a bit-mask indicating the different locks defined on the installable - * unit. The property should be obtained from a profile using - * IProfile#getInstallableUnitProperty(IInstallableUnit, String). - * - * @see #LOCK_UNINSTALL - * @see #LOCK_UPDATE - * @see #LOCK_NONE - */ - public static final String PROP_PROFILE_LOCKED_IU = "org.eclipse.equinox.p2.type.lock"; //$NON-NLS-1$ - - //TODO Move to UI - public static final String PROP_PROFILE_ROOT_IU = "org.eclipse.equinox.p2.type.root"; //$NON-NLS-1$ - - /** - * A property key (value "org.eclipse.equinox.p2.contact") for a - * String property containing a contact address where problems can be reported, - * such as an email address. - * - * @see #getProperty(String) - */ - public static final String PROP_CONTACT = "org.eclipse.equinox.p2.contact"; //$NON-NLS-1$ - /** - * A property key (value "org.eclipse.equinox.p2.description") for a - * String property containing a human-readable description of the installable unit. - * - * @see #getProperty(String) - */ - public static final String PROP_DESCRIPTION = "org.eclipse.equinox.p2.description"; //$NON-NLS-1$ - - /** - * A property key (value "org.eclipse.equinox.p2.description.url") for a - * String property containing a URL to the description of the installable unit. - * - * @see #getProperty(String) - */ - public static final String PROP_DESCRIPTION_URL = "org.eclipse.equinox.p2.description.url"; //$NON-NLS-1$ - /** - * A property key (value "org.eclipse.equinox.p2.doc.url") for a - * String property containing a URL for documentation about the installable unit. - * - * @see #getProperty(String) - */ - public static final String PROP_DOC_URL = "org.eclipse.equinox.p2.doc.url"; //$NON-NLS-1$ - - /** - * A property key (value "org.eclipse.equinox.p2.bundle.localization") for a String - * property containing the bundle localization property file name - */ - public static final String PROP_BUNDLE_LOCALIZATION = "org.eclipse.equinox.p2.bundle.localization"; //$NON-NLS-1$ - - /** - * A property key (value "org.eclipse.equinox.p2.name") for a - * String property containing a human-readable name for the installable unit. - * - * @see #getProperty(String) - */ - public static final String PROP_NAME = "org.eclipse.equinox.p2.name"; //$NON-NLS-1$ - /** - * A property key (value "org.eclipse.equinox.p2.provider") for a - * String property containing information about the vendor or provider of the - * installable unit. - * - * @see #getProperty(String) - */ - public static final String PROP_PROVIDER = "org.eclipse.equinox.p2.provider"; //$NON-NLS-1$ - - /** - * Constant used to indicate that an installable unit is not locked in anyway. - * @see #PROP_PROFILE_LOCKED_IU - */ - public static int LOCK_NONE = 0; - /** - * Constant used to indicate that an installable unit is locked so that it may - * not be uninstalled. - * @see #PROP_PROFILE_LOCKED_IU - */ - public static int LOCK_UNINSTALL = 1 << 0; - /** - * Constant used to indicate that an installable unit is locked so that it may - * not be updated. updates. - * @see #PROP_PROFILE_LOCKED_IU - */ - public static int LOCK_UPDATE = 1 << 1; - - public IArtifactKey[] getArtifacts(); - - /** - * Returns the filter on this installable unit. The filter is matched against - * the selection context of the profile the unit is installed into. An IU will not - * be installed if it has a filter condition that is not satisfied by the context. - * - * See Profile#getSelectionContext. - */ - public String getFilter(); - - /** - * Returns the fragments that have been bound to this installable unit, or - * null if this unit is not resolved. - * - * @see #isResolved() - * @return The fragments bound to this installable unit, or null - */ - public IInstallableUnitFragment[] getFragments(); - - /** - * Get an unmodifiable copy of the properties - * associated with the installable unit. - * - * @return an unmodifiable copy of the IU properties. - */ - public Map getProperties(); - - public String getProperty(String key); - - public IProvidedCapability[] getProvidedCapabilities(); - - public IRequiredCapability[] getRequiredCapabilities(); - - public IRequiredCapability[] getMetaRequiredCapabilities(); - - public ITouchpointData[] getTouchpointData(); - - public ITouchpointType getTouchpointType(); - - public boolean isFragment(); - - /** - * Returns whether this installable unit has been resolved. A resolved - * installable unit represents the union of an installable unit and some - * fragments. - * - * @see #getFragments() - * @see #unresolved() - * @return true if this installable unit is resolved, and - * false otherwise. - */ - public boolean isResolved(); - - public boolean isSingleton(); - - /** - * Returns whether this unit has a provided capability that satisfies the given - * required capability. - * @return true if this unit satisfies the given required - * capability, and false otherwise. - */ - public boolean satisfies(IRequiredCapability candidate); - - /** - * Returns the unresolved equivalent of this installable unit. If this unit is - * already unresolved, this method returns the receiver. Otherwise, this - * method returns an installable unit with the same id and version, but without - * any fragments attached. - * - * @see #getFragments() - * @see #isResolved() - * @return The unresolved equivalent of this unit - */ - public IInstallableUnit unresolved(); - - /** - * Returns information about what this installable unit is an update of. - * @return The lineage information about the installable unit - */ - public IUpdateDescriptor getUpdateDescriptor(); - - /** - * Returns the license that applies to this installable unit. - * @return the license that applies to this installable unit or null - */ - public ILicense getLicense(); - - /** - * Returns the copyright that applies to this installable unit. - * @return the copyright that applies to this installable unit or null - */ - public ICopyright getCopyright(); - - /** - * Returns whether this InstallableUnit is equal to the given object. - * - * This method returns true if: - *

      - *
    • Both this object and the given object are of type IInstallableUnit - *
    • The result of getId() on both objects are equal - *
    • The result of getVersion() on both objects are equal - *
    - */ - public boolean equals(Object obj); -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IInstallableUnitFragment.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IInstallableUnitFragment.java deleted file mode 100644 index a803f63a0..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IInstallableUnitFragment.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -/** - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface IInstallableUnitFragment extends IInstallableUnit { - public IRequiredCapability[] getHost(); -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IInstallableUnitPatch.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IInstallableUnitPatch.java deleted file mode 100644 index f67c7127d..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IInstallableUnitPatch.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -/** - * An installable unit patch is an installable unit that alters the required capabilities of another - * installable unit. - * - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface IInstallableUnitPatch extends IInstallableUnit { - /** - * The applicability scope of a patch describes the installable units that this - * patch should be applied to. Specifically, this patch will be applied to all installable - * units that satisfy all of the required capabilities in one or more of the given - * required capability arrays. - *

    - * The returned two-dimensional array can be considered - * as a boolean expression, where items in the inner array are connected by - * AND operators, and each of the arrays are separated by OR operators. For example - * a scope of [[r1, r2, r3], [r4, r5]] will match any unit whose provided capabilities - * satisfy the expression ((r1 ^ r2 ^ r3) | (r4 ^ r5)). - */ - IRequiredCapability[][] getApplicabilityScope(); - - /** - * Returns the requirement changes imposed by the patch. - * @return The patch requirement changes. - */ - IRequirementChange[] getRequirementsChange(); - - /** - * Returns the required capability that defines the lifecycle of this patch. The - * patch will be installed into a profile if and only if the lifecycle capability - * is satisfied by some IU in the profile. If a future provisioning operation causes - * the requirement to no longer be satisfied, the patch will be uninstalled. - */ - IRequiredCapability getLifeCycle(); -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ILicense.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ILicense.java deleted file mode 100644 index 99916dec8..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ILicense.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation - * IBM - ongoing development -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -import java.math.BigInteger; -import java.net.URI; - -/** - * The ILicense interface represents a software license. A license has required body text - * which may be the full text or an annotation. An optional URL field can be specified - * which links to full text. Licenses can be easily compared using their digests. - * - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface ILicense { - - /** - * Returns the location of a document containing the full license. - * - * @return the location of the license document, or null - */ - public URI getLocation(); - - /** - * Returns the license body. - * @return the license body, never null - */ - public String getBody(); - - /** - * Returns the message digest of the license body. The digest is calculated on a normalized - * version of the license where all whitespace has been reduced to one space. - * - * Any SPI must maintain the same semantics as: - * {@link org.eclipse.equinox.internal.provisional.p2.metadata.ILicense#getDigest()} - * @return the message digest as a BigInteger, never null - */ - public BigInteger getDigest(); - - /** - * Returns whether this license is equal to the given object. - * - * This method returns true if: - *

      - *
    • Both this object and the given object are of type ILicense - *
    • The result of getDigest() on both objects are equal - *
    - */ - public boolean equals(Object obj); - -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IProvidedCapability.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IProvidedCapability.java deleted file mode 100644 index 971d2f6f8..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IProvidedCapability.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation - * IBM - ongoing development -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - - - -/** - * Describes a capability as exposed or required by an installable unit - * - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface IProvidedCapability { - - public String getName(); - - public String getNamespace(); - - public Version getVersion(); - - /** - * Returns whether this provided capability satisfies the given required capability. - * @return true if this capability satisfies the given required - * capability, and false otherwise. - * - * This method must maintain the following semantics: - *
      - *
    • If the provided capability and the candidate have different names, - * return false - *
    • If the provided capability and the candidate have different namespaces. - * return false - *
    • If the candidate's version range includes the provided capability's - * version, return true - *
    • otherwise, return false - *
    - * - */ - public boolean satisfies(IRequiredCapability candidate); - - /** - * Returns whether this provided capability is equal to the given object. - * - * This method returns true if: - *
      - *
    • Both this object and the given object are of type IProvidedCapability - *
    • The result of getName() on both objects are equal - *
    • The result of getNamespace() on both objects are equal - *
    • The result of getVersion() on both objects are equal - *
    - */ - public boolean equals(Object other); - -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IRequiredCapability.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IRequiredCapability.java deleted file mode 100644 index 9e0b652e6..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IRequiredCapability.java +++ /dev/null @@ -1,90 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -/** - * A required capability represents some external constraint on an {@link IInstallableUnit}. - * Each capability represents something an {@link IInstallableUnit} needs that - * it expects to be provided by another {@link IInstallableUnit}. Capabilities are - * entirely generic, and are intended to be capable of representing anything that - * an {@link IInstallableUnit} may need either at install time, or at runtime. - *

    - * Capabilities are segmented into namespaces. Anyone can introduce new - * capability namespaces. Some well-known namespaces are introduced directly - * by the provisioning framework. - * - * @see IInstallableUnit#NAMESPACE_IU_ID - * - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface IRequiredCapability { - - public String getFilter(); - - public String getName(); - - public String getNamespace(); - - /** - * Returns the range of versions that satisfy this required capability. Returns - * an empty version range ({@link VersionRange#emptyRange} if any version - * will satisfy the capability. - * @return the range of versions that satisfy this required capability. - */ - public VersionRange getRange(); - - /** - * Returns the properties to use for evaluating required capability filters - * downstream from this capability. For example, if the selector "doc" - * is provided, then a downstream InstallableUnit with a required capability - * filtered with "doc=true" will be included. - */ - public String[] getSelectors(); - - public boolean isMultiple(); - - public boolean isOptional(); - - /** - * TODO This object shouldn't be mutable since it makes equality unstable, and - * introduces lifecycle issues (how are the changes persisted, etc) - */ - public void setFilter(String filter); - - /** - * TODO This object shouldn't be mutable since it makes equality unstable, and - * introduces lifecycle issues (how are the changes persisted, etc) - */ - public void setSelectors(String[] selectors); - - public boolean isGreedy(); - - /** - * Returns whether this required capability is equal to the given object. - * - * This method returns true if: - *

      - *
    • Both this object and the given object are of type IRequiredCapability - *
    • The result of getFilter() on both objects are equal - *
    • The result of isMultiple() on both objects are equal - *
    • The result of getName() on both objects are equal - *
    • The result of geNamespace() on both objects are equal - *
    • The result of isOptional() on both objects are equal - *
    • The result of getRange() on both objects are equal - *
    - */ - public boolean equals(Object other); - - public boolean isNegation(); - - public boolean satisfiedBy(IProvidedCapability cap); - -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IRequirementChange.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IRequirementChange.java deleted file mode 100644 index 59578f7da..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IRequirementChange.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -/** - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface IRequirementChange { - - public IRequiredCapability applyOn(); - - public IRequiredCapability newValue(); - - public boolean matches(IRequiredCapability toMatch); - - /** - * Returns whether this requirement change is equal to the given object. - * - * This method returns true if: - *
      - *
    • Both this object and the given object are of type IRequiredCapability - *
    • The result of applyOn() on both objects are equal - *
    • The result of newValue() on both objects are equal - *
    - */ - public boolean equals(Object other); -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ITouchpointData.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ITouchpointData.java deleted file mode 100644 index c1ea83b1a..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ITouchpointData.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -import java.util.Map; - -/** - * ITouchpoint data instances contain the additional information needed by a touchpoint - * to execute each engine phase it participates in. This includes the sequence of - * instruction statements to be executed during each phase, and any additional - * supporting data needed to perform the phase. - * - * @see MetadataFactory#createTouchpointData(Map) - * - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface ITouchpointData { - - /** - * Returns the touchpoint instruction corresponding to the given key. - */ - public ITouchpointInstruction getInstruction(String instructionKey); - - /** - * Returns an unmodifiable map of the touchpoint instructions. The map - * keys are strings, and the values are instances of {@link ITouchpointInstruction}. - * - * @return the touchpoint instructions - */ - public Map getInstructions(); - - /** - * Returns whether this TouchpointData is equal to the given object. - * - * This method returns true if: - *
      - *
    • Both this object and the given object are of type ITouchpointData - *
    • The result of getInstructions() on both objects are equal - *
    - */ - public boolean equals(Object obj); -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ITouchpointInstruction.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ITouchpointInstruction.java deleted file mode 100644 index e2322f5e7..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ITouchpointInstruction.java +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -/** - * A touchpoint instruction contains either a sequence of instruction statements - * to be executed during a particular engine phase, or some simple string value - * that is needed by a touchpoint to execute its phases. - *

    - * The format of a touchpoint instruction statement sequence is as follows: - * - * statement-sequence : - * | statement ';' - * | statement-sequence statement - * ; - * - *Where a statement is of the format: - * - * statement : - * | actionName '(' parameters ')' - * ; - * - * parameters : - * | // empty - * | parameter - * | parameters ',' parameter - * ; - * - * parameter : - * | paramName ':' paramValue - * ; - * - * actionName, paramName, paramValue : - * | String - * ; - * - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface ITouchpointInstruction { - - /** - * Returns the body of this touchpoint instruction. The body is either a sequence - * of instruction statements, or a simple string value. - * - * @return The body of this touchpoint instruction - */ - public String getBody(); - - //TODO What is this? Please doc - public String getImportAttribute(); - - /** - * Returns whether this TouchpointInstruction is equal to the given object. - * - * This method returns true if: - *

      - *
    • Both this object and the given object are of type ITouchpointInstruction - *
    • The result of getBody() on both objects are equal - *
    • The result of getImportAttribute() on both objects are equal - *
    - */ - public boolean equals(Object obj); - -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ITouchpointType.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ITouchpointType.java deleted file mode 100644 index f003b91d9..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/ITouchpointType.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - - - -/** - * Identifies a particular touchpoint. A touchpoint is identified by an id - * and a version. - * - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface ITouchpointType { - - /** - * A touchpoint type indicating an undefined touchpoint type. Identity (==) - * must be used to test for the NONE type. - */ - public static final ITouchpointType NONE = new ITouchpointType() { - - public String getId() { - return "null"; //$NON-NLS-1$ - } - - public Version getVersion() { - return Version.emptyVersion; - } - }; - - public String getId(); - - public Version getVersion(); - - /** - * Returns whether this TouchpointInstruction is equal to the given object. - * - * This method returns true if: - *
      - *
    • Both this object and the given object are of type ITouchpointType - *
    • The result of getId() on both objects are equal - *
    • The result of getVersion() on both objects are equal - *
    - */ - public boolean equals(Object obj); - -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IUpdateDescriptor.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IUpdateDescriptor.java deleted file mode 100644 index 268ff247c..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IUpdateDescriptor.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - - - -/** - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface IUpdateDescriptor { - public final int NORMAL = 0; - public final int HIGH = 1; - - /** - * The identifier of an installable unit that the installable unit containing this object is an update for. - * @return An installable unit id - */ - public String getId(); - - /** - * The range of the installable unit that the installable unit containing this object is an update for. - * @return A version range - */ - public VersionRange getRange(); - - /** - * The description of the update. This allows to explain what the update is about. - * @return A description - */ - public String getDescription(); - - /** - * The importance of the update descriptor represented as a int. - * @return The severity. - */ - public int getSeverity(); - - /** - * Helper method indicating whether or not an installable unit is an update for the installable unit passed - * @param iu the installable unit checked - * @return A boolean indicating whether or not an installable unit is an update. - */ - public boolean isUpdateOf(IInstallableUnit iu); -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IVersionedId.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IVersionedId.java deleted file mode 100644 index 77184d3c7..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/IVersionedId.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Cloudsmith Inc. and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Cloudsmith Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -/** - * An interface representing a (id,version) pair. - */ -public interface IVersionedId { - /** - * Returns the id portion of this versioned id. - * - * @return The id portion of this versioned id. - */ - String getId(); - - /** - * Returns the version portion of this versioned id. - * - * @return the version portion of this versioned id. - */ - Version getVersion(); -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/MetadataFactory.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/MetadataFactory.java index b1021d5b4..4e023f487 100644 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/MetadataFactory.java +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/MetadataFactory.java @@ -16,7 +16,10 @@ import java.net.URI; import java.util.*; import java.util.Map.Entry; import org.eclipse.core.runtime.Assert; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; import org.eclipse.equinox.internal.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.*; +import org.osgi.framework.Filter; /** * A factory class for instantiating various p2 metadata objects. @@ -29,34 +32,53 @@ public class MetadataFactory { * the resulting immutable unit. */ public static class InstallableUnitDescription { + public static final String PROP_TYPE_GROUP = "org.eclipse.equinox.p2.type.group"; //$NON-NLS-1$ + protected InstallableUnit unit; + /** + * A property key (value "org.eclipse.equinox.p2.type.patch") for a + * boolean property indicating that an installable unit is a group. + * + */ + public static final String PROP_TYPE_PATCH = "org.eclipse.equinox.p2.type.patch"; //$NON-NLS-1$ + + /** + * A property key (value "org.eclipse.equinox.p2.type.fragment") for a + * boolean property indicating that an installable unit is a fragment. + * + */ + public static final String PROP_TYPE_FRAGMENT = "org.eclipse.equinox.p2.type.fragment"; //$NON-NLS-1$ + + /** + * A property key (value "org.eclipse.equinox.p2.type.category") for a + * boolean property indicating that an installable unit is a category. + * + */ + public static final String PROP_TYPE_CATEGORY = "org.eclipse.equinox.p2.type.category"; //$NON-NLS-1$ + public InstallableUnitDescription() { super(); } - public void addProvidedCapabilities(Collection additional) { + public void addProvidedCapabilities(Collection additional) { if (additional == null || additional.size() == 0) return; - IProvidedCapability[] current = unit().getProvidedCapabilities(); - IProvidedCapability[] result = new IProvidedCapability[additional.size() + current.length]; - System.arraycopy(current, 0, result, 0, current.length); - int j = current.length; - for (Iterator i = additional.iterator(); i.hasNext();) - result[j++] = (IProvidedCapability) i.next(); - unit().setCapabilities(result); + Collection current = unit().getProvidedCapabilities(); + ArrayList all = new ArrayList(additional.size() + current.size()); + all.addAll(current); + all.addAll(additional); + unit().setCapabilities(all.toArray(new IProvidedCapability[all.size()])); } - public void addRequiredCapabilities(Collection additional) { + public void addRequiredCapabilities(Collection additional) { if (additional == null || additional.size() == 0) return; - IRequiredCapability[] current = unit().getRequiredCapabilities(); - IRequiredCapability[] result = new IRequiredCapability[additional.size() + current.length]; - System.arraycopy(current, 0, result, 0, current.length); - int j = current.length; - for (Iterator i = additional.iterator(); i.hasNext();) - result[j++] = (IRequiredCapability) i.next(); - unit().setRequiredCapabilities(result); + List current = unit().getRequiredCapabilities(); + ArrayList all = new ArrayList(additional.size() + current.size()); + all.addAll(current); + all.addAll(additional); + unit().setRequiredCapabilities(all.toArray(new IRequirement[all.size()])); } public void addTouchpointData(ITouchpointData data) { @@ -68,15 +90,15 @@ public class MetadataFactory { return unit().getId(); } - public IProvidedCapability[] getProvidedCapabilities() { + public Collection getProvidedCapabilities() { return unit().getProvidedCapabilities(); } - public IRequiredCapability[] getRequiredCapabilities() { + public List getRequiredCapabilities() { return unit().getRequiredCapabilities(); } - public IRequiredCapability[] getMetaRequiredCapabilities() { + public Collection getMetaRequiredCapabilities() { return unit().getMetaRequiredCapabilities(); } @@ -86,7 +108,7 @@ public class MetadataFactory { * * @return The current touchpoint data on this description */ - public ITouchpointData[] getTouchpointData() { + public List getTouchpointData() { return unit().getTouchpointData(); } @@ -107,6 +129,10 @@ public class MetadataFactory { unit().setCopyright(copyright); } + public void setFilter(Filter filter) { + unit().setFilter(filter); + } + public void setFilter(String filter) { unit().setFilter(filter); } @@ -115,19 +141,19 @@ public class MetadataFactory { unit().setId(id); } - public void setLicense(ILicense license) { - unit().setLicense(license); + public void setLicenses(ILicense[] licenses) { + unit().setLicenses(licenses); } public void setProperty(String key, String value) { unit().setProperty(key, value); } - public void setRequiredCapabilities(IRequiredCapability[] requirements) { + public void setRequiredCapabilities(IRequirement[] requirements) { unit().setRequiredCapabilities(requirements); } - public void setMetaRequiredCapabilities(IRequiredCapability[] metaRequirements) { + public void setMetaRequiredCapabilities(IRequirement[] metaRequirements) { unit().setMetaRequiredCapabilities(metaRequirements); } @@ -162,17 +188,13 @@ public class MetadataFactory { } } - /** - * Description of an installable unit patch. The description will automatically have - * the {@link IInstallableUnit#PROP_TYPE_FRAGMENT} set to true. - */ public static class InstallableUnitFragmentDescription extends InstallableUnitDescription { public InstallableUnitFragmentDescription() { super(); - setProperty(IInstallableUnit.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); + setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); } - public void setHost(IRequiredCapability[] hostRequirements) { + public void setHost(IRequirement[] hostRequirements) { ((InstallableUnitFragment) unit()).setHost(hostRequirements); } @@ -183,24 +205,20 @@ public class MetadataFactory { } } - /** - * Description of an installable unit patch. The description will automatically have - * the {@link IInstallableUnit#PROP_TYPE_PATCH} set to true. - */ public static class InstallableUnitPatchDescription extends InstallableUnitDescription { public InstallableUnitPatchDescription() { super(); - setProperty(IInstallableUnit.PROP_TYPE_PATCH, Boolean.TRUE.toString()); + setProperty(InstallableUnitDescription.PROP_TYPE_PATCH, Boolean.TRUE.toString()); } - public void setApplicabilityScope(IRequiredCapability[][] applyTo) { + public void setApplicabilityScope(IRequirement[][] applyTo) { if (applyTo == null) throw new IllegalArgumentException("A patch scope can not be null"); //$NON-NLS-1$ ((InstallableUnitPatch) unit()).setApplicabilityScope(applyTo); } - public void setLifeCycle(IRequiredCapability lifeCycle) { + public void setLifeCycle(IRequirement lifeCycle) { ((InstallableUnitPatch) unit()).setLifeCycle(lifeCycle); } @@ -211,7 +229,7 @@ public class MetadataFactory { InstallableUnit unit() { if (unit == null) { unit = new InstallableUnitPatch(); - ((InstallableUnitPatch) unit()).setApplicabilityScope(new IRequiredCapability[0][0]); + ((InstallableUnitPatch) unit()).setApplicabilityScope(new IRequirement[0][0]); } return unit; } @@ -220,7 +238,7 @@ public class MetadataFactory { /** * Singleton touchpoint data for a touchpoint with no instructions. */ - private static final ITouchpointData EMPTY_TOUCHPOINT_DATA = new TouchpointData(Collections.EMPTY_MAP); + private static final ITouchpointData EMPTY_TOUCHPOINT_DATA = new TouchpointData(CollectionUtils. emptyMap()); private static ITouchpointType[] typeCache = new ITouchpointType[5]; @@ -277,7 +295,7 @@ public class MetadataFactory { } /** - * Returns a {@link IRequiredCapability} with the given values. + * Returns a {@link IRequirement} with the given values. * * @param namespace The capability namespace * @param name The required capability name @@ -289,8 +307,12 @@ public class MetadataFactory { * and false otherwise. * @param multiple true if this capability can be satisfied by multiple provided capabilities, or it requires exactly one match */ - public static IRequiredCapability createRequiredCapability(String namespace, String name, VersionRange range, String filter, boolean optional, boolean multiple) { - return new RequiredCapability(namespace, name, range, filter, optional, multiple); + public static IRequiredCapability createRequiredCapability(String namespace, String name, VersionRange range, Filter filter, boolean optional, boolean multiple) { + return new RequiredCapability(namespace, name, range, filter, optional ? 0 : 1, multiple ? Integer.MAX_VALUE : 1, true); + } + + public static IRequirement createRequiredCapability(String namespace, String name, VersionRange range, Filter filter, int minCard, int maxCard, boolean greedy) { + return new RequiredCapability(namespace, name, range, filter, minCard, maxCard, greedy); } public static IRequiredCapability createRequiredCapability(String namespace, String name, VersionRange range, String filter, boolean optional, boolean multiple, boolean greedy) { @@ -303,8 +325,10 @@ public class MetadataFactory { * @param newValue The result of the requirement change - the requirement to replace the source requirement with * @return a requirement change */ - public static IRequirementChange createRequirementChange(IRequiredCapability applyOn, IRequiredCapability newValue) { - return new RequirementChange(applyOn, newValue); + public static IRequirementChange createRequirementChange(IRequirement applyOn, IRequirement newValue) { + if ((applyOn == null || applyOn instanceof IRequiredCapability) && (newValue == null || newValue instanceof IRequiredCapability)) + return new RequirementChange((IRequiredCapability) applyOn, (IRequiredCapability) newValue); + throw new IllegalArgumentException(); } /** @@ -327,7 +351,7 @@ public class MetadataFactory { * @throws IllegalArgumentException when the body is null */ public static ILicense createLicense(URI location, String body) { - return new License(location, body); + return new License(location, body, null); } /** @@ -354,24 +378,66 @@ public class MetadataFactory { * @param instructions The instructions for the touchpoint data. * @return The created touchpoint data */ - public static ITouchpointData createTouchpointData(Map instructions) { + public static ITouchpointData createTouchpointData(Map instructions) { Assert.isNotNull(instructions); //copy the map to protect against subsequent change by caller if (instructions.isEmpty()) return EMPTY_TOUCHPOINT_DATA; - Map result = new LinkedHashMap(instructions.size()); - for (Iterator iterator = instructions.entrySet().iterator(); iterator.hasNext();) { - Entry entry = (Entry) iterator.next(); + Map result = new LinkedHashMap(instructions.size()); + + for (Entry entry : instructions.entrySet()) { Object value = entry.getValue(); + ITouchpointInstruction instruction; if (value == null || value instanceof String) - value = createTouchpointInstruction((String) value, null); - - result.put(entry.getKey(), value); + instruction = createTouchpointInstruction((String) value, null); + else + instruction = (ITouchpointInstruction) value; + result.put(entry.getKey(), instruction); } return new TouchpointData(result); } + /** + * Merge the given touchpoint instructions with a pre-existing touchpoint data + * @param initial - the initial ITouchpointData + * @param incomingInstructions - Map of ITouchpointInstructions to merge into the initial touchpoint data + * @return the merged ITouchpointData + */ + public static ITouchpointData mergeTouchpointData(ITouchpointData initial, Map incomingInstructions) { + if (incomingInstructions == null || incomingInstructions.size() == 0) + return initial; + + Map resultInstructions = new HashMap(initial.getInstructions()); + for (String key : incomingInstructions.keySet()) { + ITouchpointInstruction instruction = incomingInstructions.get(key); + ITouchpointInstruction existingInstruction = resultInstructions.get(key); + + if (existingInstruction != null) { + String body = existingInstruction.getBody(); + if (body == null || body.length() == 0) + body = instruction.getBody(); + else if (instruction.getBody() != null) { + if (!body.endsWith(";")) //$NON-NLS-1$ + body += ';'; + body += instruction.getBody(); + } + + String importAttribute = existingInstruction.getImportAttribute(); + if (importAttribute == null || importAttribute.length() == 0) + importAttribute = instruction.getImportAttribute(); + else if (instruction.getImportAttribute() != null) { + if (!importAttribute.endsWith(",")) //$NON-NLS-1$ + importAttribute += ','; + importAttribute += instruction.getBody(); + } + instruction = createTouchpointInstruction(body, importAttribute); + } + resultInstructions.put(key, instruction); + } + return createTouchpointData(resultInstructions); + } + public static ITouchpointInstruction createTouchpointInstruction(String body, String importAttribute) { return new TouchpointInstruction(body, importAttribute); } diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/Version.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/Version.java deleted file mode 100644 index 9f47ece06..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/Version.java +++ /dev/null @@ -1,504 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Cloudsmith and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Cloudsmith Inc - initial API and implementation. - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.metadata; - -import org.eclipse.equinox.internal.p2.metadata.Messages; - -import org.eclipse.osgi.util.NLS; - -/** - *

    The Omni Version is composed of a vector of Comparable objects and a pad value. The pad - * might be null. The vector can contain integers, strings, {@link VersionVector} - * instances, or one of the special objects {@link VersionVector#MAX_VALUE MAX_VALUE}, - * {@link VersionVector#MAXS_VALUE MAXS_VALUE}, or {@link VersionVector#MIN_VALUE MIN_VALUE}.

    - * - *

    When two versions are compared, they are always considered padded to infinity by their - * pad value or by {@link VersionVector#MIN_VALUE MIN_VALUE} in case the pad value is - * null. The comparison is type sensitive so that:

    - * MAX_VALUE > Integer > VersionVector > MAXS_VALUE > String > MIN_VALUE
    - *
    - * - * The class is signature compatible with {@link org.osgi.framework.Version} but attempts - * to use it as such might render a {@link UnsupportedOperationException} in case the - * vector holds incompatible values. The method {@link #isOSGiCompatible()} can be used - * to test. - * - * @Immutable - * @noextend This class is not intended to be subclassed by clients. - */ -public class Version extends VersionVector { - private static final Integer cache[] = new Integer[100]; - - private static final char[] allowedOSGiChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".toCharArray(); //$NON-NLS-1$ - - public static final Integer ZERO_INT = new Integer(0); - - public static final Integer MAX_INT_OBJ = new Integer(Integer.MAX_VALUE); - - static { - cache[0] = ZERO_INT; - for (int i = 1; i < cache.length; i++) - cache[i] = new Integer(i); - } - - static Integer valueOf(int i) { - try { - return cache[i]; - } catch (ArrayIndexOutOfBoundsException e) { - return (i == Integer.MAX_VALUE) ? MAX_INT_OBJ : new Integer(i); - } - } - - /** - * The empty OSGi version "0.0.0". Equivalent to calling - * new Version(0,0,0). - */ - public static final Version emptyVersion = new Version(0, 0, 0); - - /** - * The version that is semantically greater then all other versions. - */ - public static final Version MAX_VERSION = new Version("raw:MpM"); //$NON-NLS-1$ - - /** - * The version that is semantically less then all other versions. - */ - public static final Version MIN_VERSION = new Version("raw:-M"); //$NON-NLS-1$ - - private static final long serialVersionUID = 8202715438560849928L; - - /** - * Creates an OSGi version identifier from the specified numerical components. - * - *

    - * The qualifier is set to the empty string. - * - * @param major Major component of the version identifier. - * @param minor Minor component of the version identifier. - * @param micro Micro component of the version identifier. - * @throws IllegalArgumentException If the numerical components are - * negative. - */ - public static Version createOSGi(int major, int minor, int micro) { - return createOSGi(major, minor, micro, null); - } - - /** - * Creates an OSGi version identifier from the specified components. - * - * @param major Major component of the version identifier. - * @param minor Minor component of the version identifier. - * @param micro Micro component of the version identifier. - * @param qualifier Qualifier component of the version identifier. If - * null is specified, then the qualifier will be set to - * the empty string. - * @throws IllegalArgumentException If the numerical components are negative - * or the qualifier string is invalid. - */ - public static Version createOSGi(int major, int minor, int micro, String qualifier) { - // TODO: Eliminate duplicates - return new Version(major, minor, micro, qualifier); - } - - /** - * Create an omni version from an OSGi version. - * @param version The OSGi version. Can be null. - * @return The created omni version - */ - public static Version fromOSGiVersion(org.osgi.framework.Version version) { - if (version == null) - return null; - if (version.equals(org.osgi.framework.Version.emptyVersion)) - return emptyVersion; - return new Version(version.getMajor(), version.getMinor(), version.getMicro(), version.getQualifier()); - } - - /** - * Parses a version identifier from the specified string. - * - * @param version String representation of the version identifier. Leading - * and trailing whitespace will be ignored. - * @return A Version object representing the version identifier - * or null if version is null or - * an empty string. - * @throws IllegalArgumentException If version is improperly - * formatted. - */ - public static Version create(String version) { - // TODO: Eliminate duplicates - if (version != null) { - Version v = new Version(); - if (VersionParser.parseInto(version, 0, version.length(), v)) - return v; - } - return null; - } - - /** - * Parses a version identifier from the specified string. This method is for backward - * compatibility with OSGi and will return the OSGi {@link #emptyVersion} when - * the provided string is empty or null. - * - * @param version String representation of the version identifier. Leading - * and trailing whitespace will be ignored. - * @return A Version object representing the version - * identifier. If version is null or - * the empty string then the OSGi emptyVersion will be - * returned. - * @throws IllegalArgumentException If version is improperly - * formatted. - * @see #create(String) - */ - public static Version parseVersion(String version) { - if (version == null || version.length() == 0 || "0.0.0".equals(version)) //$NON-NLS-1$ - return emptyVersion; - Version v = create(version); - return v == null ? emptyVersion : v; - } - - /** - * Convert version into its OSGi equivalent if possible. - * - * @param version The version to convert. Can be null - * @return The converted version or null if the argument was null - * @throws UnsupportedOperationException if the version could not be converted into an OSGi version - */ - public static org.osgi.framework.Version toOSGiVersion(Version version) { - if (version == null) - return null; - if (version.equals(emptyVersion)) - return org.osgi.framework.Version.emptyVersion; - return new org.osgi.framework.Version(version.getMajor(), version.getMinor(), version.getMicro(), version.getQualifier()); - } - - /** - * For exception messages only - * @param i the index of the entry - * @return the name of the entry - */ - private static String getOSGiEntryName(int i) { - String name = null; - switch (i) { - case 0 : - name = "major"; //$NON-NLS-1$ - break; - case 1 : - name = "minor"; //$NON-NLS-1$ - break; - case 2 : - name = "micro"; //$NON-NLS-1$ - break; - case 3 : - name = "qualifier"; //$NON-NLS-1$ - } - return name; - } - - /** - * The optional format - */ - private VersionFormat format; - - /** - * The optional original string - */ - private String original; - - /** - * Creates an OSGi version identifier from the specified numerical components. - * - *

    - * The qualifier is set to the empty string. - * - * @param major Major component of the version identifier. - * @param minor Minor component of the version identifier. - * @param micro Micro component of the version identifier. - * @throws IllegalArgumentException If the numerical components are - * negative. - * @deprecated Use {@link #createOSGi(int, int, int)}. This constructor will not remain public - */ - public Version(int major, int minor, int micro) { - this(major, minor, micro, null); - } - - /** - * Creates an OSGi version identifier from the specified components. - * - * @param major Major component of the version identifier. - * @param minor Minor component of the version identifier. - * @param micro Micro component of the version identifier. - * @param qualifier Qualifier component of the version identifier. If - * null is specified, then the qualifier will be set to - * the empty string. - * @throws IllegalArgumentException If the numerical components are negative - * or the qualifier string is invalid. - * @deprecated Use {@link #createOSGi(int, int, int, String)}. This constructor will not remain public - */ - public Version(int major, int minor, int micro, String qualifier) { - if (qualifier != null && qualifier.length() == 0) - qualifier = null; - Comparable[] vector = new Comparable[qualifier == null ? 3 : 4]; - vector[0] = valueOf(major); - vector[1] = valueOf(minor); - vector[2] = valueOf(micro); - if (qualifier != null) - vector[3] = qualifier; - init(vector, null, VersionFormat.OSGI_FORMAT, null); - validateOSGI(true); - } - - /** - * Created a version identifier from the specified string. - * - * @param version String representation of the version identifier. - * @throws IllegalArgumentException If version is improperly - * formatted. - * @deprecated Use {@link #parseVersion(String)}. This constructor will not remain public - */ - public Version(String version) { - if (!VersionParser.parseInto(version, 0, version.length(), this)) { - // Version is OSGi empty - init(new Comparable[] {ZERO_INT, ZERO_INT, ZERO_INT}, null, VersionFormat.OSGI_FORMAT, null); - } - } - - Version() { - // Empty constructor - } - - Version(Comparable[] array, Comparable padValue, VersionFormat format, String original) { - init(array, padValue, format, original); - } - - /** - * Returns the optional format. - */ - public VersionFormat getFormat() { - return format; - } - - /** - * Returns the OSGi major component of this version identifier. - * - * @return The major component. - * @throws UnsupportedOperationException if the first element in the - * vector is not a number. - * @see #isOSGiCompatible() - */ - public int getMajor() { - return getIntElement(0); - } - - /** - * Returns the OSGi micro component of this version identifier. - * - * @return The micro component. - * @throws UnsupportedOperationException if the third element in the - * vector is not a number. - * @see #isOSGiCompatible() - */ - public int getMicro() { - return getIntElement(2); - } - - /** - * Returns the OSGi minor component of this version identifier. - * - * @return The minor component. - * @throws UnsupportedOperationException if the second element in the - * vector is not a number. - * @see #isOSGiCompatible() - */ - public int getMinor() { - return getIntElement(1); - } - - /** - * Returns the original part of the string for this version - * or null if no such part was provided when the version was - * created. An OSGi type version will always return the OSGi string representation. - * - * @return The original part of the version string or - * null if that part was missing. - */ - public String getOriginal() { - return original; - } - - /** - * Returns the OSGi qualifier component of this version identifier. - * - * @return The qualifier component or null if not set. - * @throws UnsupportedOperationException if the fourth element in the - * vector is set to something other then a string. - * @see #isOSGiCompatible() - */ - public String getQualifier() { - Comparable[] vector = getVector(); - if (vector.length < 4) - return null; - if (!(vector[3] instanceof String)) - throw new UnsupportedOperationException(); - return (String) vector[3]; - } - - /** - * Checks if this version is in compliance with the OSGi version spec. - * @return A flag indicating whether the version is OSGi compatible or not. - */ - public boolean isOSGiCompatible() { - return format == VersionFormat.OSGI_FORMAT || validateOSGI(false); - } - - /** - * Appends the original for this version onto the sb StringBuffer - * if present. - * @param sb The buffer that will receive the raw string format - * @param rangeSafe Set to true if range delimiters should be escaped - */ - public void originalToString(StringBuffer sb, boolean rangeSafe) { - if (original != null) { - if (rangeSafe) { - // Escape all range delimiters while appending - String s = original; - int end = s.length(); - for (int idx = 0; idx < end; ++idx) { - char c = s.charAt(idx); - if (c == '\\' || c == '[' || c == '(' || c == ']' || c == ')' || c == ',' || c <= ' ') - sb.append('\\'); - sb.append(c); - } - } else - sb.append(original); - } - } - - /** - * Appends the raw format for this version onto the sb StringBuffer. - * @param sb The buffer that will receive the raw string format - * @param rangeSafe Set to true if range delimiters should be escaped - */ - public void rawToString(StringBuffer sb, boolean rangeSafe) { - super.toString(sb, rangeSafe); - } - - /** - * Appends the string representation of this version onto the - * sb StringBuffer. - * @param sb The buffer that will receive the version string - */ - public void toString(StringBuffer sb) { - if (format == VersionFormat.OSGI_FORMAT) { - Comparable[] vector = getVector(); - sb.append(vector[0]); - sb.append('.'); - sb.append(vector[1]); - sb.append('.'); - sb.append(vector[2]); - if (vector.length > 3) { - sb.append('.'); - sb.append(vector[3]); - } - return; - } - sb.append(VersionParser.RAW_PREFIX); - super.toString(sb, false); - if (format != null || original != null) { - sb.append('/'); - if (format != null) - format.toString(sb); - if (original != null) { - sb.append(':'); - originalToString(sb, false); - } - } - } - - void init(Comparable[] vec, Comparable pad, VersionFormat fmt, String orig) { - init(vec, pad); - format = fmt; - //don't need to retain original for OSGi version - if (fmt != VersionFormat.OSGI_FORMAT) - original = orig; - } - - private int getIntElement(int i) { - Comparable[] vector = getVector(); - if (!(vector.length > i && vector[i] instanceof Integer)) - throw new UnsupportedOperationException(); - return ((Integer) vector[i]).intValue(); - } - - // Preserve singletons during deserialization - private Object readResolve() { - Version v = this; - if (equals(MAX_VERSION)) - v = MAX_VERSION; - else if (equals(MIN_VERSION)) - v = MIN_VERSION; - else if (equals(emptyVersion)) - v = emptyVersion; - else if (equals(VersionRange.OSGi_versionMax)) - v = VersionRange.OSGi_versionMax; - else if (equals(VersionRange.OSGi_versionMin)) - v = VersionRange.OSGi_versionMin; - return v; - } - - boolean validateOSGI(boolean throwDetailed) { - Comparable[] vector = getVector(); - if (vector.length < 3 || vector.length > 4) { - if (throwDetailed) - throw new IllegalArgumentException(NLS.bind(Messages.illegal_number_of_entries_0_in_osgi_1, valueOf(vector.length), this)); - return false; - } - - if (getPad() != null) { - if (throwDetailed) - throw new IllegalArgumentException(NLS.bind(Messages.pad_not_allowed_in_osgi_0, this)); - return false; - } - - for (int i = 0; i < 3; ++i) { - Object e = vector[i]; - if (!(e instanceof Integer && ((Integer) e).intValue() >= 0)) { - if (throwDetailed) - throw new IllegalArgumentException(NLS.bind(Messages._0_is_not_a_positive_integer_in_osgi_1, getOSGiEntryName(i), this)); - return false; - } - } - if (vector.length == 4) { - Object e = vector[3]; - if (!(e instanceof String)) { - if (throwDetailed) - throw new IllegalArgumentException(NLS.bind(Messages._0_is_not_a_string_in_osgi_1, getOSGiEntryName(3), this)); - return false; - } - - String s = (String) e; - int idx = s.length(); - char[] allowed = allowedOSGiChars; - int ctop = allowed.length; - outer: while (--idx >= 0) { - char c = s.charAt(idx); - int cdx = ctop; - while (--cdx >= 0) - if (c == allowed[cdx]) - continue outer; - if (throwDetailed) - throw new IllegalArgumentException(NLS.bind(Messages._0_is_not_a_valid_qualifier_in_osgi_1, getOSGiEntryName(3), this)); - return false; - } - } - return true; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionFormat.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionFormat.java deleted file mode 100644 index 5de45b418..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionFormat.java +++ /dev/null @@ -1,1247 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Cloudsmith Inc. and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Cloudsmith Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -import org.eclipse.equinox.internal.p2.metadata.Messages; - -import java.io.Serializable; -import java.util.*; -import org.eclipse.osgi.util.NLS; - -/** - *

    The VersionFormat represents the Omni Version Format in compiled form. It - * is also a parser for versions of that format.

    - *

    An instance of VersionFormat is immutable and thus thread safe. The parser - * does not maintain any state.

    - * - * @Immutable - * @noextend This class is not intended to be subclassed by clients. - */ -public class VersionFormat implements Serializable { - private static final long serialVersionUID = 6888925893926932754L; - - /** - * Represents one fragment of a format (i.e. auto, number, string, delimiter, etc.) - */ - static abstract class Fragment implements Serializable { - private static final long serialVersionUID = 4109185333058622681L; - - private final Qualifier qualifier; - - Fragment(Qualifier qualifier) { - this.qualifier = qualifier; - } - - public final boolean equals(Object f) { - return f == this || getClass().equals(f.getClass()) && qualifier.equals(((Fragment) f).qualifier); - } - - public final int hashCode() { - return 11 * qualifier.hashCode(); - } - - public boolean isGroup() { - return false; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - toString(sb); - return sb.toString(); - } - - Comparable getDefaultValue() { - return null; - } - - Fragment getFirstLeaf() { - return this; - } - - Comparable getPadValue() { - return null; - } - - Qualifier getQualifier() { - return qualifier; - } - - boolean parse(List segments, String version, int maxPos, TreeInfo info) { - return qualifier.parse(new Fragment[] {this}, 0, segments, version, maxPos, info); - } - - abstract boolean parseOne(List segments, String version, int maxPos, TreeInfo info); - - void setDefaults(List segments) { - // No-op at this level - } - - void toString(StringBuffer sb) { - if (!(qualifier == VersionFormatParser.EXACT_ONE_QUALIFIER || (qualifier == VersionFormatParser.ZERO_OR_ONE_QUALIFIER && this.isGroup()))) - qualifier.toString(sb); - } - } - - /** - * Specifies the min and max occurrences of a fragment - */ - static class Qualifier implements Serializable { - private static final long serialVersionUID = 7494021832824671685L; - - private final int max; - private final int min; - - Qualifier(int min, int max) { - this.min = min; - this.max = max; - } - - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof Qualifier)) - return false; - Qualifier oq = (Qualifier) o; - return min == oq.min && max == oq.max; - } - - public int hashCode() { - return 31 * min + 67 * max; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - toString(sb); - return sb.toString(); - } - - int getMax() { - return max; - } - - int getMin() { - return min; - } - - boolean parse(Fragment[] fragments, int fragIdx, List segments, String version, int maxPos, TreeInfo info) { - Fragment fragment = fragments[fragIdx++]; - int idx = 0; - - // Do the required parsing. I.e. iterate this fragment - // min number of times. - // - for (; idx < min; ++idx) - if (!fragment.parseOne(segments, version, maxPos, info)) - return false; - - for (; idx < max; ++idx) { - // We are greedy. Continue parsing until we get an exception - // and remember the state before each parse is performed. - // - info.pushState(segments.size(), fragment); - if (!fragment.parseOne(segments, version, maxPos, info)) { - info.popState(segments, fragment); - break; - } - } - int maxParsed = idx; - - for (;;) { - // Pad with default values unless the max is unbounded - // - if (max != Integer.MAX_VALUE) { - for (; idx < max; ++idx) - fragment.setDefaults(segments); - } - - if (fragIdx == fragments.length) - // We are the last segment - // - return true; - - // Try to parse the next segment. If it fails, pop the state of - // this segment (or a child thereof) and try again - // - if (fragments[fragIdx].getQualifier().parse(fragments, fragIdx, segments, version, maxPos, info)) - return true; - - // Be less greedy, step back one position and try again. - // - if (maxParsed <= min) - // We have no more states to pop. Tell previous that we failed. - // - return false; - - info.popState(segments, fragment); - idx = --maxParsed; // segments now have room for one more default value - } - } - - void toString(StringBuffer sb) { - if (min == 0) { - if (max == 1) - sb.append('?'); - else if (max == Integer.MAX_VALUE) - sb.append('*'); - else { - sb.append('{'); - sb.append(min); - sb.append(','); - sb.append(max); - sb.append('}'); - } - } else if (max == Integer.MAX_VALUE) { - if (min == 1) - sb.append('+'); - else { - sb.append('{'); - sb.append(min); - sb.append(",}"); //$NON-NLS-1$ - } - } else { - sb.append('{'); - sb.append(min); - if (min != max) { - sb.append(','); - sb.append(max); - } - sb.append('}'); - } - } - - // Preserve singleton when deserialized - private Object readResolve() { - Qualifier q = this; - if (min == 0) { - if (max == 1) - q = VersionFormatParser.ZERO_OR_ONE_QUALIFIER; - else if (max == Integer.MAX_VALUE) - q = VersionFormatParser.ZERO_OR_MANY_QUALIFIER; - } else if (min == 1) { - if (max == 1) - q = VersionFormatParser.EXACT_ONE_QUALIFIER; - else if (max == Integer.MAX_VALUE) - q = VersionFormatParser.ONE_OR_MANY_QUALIFIER; - } - return q; - } - } - - private static class AutoFragment extends RangeFragment { - private static final long serialVersionUID = -1016534328164247755L; - - AutoFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { - super(instr, qualifier); - } - - boolean parseOne(List segments, String version, int maxPos, TreeInfo info) { - int pos = info.getPosition(); - maxPos = checkRange(pos, maxPos); - if (maxPos < 0) - return false; - - char c = version.charAt(pos); - if (VersionParser.isDigit(c) && isAllowed(c)) { - // Parse to next non-digit - // - int start = pos; - int value = c - '0'; - while (++pos < maxPos) { - c = version.charAt(pos); - if (!(VersionParser.isDigit(c) && isAllowed(c))) - break; - value *= 10; - value += (c - '0'); - } - int len = pos - start; - if (rangeMin > len || len > rangeMax) - return false; - - if (!isIgnored()) - segments.add(Version.valueOf(value)); - info.setPosition(pos); - return true; - } - - if (!(VersionParser.isLetter(c) && isAllowed(c))) - return false; - - // Parse to next non-letter or next delimiter - // - int start = pos++; - for (; pos < maxPos; ++pos) { - c = version.charAt(pos); - if (!(VersionParser.isLetter(c) && isAllowed(c))) - break; - } - int len = pos - start; - if (rangeMin > len || len > rangeMax) - return false; - - if (!isIgnored()) - segments.add(version.substring(start, pos)); - info.setPosition(pos); - return true; - } - - void toString(StringBuffer sb) { - sb.append('a'); - super.toString(sb); - } - } - - private static class DelimiterFragment extends Fragment { - private static final long serialVersionUID = 8173654376143370605L; - private final char[] delimChars; - private final boolean inverted; - - DelimiterFragment(VersionFormatParser.Instructions ep, Qualifier qualifier) { - super(qualifier); - if (ep == null) { - delimChars = null; - inverted = false; - } else { - inverted = ep.inverted; - delimChars = ep.characters; - } - } - - boolean isMatch(String version, int pos) { - char c = version.charAt(pos); - if (delimChars != null) { - for (int idx = 0; idx < delimChars.length; ++idx) - if (c == delimChars[idx]) - return !inverted; - return inverted; - } else if (VersionParser.isLetterOrDigit(c)) - return false; - - return true; - } - - boolean parseOne(List segments, String version, int maxPos, TreeInfo info) { - int pos = info.getPosition(); - if (pos < maxPos && isMatch(version, pos)) { - // Just swallow, a delimiter does not contribute to the vector. - // - info.setPosition(pos + 1); - return true; - } - return false; - } - - void toString(StringBuffer sb) { - sb.append('d'); - if (delimChars != null) - appendCharacterRange(sb, delimChars, inverted); - super.toString(sb); - } - } - - static boolean equalsAllowNull(Object a, Object b) { - return (a == null) ? (b == null) : (b != null && a.equals(b)); - } - - private static abstract class ElementFragment extends Fragment { - private static final long serialVersionUID = -6834591415456539713L; - private final Comparable defaultValue; - private final boolean ignored; - private final Comparable padValue; - - ElementFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { - super(qualifier); - if (instr != null) { - ignored = instr.ignore; - defaultValue = instr.defaultValue; - padValue = instr.padValue; - } else { - ignored = false; - defaultValue = null; - padValue = null; - } - } - - Comparable getDefaultValue() { - return defaultValue; - } - - Comparable getPadValue() { - return padValue; - } - - boolean isIgnored() { - return ignored; - } - - void setDefaults(List segments) { - Object defaultVal = getDefaultValue(); - if (defaultVal != null) - segments.add(defaultVal); - } - - void toString(StringBuffer sb) { - if (ignored) { - sb.append('='); - sb.append('!'); - sb.append(';'); - } - if (defaultValue != null) { - sb.append('='); - VersionVector.rawToString(sb, false, defaultValue); - sb.append(';'); - } - if (padValue != null) { - sb.append('='); - sb.append('p'); - VersionVector.rawToString(sb, false, padValue); - sb.append(';'); - } - super.toString(sb); - } - } - - private static class GroupFragment extends ElementFragment { - private static final long serialVersionUID = 9219978678087669699L; - private final boolean array; - private final Fragment[] fragments; - - GroupFragment(VersionFormatParser.Instructions instr, Qualifier qualifier, Fragment[] fragments, boolean array) { - super(instr, qualifier); - this.fragments = fragments; - this.array = array; - } - - public boolean isGroup() { - return !array; - } - - Fragment getFirstLeaf() { - return fragments[0].getFirstLeaf(); - } - - boolean parseOne(List segments, String version, int maxPos, TreeInfo info) { - if (array) { - ArrayList subSegs = new ArrayList(); - boolean success = fragments[0].getQualifier().parse(fragments, 0, subSegs, version, maxPos, info); - if (!success || subSegs.isEmpty()) - return false; - - Comparable padValue = info.getPadValue(); - if (padValue != null) - info.setPadValue(null); // Prevent outer group from getting this. - else - padValue = getPadValue(); - - VersionParser.removeRedundantTrail(segments, padValue); - segments.add(new VersionVector((Comparable[]) subSegs.toArray(new Comparable[subSegs.size()]), padValue)); - return true; - } - - if (fragments[0].getQualifier().parse(fragments, 0, segments, version, maxPos, info)) { - Comparable padValue = getPadValue(); - if (padValue != null) - info.setPadValue(padValue); - return true; - } - return false; - } - - void setDefaults(List segments) { - Comparable dflt = getDefaultValue(); - if (dflt != null) { - // A group default overrides any defaults within the - // group fragments - super.setDefaults(segments); - } else { - // Assign defaults for all fragments - for (int idx = 0; idx < fragments.length; ++idx) - fragments[idx].setDefaults(segments); - } - } - - void toString(StringBuffer sb) { - if (array) { - sb.append('<'); - for (int idx = 0; idx < fragments.length; ++idx) - fragments[idx].toString(sb); - sb.append('>'); - } else { - if (getQualifier() == VersionFormatParser.ZERO_OR_ONE_QUALIFIER) { - sb.append('['); - for (int idx = 0; idx < fragments.length; ++idx) - fragments[idx].toString(sb); - sb.append(']'); - } else { - sb.append('('); - for (int idx = 0; idx < fragments.length; ++idx) - fragments[idx].toString(sb); - sb.append(')'); - } - } - super.toString(sb); - } - } - - private static class LiteralFragment extends Fragment { - private static final long serialVersionUID = 6210696245839471802L; - private final String string; - - LiteralFragment(Qualifier qualifier, String string) { - super(qualifier); - this.string = string; - } - - boolean parseOne(List segments, String version, int maxPos, TreeInfo info) { - int pos = info.getPosition(); - int litLen = string.length(); - if (pos + litLen > maxPos) - return false; - - for (int idx = 0; idx < litLen; ++idx, ++pos) { - if (string.charAt(idx) != version.charAt(pos)) - return false; - } - info.setPosition(pos); - return true; - } - - void toString(StringBuffer sb) { - String str = string; - if (str.length() != 1) { - sb.append('\''); - toStringEscaped(sb, str, "\'"); //$NON-NLS-1$ - sb.append('\''); - } else { - char c = str.charAt(0); - switch (c) { - case '\'' : - case '\\' : - case '<' : - case '[' : - case '(' : - case '{' : - case '?' : - case '*' : - case '+' : - case '=' : - sb.append('\\'); - sb.append(c); - break; - default : - if (VersionParser.isLetterOrDigit(c)) { - sb.append('\\'); - sb.append(c); - } else - sb.append(c); - } - } - super.toString(sb); - } - } - - private static class NumberFragment extends RangeFragment { - private static final long serialVersionUID = -8552754381106711507L; - private final boolean signed; - - NumberFragment(VersionFormatParser.Instructions instr, Qualifier qualifier, boolean signed) { - super(instr, qualifier); - this.signed = signed; - } - - boolean parseOne(List segments, String version, int maxPos, TreeInfo info) { - int pos = info.getPosition(); - maxPos = checkRange(pos, maxPos); - if (maxPos < 0) - return false; - - // Parse to next non-digit - // - int start = pos; - int value; - - char c = version.charAt(pos); - if (signed || characters != null) { - boolean negate = false; - if (signed && c == '-' && pos + 1 < maxPos) { - negate = true; - c = version.charAt(++pos); - } - - if (!(c >= '0' && c <= '9' && isAllowed(c))) - return false; - - // Parse to next non-digit - // - value = c - '0'; - while (++pos < maxPos) { - c = version.charAt(pos); - if (!(c >= '0' && c <= '9' && isAllowed(c))) - break; - value *= 10; - value += (c - '0'); - } - if (negate) - value = -value; - } else { - if (c < '0' || c > '9') - return false; - - // Parse to next non-digit - // - value = c - '0'; - while (++pos < maxPos) { - c = version.charAt(pos); - if (c < '0' || c > '9') - break; - value *= 10; - value += (c - '0'); - } - } - - int len = pos - start; - if (rangeMin > len || len > rangeMax) - return false; - - if (!isIgnored()) - segments.add(Version.valueOf(value)); - info.setPosition(pos); - return true; - } - - void toString(StringBuffer sb) { - sb.append(signed ? 'N' : 'n'); - super.toString(sb); - } - } - - private static class PadFragment extends ElementFragment { - private static final long serialVersionUID = 5052010199974380170L; - - PadFragment(Qualifier qualifier) { - super(null, qualifier); - } - - boolean parseOne(List segments, String version, int maxPos, TreeInfo info) { - int pos = info.getPosition(); - if (pos >= maxPos || version.charAt(pos) != 'p') - return false; - - int[] position = new int[] {++pos}; - Comparable v = VersionParser.parseRawElement(version, position, maxPos); - if (v == null) - return false; - - if (!isIgnored()) - info.setPadValue(v); - info.setPosition(position[0]); - return true; - } - - void toString(StringBuffer sb) { - sb.append('p'); - super.toString(sb); - } - } - - private static class QuotedFragment extends RangeFragment { - private static final long serialVersionUID = 6057751133533608969L; - - QuotedFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { - super(instr, qualifier); - } - - boolean parseOne(List segments, String version, int maxPos, TreeInfo info) { - int pos = info.getPosition(); - if (pos >= maxPos) - return false; - - char endQuote; - char quote = version.charAt(pos); - switch (quote) { - case '<' : - endQuote = '>'; - break; - case '{' : - endQuote = '}'; - break; - case '(' : - endQuote = ')'; - break; - case '[' : - endQuote = ']'; - break; - case '>' : - endQuote = '<'; - break; - case '}' : - endQuote = '{'; - break; - case ')' : - endQuote = '('; - break; - case ']' : - endQuote = '['; - break; - default : - if (VersionParser.isLetterOrDigit(quote)) - return false; - endQuote = quote; - } - int start = ++pos; - char c = version.charAt(pos); - while (c != endQuote && isAllowed(c) && ++pos < maxPos) - c = version.charAt(pos); - - if (c != endQuote || rangeMin > pos - start) - // End quote not found - return false; - - int len = pos - start; - if (rangeMin > len || len > rangeMax) - return false; - - if (!isIgnored()) - segments.add(version.substring(start, pos)); - info.setPosition(++pos); // Skip quote - return true; - } - - void toString(StringBuffer sb) { - sb.append('q'); - super.toString(sb); - } - } - - private static abstract class RangeFragment extends ElementFragment { - private static final long serialVersionUID = -6680402803630334708L; - final char[] characters; - final boolean inverted; - final int rangeMax; - final int rangeMin; - - RangeFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { - super(instr, qualifier); - if (instr == null) { - characters = null; - inverted = false; - rangeMin = 0; - rangeMax = Integer.MAX_VALUE; - } else { - characters = instr.characters; - inverted = instr.inverted; - rangeMin = instr.rangeMin; - rangeMax = instr.rangeMax; - } - } - - /** - * Checks that pos is at a valid character position, that we - * have at least the required minimum characters left, and - * if a maximum number of characters is set, limits the - * returned value to a maxPos that reflects that maximum. - * @param pos the current position - * @param maxPos the current maxPos - * @return maxPos, possibly limited by rangeMax - */ - int checkRange(int pos, int maxPos) { - int check = pos; - if (rangeMin == 0) - check++; // Verify one character - else - check += rangeMin; - - if (check > maxPos) - // Less then min characters left - maxPos = -1; - else { - if (rangeMax != Integer.MAX_VALUE) { - check = pos + rangeMax; - if (check < maxPos) - maxPos = check; - } - } - return maxPos; - } - - boolean isAllowed(char c) { - char[] crs = characters; - if (crs != null) { - int idx = crs.length; - while (--idx >= 0) - if (c == crs[idx]) - return !inverted; - return inverted; - } - return true; - } - - void toString(StringBuffer sb) { - if (characters != null) - appendCharacterRange(sb, characters, inverted); - if (rangeMin != 0 || rangeMax != Integer.MAX_VALUE) { - sb.append('='); - sb.append('{'); - sb.append(rangeMin); - if (rangeMin != rangeMax) { - sb.append(','); - if (rangeMax != Integer.MAX_VALUE) - sb.append(rangeMax); - } - sb.append('}'); - sb.append(';'); - } - super.toString(sb); - } - } - - private static class RawFragment extends ElementFragment { - private static final long serialVersionUID = 4107448125256042602L; - - RawFragment(VersionFormatParser.Instructions processing, Qualifier qualifier) { - super(processing, qualifier); - } - - boolean parseOne(List segments, String version, int maxPos, TreeInfo info) { - int[] position = new int[] {info.getPosition()}; - Comparable v = VersionParser.parseRawElement(version, position, maxPos); - if (v == null) - return false; - - if (!isIgnored()) - segments.add(v); - info.setPosition(position[0]); - return true; - } - - void toString(StringBuffer sb) { - sb.append('r'); - super.toString(sb); - } - } - - private static class StringFragment extends RangeFragment { - private static final long serialVersionUID = -2265924553606430164L; - final boolean anyChar; - - StringFragment(VersionFormatParser.Instructions instr, Qualifier qualifier, boolean noLimit) { - super(instr, qualifier); - anyChar = noLimit; - } - - boolean parseOne(List segments, String version, int maxPos, TreeInfo info) { - int pos = info.getPosition(); - maxPos = checkRange(pos, maxPos); - if (maxPos < 0) - return false; - - // Parse to next delimiter or end of string - // - int start = pos; - if (characters != null) { - if (anyChar) { - // Swallow everything that matches the allowed characters - for (; pos < maxPos; ++pos) { - if (!isAllowed(version.charAt(pos))) - break; - } - } else { - // Swallow letters that matches the allowed characters - for (; pos < maxPos; ++pos) { - char c = version.charAt(pos); - if (!(VersionParser.isLetter(c) && isAllowed(c))) - break; - } - } - } else { - if (anyChar) - // Swallow all characters - pos = maxPos; - else { - // Swallow all letters - for (; pos < maxPos; ++pos) { - if (!VersionParser.isLetter(version.charAt(pos))) - break; - } - } - } - int len = pos - start; - if (len == 0 || rangeMin > len || len > rangeMax) - return false; - - if (!isIgnored()) - segments.add(version.substring(start, pos)); - info.setPosition(pos); - return true; - } - - void toString(StringBuffer sb) { - sb.append(anyChar ? 'S' : 's'); - super.toString(sb); - } - } - - private static class TreeInfo extends ArrayList { - private static final long serialVersionUID = 4770093863009659750L; - - private static class StateInfo { - Fragment fragment; - int segmentCount; - int position; - - StateInfo(int position, int segmentCount, Fragment fragment) { - this.fragment = fragment; - this.position = position; - this.segmentCount = segmentCount; - } - } - - private Comparable padValue; - private int top; - - TreeInfo(Fragment frag, int pos) { - add(new StateInfo(pos, 0, frag)); - top = 0; - } - - Comparable getPadValue() { - return padValue; - } - - int getPosition() { - return ((StateInfo) get(top)).position; - } - - void popState(List segments, Fragment frag) { - int idx = top; - while (idx > 0) { - StateInfo si = (StateInfo) get(idx); - if (si.fragment == frag) { - int nsegs = segments.size(); - int segMax = si.segmentCount; - while (nsegs > segMax) - segments.remove(--nsegs); - top = idx - 1; - break; - } - } - } - - void pushState(int segCount, Fragment fragment) { - int pos = ((StateInfo) get(top)).position; - if (++top == size()) - add(new StateInfo(pos, segCount, fragment)); - else { - StateInfo si = (StateInfo) get(top); - si.fragment = fragment; - si.position = pos; - si.segmentCount = segCount; - } - } - - void setPadValue(Comparable pad) { - padValue = pad; - } - - void setPosition(int pos) { - ((StateInfo) get(top)).position = pos; - } - } - - /** - * The predefined OSGi format that is used when parsing OSGi - * versions. - */ - public static final VersionFormat OSGI_FORMAT; - - /** - * The predefined OSGi format that is used when parsing raw - * versions. - */ - public static final VersionFormat RAW_FORMAT; - - private static final Map formatCache = Collections.synchronizedMap(new HashMap()); - - private static final String OSGI_FORMAT_STRING = "n[.n=0;[.n=0;[.S=[A-Za-z0-9_-];]]]"; //$NON-NLS-1$ - - private static final String RAW_FORMAT_STRING = "r(.r)*p?"; //$NON-NLS-1$ - - static { - try { - VersionFormatParser parser = new VersionFormatParser(); - OSGI_FORMAT = new VersionFormat(parser.compile(OSGI_FORMAT_STRING, 0, OSGI_FORMAT_STRING.length())); - formatCache.put(OSGI_FORMAT_STRING, OSGI_FORMAT); - RAW_FORMAT = new RawFormat(parser.compile(RAW_FORMAT_STRING, 0, RAW_FORMAT_STRING.length())); - formatCache.put(RAW_FORMAT_STRING, RAW_FORMAT); - } catch (FormatException e) { - // If this happens, something is wrong with the actual - // implementation of the FormatCompiler. - // - throw new ExceptionInInitializerError(e); - } - } - - /** - * Compile a version format string into a compiled format. This method is - * shorthand for:
    CompiledFormat.compile(format, 0, format.length())
    . - * - * @param format The format to compile. - * @return The compiled format - * @throws FormatException If the format could not be compiled - */ - public static VersionFormat compile(String format) throws FormatException { - return compile(format, 0, format.length()); - } - - /** - * Compile a version format string into a compiled format. The parsing starts - * at position start and ends at position end. The returned format is cached so - * subsequent calls to this method using the same format string will yield the - * same compiled format instance. - * - * @param format The format string to compile. - * @param start Start position in the format string - * @param end End position in the format string - * @return The compiled format - * @throws FormatException If the format could not be compiled - */ - public static VersionFormat compile(String format, int start, int end) throws FormatException { - String fmtString = format.substring(start, end).intern(); - synchronized (fmtString) { - VersionFormat fmt = (VersionFormat) formatCache.get(fmtString); - if (fmt == null) { - VersionFormatParser parser = new VersionFormatParser(); - fmt = new VersionFormat(parser.compile(format, start, end)); - formatCache.put(fmtString, fmt); - } - return fmt; - } - } - - /** - * Parse a version string using the {@link #RAW_FORMAT} parser. - * - * @param version The version to parse. - * @param originalFormat The original format to assign to the created version. Can be null. - * @param original The original version string to assign to the created version. Can be null. - * @return A created version - * @throws IllegalArgumentException If the version string could not be parsed. - */ - static Version parseRaw(String version, VersionFormat originalFormat, String original) { - Comparable[] padReturn = new Comparable[1]; - Comparable[] vector = RAW_FORMAT.parse(version, 0, version.length(), padReturn); - return new Version(vector, padReturn[0], originalFormat, original); - } - - static void appendCharacterRange(StringBuffer sb, char[] range, boolean inverted) { - sb.append('='); - sb.append('['); - if (inverted) - sb.append('^'); - int top = range.length; - for (int idx = 0; idx < top; ++idx) { - char b = range[idx]; - if (b == '\\' || b == ']' || (b == '-' && idx + 1 < top)) - sb.append('\\'); - - sb.append(b); - int ndx = idx + 1; - if (ndx + 2 < top) { - char c = b; - for (; ndx < top; ++ndx) { - char n = range[ndx]; - if (c + 1 != n) - break; - c = n; - } - if (ndx <= idx + 3) - continue; - - sb.append('-'); - if (c == '\\' || c == ']' || (c == '-' && idx + 1 < top)) - sb.append('\\'); - sb.append(c); - idx = ndx - 1; - } - } - sb.append(']'); - sb.append(';'); - } - - static Fragment createAutoFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { - return new AutoFragment(instr, qualifier); - } - - static Fragment createDelimiterFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { - return new DelimiterFragment(instr, qualifier); - } - - static Fragment createGroupFragment(VersionFormatParser.Instructions instr, Qualifier qualifier, Fragment[] fragments, boolean array) { - return new GroupFragment(instr, qualifier, fragments, array); - } - - static Fragment createLiteralFragment(Qualifier qualifier, String literal) { - return new LiteralFragment(qualifier, literal); - } - - static Fragment createNumberFragment(VersionFormatParser.Instructions instr, Qualifier qualifier, boolean signed) { - return new NumberFragment(instr, qualifier, signed); - } - - static Fragment createPadFragment(Qualifier qualifier) { - return new PadFragment(qualifier); - } - - static Fragment createQuotedFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { - return new QuotedFragment(instr, qualifier); - } - - static Fragment createRawFragment(VersionFormatParser.Instructions instr, Qualifier qualifier) { - return new RawFragment(instr, qualifier); - } - - static Fragment createStringFragment(VersionFormatParser.Instructions instr, Qualifier qualifier, boolean unbound) { - return new StringFragment(instr, qualifier, unbound); - } - - static void toStringEscaped(StringBuffer sb, String value, String escapes) { - for (int idx = 0; idx < value.length(); ++idx) { - char c = value.charAt(idx); - if (c == '\\' || escapes.indexOf(c) >= 0) - sb.append('\\'); - sb.append(c); - } - } - - private final Fragment topFragment; - - private String fmtString; - - VersionFormat(Fragment topFragment) { - this.topFragment = topFragment; - } - - public boolean equals(Object o) { - return this == o || o instanceof VersionFormat && toString().equals(o.toString()); - } - - public int hashCode() { - return 11 * toString().hashCode(); - } - - /** - * Parse the given version string. - * @param version The version string to parse. - * @return A created version. - * @throws IllegalArgumentException If the version string could not be parsed. - */ - public Version parse(String version) { - return parse(version, 0, version.length()); - } - - /** - * Parse the given version string. - * @param version The version string to parse. - * @param start Start position in the version string - * @return A created version. - * @throws IllegalArgumentException If the version string could not be parsed. - */ - public Version parse(String version, int start, int maxPos) { - Comparable[] padReturn = new Comparable[1]; - Comparable[] vector = parse(version, start, maxPos, padReturn); - return new Version(vector, padReturn[0], this, version.substring(start, maxPos)); - } - - /** - * Returns the string representation of this compiled format - */ - public synchronized String toString() { - if (fmtString == null) { - StringBuffer sb = new StringBuffer(); - toString(sb); - } - return fmtString; - } - - /** - * Appends the string representation of this compiled format to - * the given StringBuffer. - * @param sb The buffer that will receive the string representation - */ - public synchronized void toString(StringBuffer sb) { - if (fmtString != null) - sb.append(fmtString); - else { - int start = sb.length(); - sb.append("format"); //$NON-NLS-1$ - if (topFragment.getPadValue() != null) { - sb.append('('); - topFragment.toString(sb); - sb.append(')'); - } else - topFragment.toString(sb); - fmtString = sb.substring(start); - } - } - - TreeInfo createInfo(int start) { - return new TreeInfo(topFragment, start); - } - - Comparable[] parse(String version, int start, int maxPos, Comparable[] padReturn) { - ArrayList entries = new ArrayList(); - if (start == maxPos) - throw new IllegalArgumentException(NLS.bind(Messages.format_0_unable_to_parse_empty_version, this, version.substring(start, maxPos))); - TreeInfo info = new TreeInfo(topFragment, start); - if (!(topFragment.parse(entries, version, maxPos, info) && info.getPosition() == maxPos)) - throw new IllegalArgumentException(NLS.bind(Messages.format_0_unable_to_parse_1, this, version.substring(start, maxPos))); - Comparable pad = info.getPadValue(); - VersionParser.removeRedundantTrail(entries, pad); - padReturn[0] = pad; - return (Comparable[]) entries.toArray(new Comparable[entries.size()]); - } - - // Preserve cache during deserialization - private Object readResolve() { - synchronized (formatCache) { - String string = toString(); - VersionFormat fmt = (VersionFormat) formatCache.put(string, this); - if (fmt == null) - fmt = this; - else - // Put old format back - formatCache.put(string, fmt); - return fmt; - } - } -} - -class RawFormat extends VersionFormat { - private static final long serialVersionUID = 8851695938450999819L; - - RawFormat(Fragment topFragment) { - super(topFragment); - } - - /** - * Parse but do not assign this format as the Version format nor the version - * string as the original. - */ - public Version parse(String version, int start, int maxPos) { - Comparable[] padReturn = new Comparable[1]; - Comparable[] vector = parse(version, start, maxPos, padReturn); - return new Version(vector, padReturn[0], null, null); - } - - // Preserve singleton when deserialized - private Object readResolve() { - return RAW_FORMAT; - } -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionFormatParser.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionFormatParser.java deleted file mode 100644 index 903d15c92..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionFormatParser.java +++ /dev/null @@ -1,530 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Cloudsmith Inc. and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Cloudsmith Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -import org.eclipse.equinox.internal.p2.metadata.Messages; - -import java.util.ArrayList; -import java.util.List; -import org.eclipse.osgi.util.NLS; - -/** - * This is the Omni Version Format parser. It will parse a version format in string form - * into a group of {@link VersionFormat.Fragment} elements. That group, wrapped in a - * {@link VersionFormat}, becomes the parser for versions corresponding to the format. - * - * The class is not intended to included in a public API. Instead VersionFormats should - * be created using {@link VersionFormat#parse(String)} - * - */ -class VersionFormatParser { - - static class Instructions { - char[] characters = null; - Comparable defaultValue = null; - boolean ignore = false; - boolean inverted = false; - Comparable padValue = null; - int rangeMax = Integer.MAX_VALUE; - int rangeMin = 0; - } - - static final VersionFormat.Qualifier EXACT_ONE_QUALIFIER = new VersionFormat.Qualifier(1, 1); - - static final VersionFormat.Qualifier ONE_OR_MANY_QUALIFIER = new VersionFormat.Qualifier(1, Integer.MAX_VALUE); - - static final VersionFormat.Qualifier ZERO_OR_MANY_QUALIFIER = new VersionFormat.Qualifier(0, Integer.MAX_VALUE); - - static final VersionFormat.Qualifier ZERO_OR_ONE_QUALIFIER = new VersionFormat.Qualifier(0, 1); - - private int current; - - private List currentList; - - private int eos; - - private String format; - - private int start; - - VersionFormat.Fragment compile(String fmt, int pos, int maxPos) throws FormatException { - format = fmt; - if (start >= maxPos) - throw new FormatException(Messages.format_is_empty); - - start = pos; - current = pos; - eos = maxPos; - currentList = new ArrayList(); - while (current < eos) - parseFragment(); - - VersionFormat.Fragment topFrag; - switch (currentList.size()) { - case 0 : - throw new FormatException(Messages.format_is_empty); - case 1 : - VersionFormat.Fragment frag = (VersionFormat.Fragment) currentList.get(0); - if (frag.isGroup()) { - topFrag = frag; - break; - } - // Fall through to default - default : - topFrag = VersionFormat.createGroupFragment(null, EXACT_ONE_QUALIFIER, (VersionFormat.Fragment[]) currentList.toArray(new VersionFormat.Fragment[currentList.size()]), false); - } - currentList = null; - return topFrag; - } - - private void assertChar(char expected) throws FormatException { - if (current >= eos) - throw formatException(NLS.bind(Messages.premature_end_of_format_expected_0, new String(new char[] {expected}))); - - char c = format.charAt(current); - if (c != expected) - throw formatException(c, new String(new char[] {expected})); - ++current; - } - - private FormatException formatException(char found, String expected) { - return formatException(new String(new char[] {found}), expected); - } - - private FormatException formatException(String message) { - return new FormatException(NLS.bind(Messages.syntax_error_in_version_format_0_1_2, new Object[] {format.substring(start, eos), new Integer(current), message})); - } - - private FormatException formatException(String found, String expected) { - return new FormatException(NLS.bind(Messages.syntax_error_in_version_format_0_1_found_2_expected_3, new Object[] {format.substring(start, eos), new Integer(current), found, expected})); - } - - private FormatException illegalControlCharacter(char c) { - return formatException(NLS.bind(Messages.illegal_character_encountered_ascii_0, Version.valueOf(c))); - } - - private String parseAndConsiderEscapeUntil(char endChar) throws FormatException { - StringBuffer sb = new StringBuffer(); - while (current < eos) { - char c = format.charAt(current++); - if (c == endChar) - break; - - if (c < 32) - throw illegalControlCharacter(c); - - if (c == '\\') { - if (current == eos) - throw formatException(Messages.EOS_after_escape); - c = format.charAt(current++); - if (c < 32) - throw illegalControlCharacter(c); - } - sb.append(c); - } - return sb.toString(); - } - - private void parseAuto() throws FormatException { - VersionFormatParser.Instructions ep = parseProcessing(); - if (ep != null) { - if (ep.padValue != null) - throw formatException(Messages.auto_can_not_have_pad_value); - } - currentList.add(VersionFormat.createAutoFragment(ep, parseQualifier())); - } - - private void parseBracketGroup() throws FormatException { - List saveList = currentList; - currentList = new ArrayList(); - while (current < eos && format.charAt(current) != ']') - parseFragment(); - - if (current == eos) - throw formatException(NLS.bind(Messages.premature_end_of_format_expected_0, "]")); //$NON-NLS-1$ - - ++current; - VersionFormatParser.Instructions ep = parseProcessing(); - saveList.add(VersionFormat.createGroupFragment(ep, ZERO_OR_ONE_QUALIFIER, (VersionFormat.Fragment[]) currentList.toArray(new VersionFormat.Fragment[currentList.size()]), false)); - currentList = saveList; - } - - private void parseCharacterGroup(VersionFormatParser.Instructions ep) throws FormatException { - assertChar('['); - - StringBuffer sb = new StringBuffer(); - outer: for (; current < eos; ++current) { - char c = format.charAt(current); - switch (c) { - case '\\' : - if (current + 1 < eos) { - sb.append(format.charAt(++current)); - continue; - } - throw formatException(Messages.premature_end_of_format); - case '^' : - if (sb.length() == 0) - ep.inverted = true; - else - sb.append(c); - continue; - case ']' : - break outer; - case '-' : - if (sb.length() > 0 && current + 1 < eos) { - char rangeEnd = format.charAt(++current); - if (rangeEnd == ']') { - // Use dash verbatim when last in range - sb.append(c); - break outer; - } - - char rangeStart = sb.charAt(sb.length() - 1); - if (rangeEnd < rangeStart) - throw formatException(Messages.negative_character_range); - while (++rangeStart <= rangeEnd) - sb.append(rangeStart); - continue; - } - // Fall through to default - default : - if (c < 32) - throw illegalControlCharacter(c); - sb.append(c); - } - } - assertChar(']'); - int top = sb.length(); - char[] chars = new char[top]; - sb.getChars(0, top, chars, 0); - ep.characters = chars; - } - - private void parseDelimiter() throws FormatException { - VersionFormatParser.Instructions ep = parseProcessing(); - if (ep != null) { - if (ep.rangeMin != 0 || ep.rangeMax != Integer.MAX_VALUE) - throw formatException(Messages.delimiter_can_not_have_range); - if (ep.ignore) - throw formatException(Messages.delimiter_can_not_be_ignored); - if (ep.defaultValue != null) - throw formatException(Messages.delimiter_can_not_have_default_value); - if (ep.padValue != null) - throw formatException(Messages.delimiter_can_not_have_pad_value); - } - currentList.add(VersionFormat.createDelimiterFragment(ep, parseQualifier())); - } - - private void parseFragment() throws FormatException { - if (current == eos) - throw formatException(Messages.premature_end_of_format); - char c = format.charAt(current++); - switch (c) { - case '(' : - parseGroup(false); - break; - case '<' : - parseGroup(true); - break; - case '[' : - parseBracketGroup(); - break; - case 'a' : - parseAuto(); - break; - case 'r' : - parseRaw(); - break; - case 'n' : - parseNumber(false); - break; - case 'N' : - parseNumber(true); - break; - case 's' : - parseString(false); - break; - case 'S' : - parseString(true); - break; - case 'd' : - parseDelimiter(); - break; - case 'q' : - parseQuotedString(); - break; - case 'p' : - parsePad(); - break; - default : - parseLiteral(c); - } - } - - private void parseGroup(boolean array) throws FormatException { - List saveList = currentList; - currentList = new ArrayList(); - char expectedEnd = array ? '>' : ')'; - while (current < eos && format.charAt(current) != expectedEnd) - parseFragment(); - assertChar(expectedEnd); - - VersionFormatParser.Instructions ep = parseProcessing(); - if (ep != null) { - if (ep.characters != null) - throw formatException(Messages.array_can_not_have_character_group); - if (ep.rangeMax != Integer.MAX_VALUE && ep.padValue != null) { - throw formatException(Messages.cannot_combine_range_upper_bound_with_pad_value); - } - } - - if (currentList.isEmpty()) - throw formatException(array ? Messages.array_can_not_be_empty : Messages.group_can_not_be_empty); - saveList.add(VersionFormat.createGroupFragment(ep, parseQualifier(), (VersionFormat.Fragment[]) currentList.toArray(new VersionFormat.Fragment[currentList.size()]), array)); - currentList = saveList; - } - - private int parseIntegerLiteral() throws FormatException { - if (current == eos) - throw formatException(NLS.bind(Messages.premature_end_of_format_expected_0, "")); //$NON-NLS-1$ - - char c = format.charAt(current); - if (!VersionParser.isDigit(c)) - throw formatException(c, ""); //$NON-NLS-1$ - - int value = c - '0'; - while (++current < eos) { - c = format.charAt(current); - if (!VersionParser.isDigit(c)) - break; - value *= 10; - value += (c - '0'); - } - return value; - } - - private void parseLiteral(char c) throws FormatException { - String value; - switch (c) { - case '\'' : - value = parseAndConsiderEscapeUntil(c); - break; - case ')' : - case ']' : - case '{' : - case '}' : - case '?' : - case '*' : - throw formatException(c, ""); //$NON-NLS-1$ - default : - if (VersionParser.isLetterOrDigit(c)) - throw formatException(c, ""); //$NON-NLS-1$ - - if (c < 32) - throw illegalControlCharacter(c); - - if (c == '\\') { - if (current == eos) - throw formatException(Messages.EOS_after_escape); - c = format.charAt(current++); - if (c < 32) - throw illegalControlCharacter(c); - } - value = new String(new char[] {c}); - } - currentList.add(VersionFormat.createLiteralFragment(parseQualifier(), value)); - } - - private int[] parseMinMax() throws FormatException { - - int max = Integer.MAX_VALUE; - ++current; - int min = parseIntegerLiteral(); - char c = format.charAt(current); - if (c == '}') { - max = min; - if (max == 0) - throw formatException(Messages.range_max_cannot_be_zero); - ++current; - } else if (c == ',' && current + 1 < eos) { - if (format.charAt(++current) != '}') { - max = parseIntegerLiteral(); - if (max == 0) - throw formatException(Messages.range_max_cannot_be_zero); - if (max < min) - throw formatException(Messages.range_max_cannot_be_less_then_range_min); - } - assertChar('}'); - } else - throw formatException(c, "},"); //$NON-NLS-1$ - return new int[] {min, max}; - } - - private void parseNumber(boolean signed) throws FormatException { - VersionFormatParser.Instructions ep = parseProcessing(); - if (ep != null) { - if (ep.padValue != null) - throw formatException(Messages.number_can_not_have_pad_value); - } - currentList.add(VersionFormat.createNumberFragment(ep, parseQualifier(), signed)); - } - - private void parsePad() throws FormatException { - currentList.add(VersionFormat.createPadFragment(parseQualifier())); - } - - private VersionFormatParser.Instructions parseProcessing() throws FormatException { - if (current >= eos) - return null; - - char c = format.charAt(current); - if (c != '=') - return null; - - VersionFormatParser.Instructions ep = new VersionFormatParser.Instructions(); - do { - current++; - parseProcessingInstruction(ep); - } while (current < eos && format.charAt(current) == '='); - return ep; - } - - private void parseProcessingInstruction(VersionFormatParser.Instructions processing) throws FormatException { - if (current == eos) - throw formatException(Messages.premature_end_of_format); - - char c = format.charAt(current); - if (c == 'p') { - // =pad(); - // - if (processing.padValue != null) - throw formatException(Messages.pad_defined_more_then_once); - if (processing.ignore) - throw formatException(Messages.cannot_combine_ignore_with_other_instruction); - ++current; - processing.padValue = parseRawElement(); - } else if (c == '!') { - // =ignore; - // - if (processing.ignore) - throw formatException(Messages.ignore_defined_more_then_once); - if (processing.padValue != null || processing.characters != null || processing.rangeMin != 0 || processing.rangeMax != Integer.MAX_VALUE || processing.defaultValue != null) - throw formatException(Messages.cannot_combine_ignore_with_other_instruction); - ++current; - processing.ignore = true; - } else if (c == '[') { - // =[; - if (processing.defaultValue != null) - throw formatException(Messages.default_defined_more_then_once); - if (processing.ignore) - throw formatException(Messages.cannot_combine_ignore_with_other_instruction); - processing.defaultValue = parseRawElement(); - } - assertChar(';'); - } - - private VersionFormat.Qualifier parseQualifier() throws FormatException { - if (current >= eos) - return EXACT_ONE_QUALIFIER; - - char c = format.charAt(current); - if (c == '?') { - ++current; - return ZERO_OR_ONE_QUALIFIER; - } - - if (c == '*') { - ++current; - return ZERO_OR_MANY_QUALIFIER; - } - - if (c == '+') { - ++current; - return ONE_OR_MANY_QUALIFIER; - } - - if (c != '{') - return EXACT_ONE_QUALIFIER; - - int[] minMax = parseMinMax(); - int min = minMax[0]; - int max = minMax[1]; - - // Use singletons for commonly used ranges - // - if (min == 0) { - if (max == 1) - return ZERO_OR_ONE_QUALIFIER; - if (max == Integer.MAX_VALUE) - return ZERO_OR_MANY_QUALIFIER; - } else if (min == 1) { - if (max == 1) - return EXACT_ONE_QUALIFIER; - if (max == Integer.MAX_VALUE) - return ONE_OR_MANY_QUALIFIER; - } - return new VersionFormat.Qualifier(min, max); - } - - private void parseQuotedString() throws FormatException { - VersionFormatParser.Instructions ep = parseProcessing(); - if (ep != null) { - if (ep.padValue != null) - throw formatException(Messages.string_can_not_have_pad_value); - } - currentList.add(VersionFormat.createQuotedFragment(ep, parseQualifier())); - } - - private void parseRaw() throws FormatException { - VersionFormatParser.Instructions ep = parseProcessing(); - if (ep != null) { - if (ep.padValue != null) - throw formatException(Messages.raw_element_can_not_have_pad_value); - } - currentList.add(VersionFormat.createRawFragment(ep, parseQualifier())); - } - - private Comparable parseRawElement() throws FormatException { - int[] position = new int[] {current}; - Comparable v = VersionParser.parseRawElement(format, position, eos); - if (v == null) - throw new FormatException(NLS.bind(Messages.raw_element_expected_0, format)); - current = position[0]; - return v; - } - - private void parseString(boolean unlimited) throws FormatException { - VersionFormatParser.Instructions ep = parseProcessing(); - if (ep != null) { - if (ep.padValue != null) - throw formatException(Messages.string_can_not_have_pad_value); - } - currentList.add(VersionFormat.createStringFragment(ep, parseQualifier(), unlimited)); - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionParser.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionParser.java deleted file mode 100644 index 138d895b8..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionParser.java +++ /dev/null @@ -1,366 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Cloudsmith Inc. and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Cloudsmith Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -import org.eclipse.equinox.internal.p2.metadata.Messages; - -import java.util.ArrayList; -import java.util.List; -import org.eclipse.osgi.util.NLS; - -/** - * The Omni Version parser. Not intended for public API. Instead use - * {@link Version#Version(String)} or {@link Version#parseVersion(String)}. - * - * The class also contains some general purpose parser support methods - * - * @noextend This class is not intended to be subclassed by clients. - */ -abstract class VersionParser { - static void removeRedundantTrail(List segments, Comparable padValue) { - Comparable redundantTrail = padValue == null ? VersionVector.MIN_VALUE : padValue; - int idx = segments.size(); - while (--idx >= 0 && segments.get(idx).equals(redundantTrail)) - segments.remove(idx); - } - - static final String RAW_PREFIX = "raw:"; //$NON-NLS-1$ - - private VersionParser() { - // Prevent class from being instantiated - } - - /** - * Parse the version string and assing the parsed portions to the receiver. - * This method is called from the version string constructor. - * - * @param version The string to be parsed - * @param start Start position in the version string - * @param maxPos End position in the version string - * @param receiver The version to be filled in - * @returns true if a version indeed was parsed or false if the string - * contained only whitespace. - * @throws IllegalArgumentException if the version is malformed - */ - static boolean parseInto(String version, int start, int maxPos, Version receiver) throws IllegalArgumentException { - // trim leading and trailing whitespace - int pos = skipWhite(version, start); - maxPos = skipTrailingWhite(version, start, maxPos); - if (pos == maxPos) - return false; - - Comparable[] padReturn = new Comparable[1]; - Comparable[] vector = null; - Comparable pad = null; - VersionFormat fmt = null; - char c = version.charAt(pos); - if (isDigit(c)) { - fmt = VersionFormat.OSGI_FORMAT; - vector = fmt.parse(version, pos, maxPos, padReturn); - receiver.init(vector, padReturn[0], fmt, version); - return true; - } - - if (!isLetter(c)) - throw new IllegalArgumentException(); - - if (version.startsWith(RAW_PREFIX, pos)) { - VersionFormat rawFmt = VersionFormat.RAW_FORMAT; - pos += 4; - - // Find ending '/' that is neither quoted or escaped - int end = maxPos; - for (int idx = pos; idx < maxPos; ++idx) { - c = version.charAt(idx); - switch (c) { - case '/' : - end = idx; - break; - case '\\' : - ++idx; - continue; - case '\'' : - case '"' : - for (++idx; idx < maxPos; ++idx) { - char e = version.charAt(idx); - if (e == c) { - break; - } - if (e == '\\') - ++idx; - } - // fall through to default - default : - continue; - } - break; - } - - vector = rawFmt.parse(version, pos, end, padReturn); - pad = padReturn[0]; - pos = end; - if (pos == maxPos) { - // This was a pure raw version - // - receiver.init(vector, pad, null, null); - return true; - } - - if (version.charAt(pos) != '/') - throw new IllegalArgumentException(NLS.bind(Messages.expected_slash_after_raw_vector_0, version.substring(start, maxPos))); - ++pos; - - if (pos == maxPos) - throw new IllegalArgumentException(NLS.bind(Messages.expected_orignal_after_slash_0, version.substring(start, maxPos))); - } - - if (version.startsWith("format(", pos)) { //$NON-NLS-1$ - // Parse the format - // - pos += 7; - try { - // Find matching ')' that is neither quoted or escaped - // - int end = findEndOfFormat(version, pos, maxPos); - fmt = VersionFormat.compile(version, pos, end); - pos = end + 1; - } catch (FormatException e) { - throw new IllegalArgumentException(e.getMessage()); - } - if (pos == maxPos) { - // This was a raw version with format but no original - // - if (vector == null) - throw new IllegalArgumentException(NLS.bind(Messages.only_format_specified_0, version.substring(start, maxPos))); - receiver.init(vector, pad, fmt, null); - return true; - } - } - - if (fmt == null && vector == null) - throw new IllegalArgumentException(NLS.bind(Messages.neither_raw_vector_nor_format_specified_0, version.substring(start, maxPos))); - - if (version.charAt(pos) != ':') - throw new IllegalArgumentException(NLS.bind(Messages.colon_expected_before_original_version_0, version.substring(start, maxPos))); - - pos++; - if (pos == maxPos) - throw new IllegalArgumentException(NLS.bind(Messages.expected_orignal_after_colon_0, version.substring(start, maxPos))); - - if (vector == null) { - // Vector and pad must be created by parsing the original - // - vector = fmt.parse(version, pos, maxPos, padReturn); - pad = padReturn[0]; - } - receiver.init(vector, pad, fmt, version.substring(pos)); - return true; - } - - static boolean isDigit(char c) { - return c >= '0' && c <= '9'; - } - - static boolean isLetter(char c) { - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); - } - - static boolean isLetterOrDigit(char c) { - return isDigit(c) || isLetter(c); - } - - static int findEndOfFormat(String string, int pos, int maxPos) { - int end = -1; - int depth = 1; - for (int idx = pos; idx < maxPos; ++idx) { - char c = string.charAt(idx); - switch (c) { - case ')' : - if (--depth == 0) { - end = idx; - break; - } - continue; - case '(' : - ++depth; - continue; - case '\\' : - ++idx; - continue; - case '\'' : - case '"' : - for (++idx; idx < maxPos; ++idx) { - char e = string.charAt(idx); - if (e == c) { - break; - } - if (e == '\\') - ++idx; - } - // fall through to default - default : - continue; - } - break; - } - if (depth != 0) - throw new IllegalArgumentException(NLS.bind(Messages.unbalanced_format_parenthesis, string.substring(pos - 1, maxPos))); - return end; - } - - static Comparable parseRawElement(String value, int[] position, int maxPos) { - int current = position[0]; - if (current >= maxPos) - return null; - - boolean negate = false; - char c = value.charAt(current); - Comparable v; - switch (c) { - case '\'' : - case '"' : { - StringBuffer sb = new StringBuffer(); - for (;;) { - char q = c; - if (++current == maxPos) - return null; - c = value.charAt(current); - while (c != q) { - if (c < 32) - return null; - sb.append(c); - if (++current == maxPos) - return null; - c = value.charAt(current); - } - if (++current == maxPos) - break; - c = value.charAt(current); - if (c != '\'' && c != '"') - break; - } - v = sb.toString(); - break; - } - case '<' : { - if (++current == maxPos) - return null; - - position[0] = current; - v = parseRawVector(value, position, maxPos); - if (v == null) - return null; - current = position[0]; - break; - } - case 'm' : - v = VersionVector.MAXS_VALUE; - ++current; - break; - case 'M' : - v = VersionVector.MAX_VALUE; - ++current; - break; - case '-' : - if (++current >= maxPos) - return null; - - c = value.charAt(current); - if (c == 'M') { - ++current; - v = VersionVector.MIN_VALUE; - break; - } - negate = true; - // Fall through to default - default : { - if (isDigit(c)) { - int start = current++; - while (current < maxPos && isDigit(value.charAt(current))) - ++current; - int val = Integer.parseInt(value.substring(start, current)); - if (negate) - val = -val; - v = Version.valueOf(val); - break; - } - return null; - } - } - position[0] = current; - return v; - } - - private static Comparable parseRawVector(String value, int[] position, int maxPos) { - int pos = position[0]; - if (pos >= maxPos) - return null; - - char c = value.charAt(pos); - if (c == '>') - return null; - - ArrayList rawList = new ArrayList(); - boolean padMarkerSeen = (c == 'p'); - if (padMarkerSeen) { - if (++pos >= maxPos) - return null; - position[0] = pos; - } - - Comparable pad = null; - for (;;) { - Comparable elem = parseRawElement(value, position, maxPos); - if (elem == null) - return null; - - if (padMarkerSeen) - pad = elem; - else - rawList.add(elem); - - pos = position[0]; - if (pos >= maxPos) - return null; - - c = value.charAt(pos); - position[0] = ++pos; - if (c == '>') - break; - - if (padMarkerSeen || pos >= maxPos) - return null; - - if (c == 'p') { - padMarkerSeen = true; - continue; - } - - if (c != '.') - return null; - } - removeRedundantTrail(rawList, pad); - return new VersionVector((Comparable[]) rawList.toArray(new Comparable[rawList.size()]), pad); - } - - static int skipWhite(String string, int pos) { - int top = string.length(); - while (pos < top && string.charAt(pos) <= ' ') - ++pos; - return pos; - } - - static int skipTrailingWhite(String string, int start, int end) { - while (end > start && string.charAt(end - 1) <= ' ') - --end; - return end; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionRange.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionRange.java deleted file mode 100644 index 16484abe6..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionRange.java +++ /dev/null @@ -1,500 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Cloudsmith Inc - rewrite to handle non-OSGi versions. - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -import org.eclipse.equinox.internal.p2.metadata.Messages; - -import java.io.Serializable; -import org.eclipse.osgi.util.NLS; - -/** - * This class represents a version range with Omni Version bounds. It is signature - * equivalent with the OSGi {@link org.eclipse.osgi.service.resolver.VersionRange VersionRange} - * - * @Immutable - * @noextend This class is not intended to be subclassed by clients. - */ -public class VersionRange implements Serializable { - private static final long serialVersionUID = 4988030307298088028L; - - static final Version OSGi_versionMin = new Version(0, 0, 0); - static final Version OSGi_versionMax = new Version(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); - - /** - * TODO: This should not be OSGi but it has to be that for now since the resolver creates - * a filter where the min and max are converted into strings. When the filter is evaluated an - * attempt is made to recreate them as OSGi versions. - * - * An empty OSGi Version range. - */ - public static final VersionRange emptyRange = new VersionRange(OSGi_versionMin, true, OSGi_versionMax, true); - - private final Version minVersion; - private final boolean includeMin; - private final Version maxVersion; - private final boolean includeMax; - - private static int copyEscaped(String vr, int pos, String breakChars, StringBuffer sb) { - int top = vr.length(); - pos = VersionParser.skipWhite(vr, pos); - if (pos >= top) - throw new IllegalArgumentException(); - - char c = vr.charAt(pos); - for (;;) { - if (c == '\\' && ++pos < top) - c = vr.charAt(pos); - else { - if (c <= ' ') - return VersionParser.skipWhite(vr, pos); - if (breakChars != null && breakChars.indexOf(c) >= 0) - break; - } - sb.append(c); - if (++pos >= top) - break; - c = vr.charAt(pos); - } - return pos; - } - - /** - * Constructs a VersionRange with the specified minVersion and maxVersion. - * @param minVersion the minimum version of the range - * @param maxVersion the maximum version of the range - */ - public VersionRange(Version minVersion, boolean includeMin, Version maxVersion, boolean includeMax) { - if (minVersion == null) { - if (maxVersion == null) { - // For backward compatibility with the OSGi version version range - minVersion = OSGi_versionMin; - maxVersion = OSGi_versionMax; - } else - minVersion = maxVersion.getFormat() == VersionFormat.OSGI_FORMAT ? OSGi_versionMin : Version.MIN_VERSION; - } else { - if (maxVersion == null) - maxVersion = minVersion.getFormat() == VersionFormat.OSGI_FORMAT ? OSGi_versionMax : Version.MAX_VERSION; - else { - if (minVersion != maxVersion && minVersion.equals(maxVersion)) - maxVersion = minVersion; - else if (!(minVersion.getFormat() == null ? maxVersion.getFormat() == null : minVersion.getFormat().equals(maxVersion.getFormat()))) { - // We always allow the MIN and MAX boundaries but if the other end is OSGi, then they too must be OSGi - if (minVersion.equals(Version.MIN_VERSION)) { - if (maxVersion.getFormat() == VersionFormat.OSGI_FORMAT) - minVersion = OSGi_versionMin; - } else if (maxVersion.equals(Version.MAX_VERSION)) { - if (minVersion.getFormat() == VersionFormat.OSGI_FORMAT) - maxVersion = OSGi_versionMax; - } else - throw new IllegalArgumentException(NLS.bind(Messages.range_boundaries_0_and_1_cannot_have_different_formats, minVersion, maxVersion)); - } - } - } - this.minVersion = minVersion; - this.includeMin = includeMin; - this.maxVersion = maxVersion; - this.includeMax = includeMax; - validateRange(); - } - - /** - * Constructs a VersionRange from the given versionRange String. - * @param versionRange a version range String that specifies a range of - * versions. - */ - public VersionRange(String versionRange) { - int top = 0; - int pos = 0; - if (versionRange != null) { - top = versionRange.length(); - pos = VersionParser.skipWhite(versionRange, 0); - top = VersionParser.skipTrailingWhite(versionRange, pos, top); - } - - if (pos >= top) { - minVersion = OSGi_versionMin; - includeMin = true; - maxVersion = OSGi_versionMax; - includeMax = true; - return; - } - - char c = versionRange.charAt(pos); - int[] position = new int[1]; - boolean rawPrefix = false; - VersionFormat fmt = null; - if (VersionParser.isLetter(c)) { - if (versionRange.startsWith("raw:", pos)) { //$NON-NLS-1$ - rawPrefix = true; - pos += 4; - } else { - position[0] = pos; - fmt = parseFormat(versionRange, position); - pos = position[0]; - if (pos >= versionRange.length()) - throw new IllegalArgumentException(NLS.bind(Messages.format_must_be_delimited_by_colon_0, versionRange)); - - c = versionRange.charAt(pos); - if (c != ':') - throw new IllegalArgumentException(NLS.bind(Messages.format_must_be_delimited_by_colon_0, versionRange)); - ++pos; - } - pos = VersionParser.skipWhite(versionRange, pos); - if (pos >= top) - throw new IllegalArgumentException(NLS.bind(Messages.premature_EOS_0, versionRange)); - c = versionRange.charAt(pos); - } else - fmt = VersionFormat.OSGI_FORMAT; - - String minStr; - String maxStr; - StringBuffer sb = new StringBuffer(); - if (c == '[' || c == '(') { - includeMin = (c == '['); - pos = copyEscaped(versionRange, ++pos, ",)]", sb); //$NON-NLS-1$ - if (pos >= top) - throw new IllegalArgumentException(NLS.bind(Messages.premature_EOS_0, versionRange)); - c = versionRange.charAt(pos++); - if (c != ',') - throw new IllegalArgumentException(NLS.bind(Messages.missing_comma_in_range_0, versionRange)); - - minStr = sb.toString(); - sb.setLength(0); - pos = copyEscaped(versionRange, pos, ")]", sb); //$NON-NLS-1$ - if (pos >= top) - throw new IllegalArgumentException(); - maxStr = sb.toString(); - - c = versionRange.charAt(pos++); - includeMax = (c == ']'); - } else { - StringBuffer sbMin = new StringBuffer(); - pos = copyEscaped(versionRange, pos, rawPrefix ? "/" : null, sbMin); //$NON-NLS-1$ - includeMin = includeMax = true; - minStr = sbMin.toString(); - maxStr = null; - } - - if (rawPrefix) { - String origMin = null; - String origMax = null; - pos = VersionParser.skipWhite(versionRange, pos); - if (pos < top && versionRange.charAt(pos) == '/') { - if (++pos == top) - throw new IllegalArgumentException(NLS.bind(Messages.original_stated_but_missing_0, versionRange)); - position[0] = pos; - fmt = parseFormat(versionRange, position); - pos = VersionParser.skipWhite(versionRange, position[0]); - if (pos < top) { - boolean origUseIncDelims = false; - c = versionRange.charAt(pos); - if (c != ':') - throw new IllegalArgumentException(NLS.bind(Messages.original_must_start_with_colon_0, versionRange)); - - pos = VersionParser.skipWhite(versionRange, ++pos); - if (pos == top) - throw new IllegalArgumentException(NLS.bind(Messages.original_stated_but_missing_0, versionRange)); - - c = versionRange.charAt(pos); - if (c == '[' || c == '(') { - if (includeMin != (c == '[') || maxStr == null) - throw new IllegalArgumentException(NLS.bind(Messages.raw_and_original_must_use_same_range_inclusion_0, versionRange)); - pos = VersionParser.skipWhite(versionRange, ++pos); - origUseIncDelims = true; - } - - sb.setLength(0); - if (maxStr == null) { - copyEscaped(versionRange, pos, ",])", sb); //$NON-NLS-1$ - origMin = sb.toString(); - } else { - pos = copyEscaped(versionRange, pos, ",])", sb); //$NON-NLS-1$ - if (pos >= top) - throw new IllegalArgumentException(NLS.bind(Messages.premature_EOS_0, versionRange)); - c = versionRange.charAt(pos++); - if (c != ',') - throw new IllegalArgumentException(NLS.bind(Messages.missing_comma_in_range_0, versionRange)); - origMin = sb.toString(); - - sb.setLength(0); - pos = copyEscaped(versionRange, pos, "])", sb); //$NON-NLS-1$ - if (origUseIncDelims) { - if (pos >= top) - throw new IllegalArgumentException(NLS.bind(Messages.premature_EOS_0, versionRange)); - c = versionRange.charAt(pos++); - if (includeMax != (c == ']')) - throw new IllegalArgumentException(NLS.bind(Messages.raw_and_original_must_use_same_range_inclusion_0, versionRange)); - } - origMax = sb.toString(); - } - } - } - Version minV = VersionFormat.parseRaw(minStr, fmt, origMin); - - // We might have parsed the Version.MIN_VERSION. If so, replace it. The format is incorrect. - // - boolean isOSGi = (fmt == VersionFormat.OSGI_FORMAT); - boolean isMinMin = (minV.getVector().length == 0 && minV.getPad() == null); - minVersion = isMinMin ? (isOSGi ? OSGi_versionMin : Version.MIN_VERSION) : minV; - - if (maxStr != null) { - if (maxStr.equals(minStr)) - maxVersion = minV; - else { - Version maxV = VersionFormat.parseRaw(maxStr, fmt, origMax); - Comparable[] maxVector = maxV.getVector(); - - // We might have parsed the Version.MAX_VERSION. If so, replace it. The format is incorrect. - // - boolean isMaxMax = (maxVector.length == 0 && maxV.getPad() == VersionVector.MAX_VALUE); - maxVersion = isMaxMax ? (isOSGi ? OSGi_versionMax : Version.MAX_VERSION) : maxV; - } - } else - maxVersion = (fmt == VersionFormat.OSGI_FORMAT ? OSGi_versionMax : Version.MAX_VERSION); - } else { - if (fmt == null) - fmt = VersionFormat.OSGI_FORMAT; - minVersion = fmt.parse(minStr); - if (maxStr != null) { - if (maxStr.equals(minStr)) - maxVersion = minVersion; - else - maxVersion = fmt.parse(maxStr); - } else { - maxVersion = (fmt == VersionFormat.OSGI_FORMAT) ? OSGi_versionMax : Version.MAX_VERSION; - } - } - validateRange(); - } - - private static VersionFormat parseFormat(String versionRange, int[] position) { - int pos = VersionParser.skipWhite(versionRange, position[0]); - if (!versionRange.startsWith("format(", pos)) //$NON-NLS-1$ - return null; - - pos += 7; - int end = VersionParser.findEndOfFormat(versionRange, pos, versionRange.length()); - try { - position[0] = end + 1; - return VersionFormat.compile(versionRange, pos, end); - } catch (FormatException e) { - throw new IllegalArgumentException(e.getMessage()); - } - } - - /** - * Returns the version format. - */ - public VersionFormat getFormat() { - return minVersion.equals(Version.MIN_VERSION) ? maxVersion.getFormat() : minVersion.getFormat(); - } - - /** - * Returns the minimum Version of this VersionRange - * @return the minimum Version of this VersionRange - */ - public Version getMinimum() { - return minVersion; - } - - /** - * Indicates if the minimum version is included in the version range. - * @return true if the minimum version is included in the version range; - * otherwise false is returned - */ - public boolean getIncludeMinimum() { - return includeMin; - } - - /** - * Returns the maximum Version of this VersionRange - * @return the maximum Version of this VersionRange - */ - public Version getMaximum() { - return maxVersion; - } - - /** - * Indicates if the maximum version is included in the version range. - * @return true if the maximum version is included in the version range; - * otherwise false is returned - */ - public boolean getIncludeMaximum() { - return includeMax; - } - - public VersionRange intersect(VersionRange r2) { - int minCompare = minVersion.compareTo(r2.getMinimum()); - int maxCompare = maxVersion.compareTo(r2.getMaximum()); - - boolean resultMinIncluded; - Version resultMin; - if (minCompare == 0) { - if (maxCompare == 0 && includeMin == r2.getIncludeMinimum() && includeMax == r2.getIncludeMaximum()) - return this; - resultMin = minVersion; - resultMinIncluded = includeMin && r2.getIncludeMinimum(); - } else if (minCompare < 0) { - resultMin = r2.getMinimum(); - resultMinIncluded = r2.getIncludeMinimum(); - } else { // minCompare > 0) - resultMin = minVersion; - resultMinIncluded = includeMin; - } - - boolean resultMaxIncluded; - Version resultMax; - if (maxCompare > 0) { - resultMax = r2.getMaximum(); - resultMaxIncluded = r2.getIncludeMaximum(); - } else if (maxCompare < 0) { - resultMax = maxVersion; - resultMaxIncluded = includeMax; - } else {//maxCompare == 0 - resultMax = maxVersion; - resultMaxIncluded = includeMax && r2.getIncludeMaximum(); - } - - int minMaxCmp = resultMin.compareTo(resultMax); - if (minMaxCmp < 0 || (minMaxCmp == 0 && resultMinIncluded && resultMaxIncluded)) - return new VersionRange(resultMin, resultMinIncluded, resultMax, resultMaxIncluded); - - return null; - } - - /** - * Returns whether the given version is included in this VersionRange. - * This will depend on the minimum and maximum versions of this VersionRange - * and the given version. - * - * @param version a version to be tested for inclusion in this VersionRange. - * (may be null) - * @return true if the version is include, - * false otherwise - */ - public boolean isIncluded(Version version) { - if (version == null) - return false; - - if (minVersion == maxVersion) - // Can only happen when both includeMin and includeMax are true - return minVersion.equals(version); - - int minCheck = includeMin ? 0 : -1; - int maxCheck = includeMax ? 0 : 1; - return minVersion.compareTo(version) <= minCheck && maxVersion.compareTo(version) >= maxCheck; - } - - /** - * Checks if the versions of this range is in compliance with the OSGi version spec. - * @return A flag indicating whether the range is OSGi compatible or not. - */ - public boolean isOSGiCompatible() { - return minVersion.isOSGiCompatible() && maxVersion.isOSGiCompatible(); - } - - public boolean equals(Object object) { - if (!(object instanceof VersionRange)) - return false; - VersionRange vr = (VersionRange) object; - return includeMin == vr.includeMin && includeMax == vr.includeMax && minVersion.equals(vr.getMinimum()) && maxVersion.equals(vr.getMaximum()); - } - - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + maxVersion.hashCode(); - result = prime * result + minVersion.hashCode(); - result = prime * result + (includeMax ? 1231 : 1237); - result = prime * result + (includeMin ? 1231 : 1237); - return result; - } - - public String toString() { - StringBuffer result = new StringBuffer(); - toString(result); - return result.toString(); - } - - public void toString(StringBuffer result) { - VersionFormat fmt = getFormat(); - if (fmt == VersionFormat.OSGI_FORMAT) { - if (includeMin && includeMax && OSGi_versionMax.equals(maxVersion)) { - minVersion.toString(result); - } else { - result.append(includeMin ? '[' : '('); - minVersion.toString(result); - result.append(','); - maxVersion.toString(result); - result.append(includeMax ? ']' : ')'); - } - return; - } - - boolean gtEqual = includeMin && includeMax && Version.MAX_VERSION.equals(maxVersion); - result.append("raw:"); //$NON-NLS-1$ - if (gtEqual) { - minVersion.rawToString(result, true); - } else { - result.append(includeMin ? '[' : '('); - minVersion.rawToString(result, true); - result.append(','); - maxVersion.rawToString(result, true); - result.append(includeMax ? ']' : ')'); - } - boolean hasOriginal = (minVersion.getOriginal() != null || maxVersion.getOriginal() != null); - if (fmt != null || hasOriginal) { - result.append('/'); - if (fmt != null) - fmt.toString(result); - if (hasOriginal) { - result.append(':'); - if (gtEqual) { - minVersion.originalToString(result, true); - } else { - if (Version.MIN_VERSION.equals(minVersion)) - minVersion.rawToString(result, true); - else - minVersion.originalToString(result, true); - result.append(','); - maxVersion.originalToString(result, true); - } - } - } - } - - // Preserve singletons during deserialization - private Object readResolve() { - VersionRange vr = this; - if (equals(emptyRange)) - vr = emptyRange; - return vr; - } - - private void validateRange() { - int cmp = minVersion.compareTo(maxVersion); - if (!(cmp < 0 || (cmp == 0 && includeMin && includeMax))) - throw new IllegalArgumentException(NLS.bind(Messages.range_min_0_is_not_less_then_range_max_1, minVersion, maxVersion)); - } - - public static org.eclipse.osgi.service.resolver.VersionRange toOSGiVersionRange(VersionRange range) { - if (range.equals(emptyRange)) - return org.eclipse.osgi.service.resolver.VersionRange.emptyRange; - return new org.eclipse.osgi.service.resolver.VersionRange(Version.toOSGiVersion(range.getMinimum()), range.getIncludeMinimum(), Version.toOSGiVersion(range.getMaximum()), range.getIncludeMinimum()); - } - - public static VersionRange fromOSGiVersionRange(org.eclipse.osgi.service.resolver.VersionRange range) { - if (range.equals(org.eclipse.osgi.service.resolver.VersionRange.emptyRange)) - return emptyRange; - return new VersionRange(Version.fromOSGiVersion(range.getMinimum()), range.getIncludeMinimum(), Version.fromOSGiVersion(range.getMaximum()), range.getIncludeMaximum()); - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionVector.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionVector.java deleted file mode 100644 index 3d70be612..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionVector.java +++ /dev/null @@ -1,367 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Cloudsmith Inc. and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Cloudsmith Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -import java.io.Serializable; - -/** - * The VersionVector represents an array of Comparable objects. The array can be - * nested since a VersionVector is Comparable in itself. - * - * @Immutable - */ -public class VersionVector implements Comparable, Serializable { - - private static final class MaxStringValue implements Comparable, Serializable { - private static final long serialVersionUID = -4936252230441132767L; - - MaxStringValue() { - // Empty constructor - } - - public int compareTo(Object o) { - return o == this ? 0 : (o == MAX_VALUE || o instanceof Integer || o instanceof VersionVector ? -1 : 1); - } - - // For singleton deserialization - private Object readResolve() { - return MAXS_VALUE; - } - - public String toString() { - return "m"; //$NON-NLS-1$ - } - } - - private static final class MaxValue implements Comparable, Serializable { - private static final long serialVersionUID = -5889641741635253589L; - - MaxValue() { - // Empty constructor - } - - public int compareTo(Object o) { - return o == this ? 0 : 1; - } - - public String toString() { - return "M"; //$NON-NLS-1$ - } - - // For singleton deserialization - private Object readResolve() { - return MAX_VALUE; - } - } - - private static class MinValue implements Comparable, Serializable { - private static final long serialVersionUID = -1066323980049812226L; - - MinValue() { - // Empty constructor - } - - public int compareTo(Object o) { - return o == this ? 0 : -1; - } - - public String toString() { - return "-M"; //$NON-NLS-1$ - } - - private Object readResolve() { - return MIN_VALUE; - } - } - - /** - * A value that is greater then any other value - */ - public static final Comparable MAX_VALUE = new MaxValue(); - - /** - * A value that is greater then any string but less then {@link #MAX_VALUE} and - * any Integer or VersionVector. - */ - public static final Comparable MAXS_VALUE = new MaxStringValue(); - - /** - * A value that is less then any other value - */ - public static final Comparable MIN_VALUE = new MinValue(); - - private static final long serialVersionUID = -8385373304298723744L; - - static void rawToString(StringBuffer sb, boolean forRange, Comparable e) { - if (e instanceof String) { - writeQuotedString(sb, forRange, (String) e, '\'', 0, false); - } else if (e instanceof VersionVector) { - sb.append('<'); - ((VersionVector) e).toString(sb, forRange); - sb.append('>'); - } else - sb.append(e); - } - - /** - * Write a string within quotes. If the string is found to contain the quote, an attempt is made - * to flip quote character (single quote becomes double quote and vice versa). A string that contains - * both will be written as several adjacent quoted strings so that each string is quoted with a - * quote character that it does not contain. - * @param sb The buffer that will receive the string - * @param rangeSafe Set to true if the resulting string will be used in a range string - * and hence need to escape the range delimiter characters - * @param s The string to be written - * @param quote The quote character to start with. Must be the single or double quote character. - * @param startPos The start position - * @param didFlip True if the call is recursive and thus, cannot switch quotes in the first string. - */ - static void writeQuotedString(StringBuffer sb, boolean rangeSafe, String s, char quote, int startPos, boolean didFlip) { - int quotePos = sb.length(); - sb.append(quote); - boolean otherSeen = false; - int top = s.length(); - for (int idx = startPos; idx < top; ++idx) { - char c = s.charAt(idx); - if (c == '\'' || c == '"') { - if (c == quote) { - char otherQuote = quote == '\'' ? '"' : '\''; - if (didFlip || otherSeen) { - // We can only flip once - sb.append(quote); - writeQuotedString(sb, rangeSafe, s, otherQuote, idx, true); - return; - } - quote = otherQuote; - sb.setCharAt(quotePos, quote); - didFlip = true; - } else - otherSeen = true; - } - if (rangeSafe && (c == '\\' || c == '[' || c == '(' || c == ']' || c == ')' || c == ',' || c <= ' ')) - sb.append('\\'); - sb.append(c); - } - sb.append(quote); - } - - private static int compareSegments(Comparable a, Comparable b) { - if (a == b) - return 0; - - if (a instanceof Integer && b instanceof Integer) { - int ai = ((Integer) a).intValue(); - int bi = ((Integer) b).intValue(); - return ai > bi ? 1 : (ai < bi ? -1 : 0); - } - - if (a instanceof String && b instanceof String) - return a.compareTo(b); - - if (a == MAX_VALUE || a == MIN_VALUE || a == MAXS_VALUE) - return a.compareTo(b); - - if (b == MAX_VALUE || b == MIN_VALUE || b == MAXS_VALUE) - return -b.compareTo(a); - - if (a instanceof Integer) - return 1; - if (b instanceof Integer) - return -1; - if (a instanceof VersionVector) - return (b instanceof VersionVector) ? a.compareTo(b) : 1; - - if (b instanceof VersionVector) - return -1; - - throw new IllegalArgumentException(); - } - - private Comparable padValue; - - private Comparable[] vector; - - VersionVector() { - // Constructor used in conjunction with init (when version is parsed from string) - } - - VersionVector(Comparable[] vector, Comparable pad) { - this.vector = vector; - this.padValue = (pad == MIN_VALUE) ? null : pad; - } - - public int compareTo(Object o) { - if (o == this) - return 0; - - VersionVector ov = (VersionVector) o; - Comparable[] t_vector = vector; - Comparable[] o_vector = ov.vector; - int top = t_vector.length; - if (top > o_vector.length) - top = o_vector.length; - - for (int idx = 0; idx < top; ++idx) { - int cmp = compareSegments(t_vector[idx], o_vector[idx]); - if (cmp != 0) - return cmp; - } - - // All elements compared equal up to this point. Check - // pad values - if (top < t_vector.length) - return (ov.padValue == null) ? 1 : compareReminder(top, ov.padValue); - - if (top < o_vector.length) - return (padValue == null) ? -1 : -ov.compareReminder(top, padValue); - - // Lengths are equal. Compare pad values - return padValue == null ? (ov.padValue == null ? 0 : -1) : (ov.padValue == null ? 1 : compareSegments(padValue, ov.padValue)); - } - - public boolean equals(Object o) { - if (o == this) - return true; - - if (!(o instanceof VersionVector)) - return false; - - VersionVector ov = (VersionVector) o; - - // We compare pad first since it is impossible for versions with - // different pad to be equal (versions are padded to infinity) - if (padValue == null) { - if (ov.padValue != null) - return false; - } else { - if (ov.padValue == null || !padValue.equals(ov.padValue)) - return false; - } - - Comparable[] t_vector = vector; - Comparable[] o_vector = ov.vector; - int idx = t_vector.length; - - // If the length of the vector differs, the versions cannot be equal - // since segments equal to pad are stripped by the parser - if (idx != o_vector.length) - return false; - - while (--idx >= 0) - if (!t_vector[idx].equals(o_vector[idx])) - return false; - - return true; - } - - /** - * Returns the pad value used when comparing this versions to - * versions that has a raw vector with a larger number of elements - * @return The pad value or null if not set. - */ - public Comparable getPad() { - return padValue; - } - - /** - * An element from the raw vector - * @param index The zero based index of the desired element - * @return An element from the raw vector - */ - public Comparable getSegment(int index) { - return vector[index]; - } - - /** - * Returns the number of elements in the raw vector - * @return The element count - */ - public int getSegmentCount() { - return vector.length; - } - - public int hashCode() { - int hashCode = padValue == null ? 31 : padValue.hashCode(); - int idx = vector.length; - while (--idx >= 0) { - Object elem = vector[idx]; - if (elem != null) - hashCode += elem.hashCode(); - hashCode = hashCode * 31; - } - return hashCode; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - toString(sb); - return sb.toString(); - } - - /** - * Append the string representation of this instance to the - * sb buffer. - * @param sb The buffer to append to - */ - public void toString(StringBuffer sb) { - toString(sb, false); - } - - /** - * Append the string representation of this instance to the - * sb buffer. - * @param sb The buffer to append to - * @param rangeSafe If true, the range delimiters will be escaped - * with backslash. - */ - public void toString(StringBuffer sb, boolean rangeSafe) { - int top = vector.length; - if (top == 0) - // Write one pad value as explicit. It will be considered - // redundant and removed by the parser but the raw format - // does not allow zero elements - rawToString(sb, rangeSafe, padValue == null ? MIN_VALUE : padValue); - else { - for (int idx = 0; idx < top; ++idx) { - if (idx > 0) - sb.append('.'); - rawToString(sb, rangeSafe, vector[idx]); - } - } - if (padValue != null) { - sb.append('p'); - rawToString(sb, rangeSafe, padValue); - } - } - - /** - * This method is package protected since it violates the immutable - * contract. - * @return The raw vector. Must be treated as read-only - */ - Comparable[] getVector() { - return vector; - } - - void init(Comparable[] vec, Comparable pad) { - vector = vec; - padValue = (pad == MIN_VALUE) ? null : pad; - } - - private int compareReminder(int idx, Comparable othersPad) { - int cmp; - for (cmp = 0; idx < vector.length && cmp == 0; ++idx) - cmp = compareSegments(vector[idx], othersPad); - if (cmp == 0) - cmp = (padValue == null) ? -1 : padValue.compareTo(othersPad); - return cmp; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionedId.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionedId.java deleted file mode 100644 index 3b97f48a1..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/VersionedId.java +++ /dev/null @@ -1,101 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 Code 9 and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Code 9 - initial API and implementation - * EclipseSource - ongoing development - * Thomas Hallgren - Fix for bug 268659 - * IBM - ongoing development - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata; - -import org.eclipse.equinox.internal.p2.core.helpers.StringHelper; - -/** - * An object representing a (id,version) pair. - * - * @noextend This class is not intended to be subclassed by clients. - */ -public class VersionedId implements IVersionedId { - private final String id; - private final Version version; - - /** - * Creates and returns a new {@link VersionedId} from the given string specification. - * The specification must be of the form "id/version", or just "id" if the version is absent - *

    - * This factory method can be used to reconstruct a {@link VersionedId} - * instance from the string representation produced by a previous invocation of - * {@link #toString()}. - * - * @param spec the specification for the versioned id to create - * @return the parsed versioned id - * @throws IllegalArgumentException If spec is improperly - * formatted. - */ - public static IVersionedId parse(String spec) { - String[] segments = StringHelper.getArrayFromString(spec, '/'); - return new VersionedId(segments[0], segments.length == 1 ? null : segments[1]); - } - - /** - * Creates a new versioned id with the given id and version. - * - * @param id The identifier - * @param version The version - * @throws IllegalArgumentException If version is improperly - * formatted. - */ - public VersionedId(String id, String version) { - this.id = id; - this.version = Version.parseVersion(version); - } - - /** - * Creates a new versioned id with the given id and version. - * - * @param id The identifier - * @param version The version - */ - public VersionedId(String id, Version version) { - this.id = id; - this.version = (version == null) ? Version.emptyVersion : version; - } - - public boolean equals(Object obj) { - if (this == obj) - return true; - - if (!(obj instanceof VersionedId)) - return false; - - VersionedId vname = (VersionedId) obj; - return id.equals(vname.id) && version.equals(vname.version); - } - - public int hashCode() { - return id.hashCode() * 31 + version.hashCode(); - } - - public String getId() { - return id; - } - - public Version getVersion() { - return version; - } - - /** - * Returns a string representation of this versioned id. - * The result can be used to later construct an equal {@link VersionedId} - * instance using {{@link #parse(String)}. - * @return A string representation of this versioned id - */ - public String toString() { - return Version.emptyVersion.equals(version) ? id : id + '/' + version.toString(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CapabilityQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CapabilityQuery.java deleted file mode 100644 index 4336989a9..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CapabilityQuery.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; - -/** - * A query that searches for {@link IInstallableUnit} instances that provide - * capabilities that match one or more required capabilities. - */ -public class CapabilityQuery extends MatchQuery { - private IRequiredCapability[] required; - - /** - * Creates a new query on the given required capability. - * @param required The required capability - */ - public CapabilityQuery(IRequiredCapability required) { - this.required = new IRequiredCapability[] {required}; - } - - /** - * Creates a new query on the given required capabilities. The installable - * unit must provide capabilities that match all of the given required capabilities - * for this query to be satisfied. - * @param required The required capabilities - */ - public CapabilityQuery(IRequiredCapability[] required) { - this.required = required; - } - - /** - * Returns the required capability that this query is matching against. - * @return the required capability that this query is matching against. - */ - public IRequiredCapability[] getRequiredCapabilities() { - return required; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.p2.query2.Query#isMatch(java.lang.Object) - */ - public boolean isMatch(Object object) { - if (!(object instanceof IInstallableUnit)) - return false; - IInstallableUnit candidate = (IInstallableUnit) object; - for (int i = 0; i < required.length; i++) - if (!candidate.satisfies(required[i])) - return false; - return true; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/Collector.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/Collector.java deleted file mode 100644 index 024280495..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/Collector.java +++ /dev/null @@ -1,137 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * EclipseSource - ongoing development - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - -import org.eclipse.equinox.internal.p2.metadata.Messages; - -import java.lang.reflect.Array; -import java.util.*; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; - -/** - * A collector is a generic visitor that collects objects passed to it, - * and can then express the result of the visit in various forms. The collector - * can also short-circuit a traversal by returning false from - * its {@link #accept(Object)} method. - *

    - * This default collector just accepts all objects passed to it. Clients may subclass - * to perform different processing on the objects passed to it. - */ -public class Collector implements IQueryable { - private Set collected = null; - - /** - * Creates a new collector. - */ - public Collector() { - super(); - } - - /** - * Accepts an object. - *

    - * This default implementation adds the objects to a list. Clients may - * override this method to perform additional filtering, add different objects - * to the list, short-circuit the traversal, or process the objects directly without - * collecting them. - * - * @param object the object to collect or visit - * @return true if the traversal should continue, - * or false to indicate the traversal should stop. - */ - public boolean accept(Object object) { - getCollection().add(object); - return true; - } - - /** - * Returns the collection that is being used to collect results. Unlike {@linkplain #toCollection()}, - * this returns the actual modifiable collection that is being used to store results. The - * return value is only intended to be used within subclasses and should not be exposed - * outside of a collection class. - * - * @return the collection being used to collect results. - */ - protected Collection getCollection() { - if (collected == null) - collected = new HashSet(); - return collected; - } - - /** - * Returns whether this collector is empty. - * @return true if this collector has accepted any results, - * and false otherwise. - */ - public boolean isEmpty() { - return collected == null || collected.isEmpty(); - } - - /** - * Returns an iterator on the collected objects. - * - * @return an iterator of the collected objects. - */ - public Iterator iterator() { - return collected == null ? Collections.EMPTY_LIST.iterator() : collected.iterator(); - } - - /** - * Returns the number of collected objects. - */ - public int size() { - return collected == null ? 0 : collected.size(); - } - - /** - * Returns the collected objects as an array - * - * @param clazz The type of array to return - * @return The array of results - * @throws ArrayStoreException the runtime type of the specified array is - * not a supertype of the runtime type of every collected object - */ - public Object[] toArray(Class clazz) { - int size = collected == null ? 0 : collected.size(); - Object[] result = (Object[]) Array.newInstance(clazz, size); - if (size != 0) - collected.toArray(result); - return result; - } - - /** - * Returns the collected objects as an immutable collection. - * - * @return An unmodifiable collection of the collected objects - */ - public Collection toCollection() { - return collected == null ? Collections.EMPTY_SET : Collections.unmodifiableSet(collected); - } - - /** - * Performs a query on this results of this collector. - */ - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - Iterator iter = collector == this ? toCollection().iterator() : iterator(); - if (monitor == null) - monitor = new NullProgressMonitor(); - try { - monitor.beginTask(Messages.performing_subquery, 1); - collector = query.perform(iter, collector); - monitor.worked(1); - } finally { - monitor.done(); - } - return collector; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CompositeQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CompositeQuery.java deleted file mode 100644 index a4c88a629..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CompositeQuery.java +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - - -import java.util.Iterator; - -/** - * A Composite Query is an aggregate query in which each sub-query - * is executed in succession. The results from the ith sub-query - * are piped as input into the i+1th sub-query. - */ -public class CompositeQuery implements Query { - protected Query[] queries; - - public CompositeQuery(Query[] queries) { - this.queries = queries; - } - - /** - * Gets the ID for this Query. - */ - public String getId() { - return QueryHelpers.getId(this); - } - - /** - * Gets a particular property of the query. - * @param property The property to retrieve - */ - public Object getProperty(String property) { - return QueryHelpers.getProperty(this, property); - } - - /** - * Set the queries of this composite. This is needed to allow subclasses of - * CompsiteQuery to set the queries in a constructor - */ - protected final void setQueries(Query[] queries) { - this.queries = queries; - } - - public Collector perform(Iterator iterator, Collector result) { - Collector collector; - Iterator iter = iterator; - for (int i = 0; i < queries.length; i++) { - // Take the results of the previous query and using them - // to drive the next one (i.e. composing queries) - collector = queries[i].perform(iter, new Collector()); - iter = collector.iterator(); - } - boolean gatherResults = true; - while (iter.hasNext() && gatherResults) - gatherResults = result.accept(iter.next()); - return result; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CompoundQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CompoundQuery.java deleted file mode 100644 index 45cc8b66d..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CompoundQuery.java +++ /dev/null @@ -1,218 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * EclipseSource - ongoing development - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - - -import java.util.*; - -/** - * A query that combines a group of sub-queries.

    - * - * In a CompoundQuery each sub-query is executed and the results are combined using - * either logical AND or logical OR operations.

    - * - * Clients are expected to call {@link CompoundQuery#createCompoundQuery(Query[], boolean)} - * to create a concrete instance of a CompoundQuery. If all Queries are instances of - * {@link IMatchQuery} then the resulting compound query will be a MatchCompoundQuery, otherwise the - * resulting compound query will be a {@link ContextQuery}. - * - * @noextend This class is not intended to be subclassed by clients. - */ -public abstract class CompoundQuery implements Query { - protected Query[] queries; - protected boolean and; - - /** - * Creates a compound query that combines the given queries. The queries - * will be performed by the compound query in the given order. This method - * might not perform all queries if it can determine the result of the compound - * expression without doing so. - * - * If all the queries are instances of {@link IMatchQuery} then the resulting - * compound query will be an instance of IMatchQuery, otherwise the resulting - * compound query will be a context query. - * - * @param queries The queries to perform - * @param and true if this query represents a logical 'and', and - * false if this query represents a logical 'or'. - */ - public static CompoundQuery createCompoundQuery(Query[] queries, boolean and) { - if (isMatchQueries(queries)) { - return new CompoundQuery.MatchCompoundQuery(queries, and); - } - return new CompoundQuery.ContextCompoundQuery(queries, and); - } - - /** - * Returns the queries that make up this compound query - */ - public Query[] getQueries() { - return queries; - } - - /** - * Returns whether this compound query combines its queries with a logical - * 'and' or 'or'. - * @return true if this query represents a logical 'and', and - * false if this query represents a logical 'or'. - */ - public boolean isAnd() { - return and; - } - - protected CompoundQuery(Query[] queries, boolean and) { - this.queries = queries; - this.and = and; - } - - /** - * @param queries - */ - private static boolean isMatchQueries(Query[] queries) { - for (int i = 0; i < queries.length; i++) { - if (!(queries[i] instanceof IMatchQuery)) { - return false; - } - } - return true; - } - - /** - * Gets the ID for this Query. - */ - public String getId() { - return QueryHelpers.getId(this); - } - - /** - * Gets a particular property of the query. - * @param property The property to retrieve - */ - public Object getProperty(String property) { - return QueryHelpers.getProperty(this, property); - } - - /** - * The compound query instantiated when all queries are Match Queries. - */ - private static class MatchCompoundQuery extends CompoundQuery implements IMatchQuery { - - protected MatchCompoundQuery(Query[] queries, boolean and) { - super(queries, and); - } - - public boolean isMatch(Object candidate) { - for (int i = 0; i < queries.length; i++) { - boolean valid = ((IMatchQuery) queries[i]).isMatch(candidate); - // if we are OR'ing then the first time we find a requirement that is met, return success - if (valid && !and) - return true; - // if we are AND'ing then the first time we find a requirement that is NOT met, return failure - if (!valid && and) - return false; - } - // if we get past the requirements check and we are AND'ing then return true - // since all requirements must have been met. If we are OR'ing then return false - // since none of the requirements were met. - return and; - } - - /** - * Performs this query on the given iterator, passing all objects in the iterator - * that match the criteria of this query to the given result. - */ - public final Collector perform(Iterator iterator, Collector result) { - prePerform(); - try { - while (iterator.hasNext()) { - Object candidate = iterator.next(); - if (isMatch(candidate)) - if (!result.accept(candidate)) - break; - } - } finally { - postPerform(); - } - return result; - } - - public void prePerform() { - for (int i = 0; i < queries.length; i++) { - ((IMatchQuery) queries[i]).prePerform(); - } - } - - public void postPerform() { - for (int i = 0; i < queries.length; i++) { - ((IMatchQuery) queries[i]).postPerform(); - } - } - } - - /** - * The compound query instantiated when any of the queries are not - * match queries. - */ - private static class ContextCompoundQuery extends CompoundQuery { - - protected ContextCompoundQuery(Query[] queries, boolean and) { - super(queries, and); - } - - /* - * A collector that takes the set to puts the elements in. - */ - class SetCollector extends Collector { - Set s = null; - - public SetCollector(Set s) { - this.s = s; - } - - public boolean accept(Object object) { - s.add(object); - return true; - } - } - - public Collector perform(Iterator iterator, Collector result) { - if (queries.length < 1) - return result; - - Collection data = new LinkedList(); - - while (iterator.hasNext()) { - data.add(iterator.next()); - } - - Set[] resultSets = new Set[queries.length]; - for (int i = 0; i < queries.length; i++) { - resultSets[i] = new HashSet(); - queries[i].perform(data.iterator(), new SetCollector(resultSets[i])); - } - - Set set = resultSets[0]; - for (int i = 1; i < resultSets.length; i++) { - if (isAnd()) - set.retainAll(resultSets[i]); - else - set.addAll(resultSets[i]); - } - - Iterator resultIterator = set.iterator(); - boolean gatherResults = true; - while (resultIterator.hasNext() && gatherResults) - gatherResults = result.accept(resultIterator.next()); - return result; - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CompoundQueryable.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CompoundQueryable.java deleted file mode 100644 index ff7484c73..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/CompoundQueryable.java +++ /dev/null @@ -1,122 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - -import java.lang.reflect.Array; -import java.util.*; -import org.eclipse.core.runtime.*; - -/** - * A queryable that holds a number of other IQueryables and provides - * a mechanism for querying the entire set. - */ -public class CompoundQueryable implements IQueryable { - - private IQueryable[] queryables; - - public CompoundQueryable(IQueryable[] queryables) { - this.queryables = queryables; - } - - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - if (monitor == null) { - monitor = new NullProgressMonitor(); - } - boolean isMatchQuery = query instanceof IMatchQuery; - Collector results = collector; - int totalWork = isMatchQuery ? queryables.length : queryables.length + 1; - - try { - SubMonitor subMonitor = SubMonitor.convert(monitor, totalWork * 10); - if (!isMatchQuery) { - // If it is not a match query, then collect the results - // as a list, we will query this list for the final results - results = new ListCollector(); - } - for (int i = 0; i < queryables.length; i++) { - if (subMonitor.isCanceled()) - break; - results = queryables[i].query(query, results, subMonitor.newChild(10)); - } - - if (!isMatchQuery) { - // If it is not a MatchQuery then we must query the results. - collector = results.query(query, collector, subMonitor.newChild(10)); - } else - collector = results; - } finally { - monitor.done(); - } - - return collector; - } - - /** - * A list collector. - * - * This is a collector backed as a list. - * - * The list collector is not intended to be used outside of this class. It is only public - * for testing purposes. - * - * @noinstantiate This class is not intended to be instantiated by clients. - * @noextend This class is not intended to be subclassed by clients. - * - */ - public class ListCollector extends Collector { - private List collected; - - public ListCollector() { - super(); - } - - protected Collection getCollection() { - if (collected == null) - collected = new ArrayList(); - return collected; - } - - public boolean isEmpty() { - return collected == null || collected.isEmpty(); - } - - public Object[] toArray(Class clazz) { - int size = collected == null ? 0 : collected.size(); - Object[] result = (Object[]) Array.newInstance(clazz, size); - if (size != 0) - collected.toArray(result); - return result; - } - - public boolean accept(Object object) { - if (collected == null) - collected = new ArrayList(); - collected.add(object); - return true; - } - - /** - * Returns the collected objects as an immutable collection. - * - * @return An unmodifiable collection of the collected objects - */ - public Collection toCollection() { - return collected == null ? Collections.EMPTY_LIST : Collections.unmodifiableList(collected); - } - - public Iterator iterator() { - return collected == null ? Collections.EMPTY_LIST.iterator() : collected.iterator(); - } - - public int size() { - return collected == null ? 0 : collected.size(); - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/ContextQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/ContextQuery.java deleted file mode 100644 index 532f9e691..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/ContextQuery.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - - -import java.util.Iterator; - -/** - * ContextQuery is the abstract superclass for Queries that require the entire - * input to evaluate the results. Queries must consider the group of elements before - * processing the results.

    - * - * ContextQueries must also be transitive. That is, if run on a subset of the - * input, the order in which they are executed must not matter. If there is the - * need for a non-transitive query, please see: - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=261403 - *

    - * Users of this query must call {@link #perform(Iterator, Collector)} to compute - * the results.

    - * This class may be subclassed by clients. Subclasses should specify the type - * of object they support querying on. Subclasses are also encouraged to clearly - * specify their match algorithm, and expose the parameters involved in the match - * computation, to allow {@link IQueryable} implementations to optimize their - * execution of the query.

    - * - */ -public abstract class ContextQuery implements Query { - - /** - * Evaluates the query for a specific input. - * - * @param iterator The elements for which to evaluate the query on - * @param result A collector to collect the results. For each element accepted - * by the query,{@link Collector#accept(Object)} must be called. - * @return The results of the query. The collector returned must be - * the collector passed in. - */ - public abstract Collector perform(Iterator iterator, Collector result); - - /** - * Gets the ID for this Query. - */ - public String getId() { - return QueryHelpers.getId(this); - } - - /** - * Gets a particular property of the query. - * @param property The property to retrieve - */ - public Object getProperty(String property) { - return QueryHelpers.getProperty(this, property); - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/IMatchQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/IMatchQuery.java deleted file mode 100644 index 6a3830611..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/IMatchQuery.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - -/** - * A query in which the elements can be evaluated by calling isMatch on. Each - * element can be evaluated independently of all other elements. Match queries - * can be evaluated in parallel as each call {@link #isMatch(Object)} is mutually - * exclusive from all other calls.

    - * - * @spi Clients should not implement this interface, but rather extend {@link MatchQuery}. - */ -public interface IMatchQuery extends Query { - - /** - * Returns whether the given object satisfies the parameters of this query. - * - * @param candidate The object to perform the query against - * @return true if the unit satisfies the parameters - * of this query, and false otherwise - * - * @noreference This method is not intended to be referenced by clients. - */ - public boolean isMatch(Object candidate); - - /** - * Execute any pre-processing that must be done before this query is performed against - * a particular iterator. This method may be used by subclasses to do any calculations, - * caching, or other preparation for the query. - *

    - * This method is internal to the framework. Subclasses may override this method, but - * should not call this method. - * - * @noreference This method is not intended to be referenced by clients. - */ - public void prePerform(); - - /** - * Execute any post-processing that must be done after this query has been performed against - * a particular iterator. This method may be used by subclasses to clear caches or any other - * cleanup that should occur after a query. - *

    - * This method will be called even if the query does not complete successfully. - *

    - * This method is internal to the framework. Subclasses may override this method, but - * should not call this method. - * - * @noreference This method is not intended to be referenced by clients. - */ - public void postPerform(); -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/IQueryable.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/IQueryable.java deleted file mode 100644 index 3389d5182..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/IQueryable.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - - -import org.eclipse.core.runtime.IProgressMonitor; - -/** - * An IQueryable contains objects, and is able to perform queries on those objects. - *

    - * This interface may be implemented by clients. - */ -public interface IQueryable { - /** - * Performs a query, passing any objects that satisfy the - * query to the provided collector. - *

    - * This method is long-running; progress and cancellation are provided - * by the given progress monitor. - *

    - * - * @param query The query to perform - * @param collector Collects the results of the query - * @param monitor a progress monitor, or null if progress - * reporting is not desired - * @return The collector argument - */ - public Collector query(Query query, Collector collector, IProgressMonitor monitor); -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/IUPropertyQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/IUPropertyQuery.java deleted file mode 100644 index 9b43371dc..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/IUPropertyQuery.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; - -/** - * A query that searches for {@link IInstallableUnit} instances that have - * a property whose value matches the provided value. If no property name is - * specified, then all {@link IInstallableUnit} instances are accepted. - */ -public class IUPropertyQuery extends MatchQuery { - private String propertyName; - private String propertyValue; - - /** - * Creates a new query on the given property name and value. - */ - public IUPropertyQuery(String propertyName, String propertyValue) { - this.propertyName = propertyName; - this.propertyValue = propertyValue; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.p2.query2.Query#isMatch(java.lang.Object) - */ - public boolean isMatch(Object object) { - if (!(object instanceof IInstallableUnit)) - return false; - IInstallableUnit candidate = (IInstallableUnit) object; - if (propertyName == null) - return true; - String value = getProperty(candidate, propertyName); - if (value != null && (value.equals(propertyValue) || propertyValue == null)) - return true; - return false; - } - - protected String getProperty(IInstallableUnit iu, String name) { - return iu.getProperty(name); - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/InstallableUnitQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/InstallableUnitQuery.java deleted file mode 100644 index a0152a1e5..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/InstallableUnitQuery.java +++ /dev/null @@ -1,103 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - -import org.eclipse.equinox.internal.provisional.p2.metadata.*; - -/** - * A query that matches on the id and version of an {@link IInstallableUnit}. - */ -public class InstallableUnitQuery extends MatchQuery { - /** - * A convenience query that will match any {@link IInstallableUnit} - * it encounters. - */ - public static final InstallableUnitQuery ANY = new InstallableUnitQuery((String) null); - - private String id; - private final VersionRange range; - - /** - * Creates a query that will match any {@link IInstallableUnit} with the given - * id, regardless of version. - * - * @param id The installable unit id to match, or null to match any id - */ - public InstallableUnitQuery(String id) { - this.id = id; - this.range = null; - } - - /** - * Creates a query that will match any {@link IInstallableUnit} with the given - * id, and whose version falls in the provided range. - * - * @param id The installable unit id to match, or null to match any id - * @param range The version range to match - */ - public InstallableUnitQuery(String id, VersionRange range) { - this.id = id; - this.range = range; - } - - /** - * Creates a query that will match any {@link IInstallableUnit} with the given - * id and version. - * - * @param id The installable unit id to match, or null to match any id - * @param version The precise version that a matching unit must have - */ - public InstallableUnitQuery(String id, Version version) { - this.id = id; - this.range = (version == null || Version.emptyVersion.equals(version)) ? null : new VersionRange(version, true, version, true); - } - - /** - * Creates a query that will match any {@link IInstallableUnit} with the given - * id and version. - * - * @param versionedId The precise id/version combination that a matching unit must have - */ - public InstallableUnitQuery(IVersionedId versionedId) { - this(versionedId.getId(), versionedId.getVersion()); - } - - /** - * Returns the id that this query will match against. - * @return The installable unit it - */ - public String getId() { - return id; - } - - /** - * Returns the version range that this query will match against. - * @return The installable unit version range. - */ - public VersionRange getRange() { - return range; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.p2.query2.Query#isMatch(java.lang.Object) - */ - public boolean isMatch(Object object) { - if (!(object instanceof IInstallableUnit)) - return false; - IInstallableUnit candidate = (IInstallableUnit) object; - if (id != null && !id.equals(candidate.getId())) - return false; - if (range != null && !range.isIncluded(candidate.getVersion())) - return false; - return true; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/LatestIUVersionQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/LatestIUVersionQuery.java deleted file mode 100644 index 098642d64..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/LatestIUVersionQuery.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - -import java.util.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; - -/** - * This query returns the latest version for each unique IU Id. - * All other elements are discarded. - */ -public class LatestIUVersionQuery extends ContextQuery { - - /** - * Performs the LatestIUVersionQuery - */ - public Collector perform(Iterator iterator, Collector result) { - HashMap greatestIUVersion = new HashMap(); - while (iterator.hasNext()) { - Object next = iterator.next(); - - if (!(next instanceof IInstallableUnit)) - // Don't accept things if they are not IUs - continue; - IInstallableUnit iu = (IInstallableUnit) next; - if (greatestIUVersion.containsKey(iu.getId())) { - IInstallableUnit currentIU = (IInstallableUnit) greatestIUVersion.get(iu.getId()); - if (currentIU.getVersion().compareTo(iu.getVersion()) < 0) - greatestIUVersion.put(iu.getId(), iu); - } else - greatestIUVersion.put(iu.getId(), iu); - } - - Collection values = greatestIUVersion.values(); - Iterator valuesIterator = values.iterator(); - boolean continueGather = true; - - while (valuesIterator.hasNext() && continueGather) { - IInstallableUnit nextIU = (IInstallableUnit) valuesIterator.next(); - continueGather = result.accept(nextIU); - } - return result; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/MatchQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/MatchQuery.java deleted file mode 100644 index 86b647663..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/MatchQuery.java +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation -* IBM Corporation - ongoing development -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - - -import java.util.Iterator; - -/** - * This class represents the superclass of most of p2's queries. Every element - * in the query can be evaluated by calling isMatch on it. If {@link #isMatch(Object)} returns true, - * then the element WILL be included in the query result. If {@link #isMatch(Object)} returns false, then - * the element WILL NOT be included in the query result. - *

    - * This class may be subclassed by clients. Subclasses should specify the type - * of object they support querying on. Subclasses are also encouraged to clearly - * specify their match algorithm, and expose the parameters involved in the match - * computation, to allow {@link IQueryable} implementations to optimize their - * execution of the query. - */ -public abstract class MatchQuery implements IMatchQuery { - - /** - * Returns whether the given object satisfies the parameters of this query. - * - * @param candidate The object to perform the query against - * @return true if the unit satisfies the parameters - * of this query, and false otherwise - * - * @noreference This method is not intended to be referenced by clients. - * Clients should call {@link #perform(Iterator, Collector)} - */ - public abstract boolean isMatch(Object candidate); - - /** - * Gets the ID for this Query. - */ - public String getId() { - return QueryHelpers.getId(this); - } - - /** - * Gets a particular property of the query. - * @param property The property to retrieve - */ - public Object getProperty(String property) { - return QueryHelpers.getProperty(this, property); - } - - /** - * Performs this query on the given iterator, passing all objects in the iterator - * that match the criteria of this query to the given result. - */ - public final Collector perform(Iterator iterator, Collector result) { - prePerform(); - try { - while (iterator.hasNext()) { - Object candidate = iterator.next(); - if (isMatch(candidate)) - if (!result.accept(candidate)) - break; - } - } finally { - postPerform(); - } - return result; - } - - /** - * Execute any pre-processing that must be done before this query is performed against - * a particular iterator. This method may be used by subclasses to do any calculations, - * caching, or other preparation for the query. - *

    - * This method is internal to the framework. Subclasses may override this method, but - * should not call this method. - * - * @noreference This method is not intended to be referenced by clients. - */ - public void prePerform() { - // nothing to do by default - } - - /** - * Execute any post-processing that must be done after this query has been performed against - * a particular iterator. This method may be used by subclasses to clear caches or any other - * cleanup that should occur after a query. - *

    - * This method will be called even if the query does not complete successfully. - *

    - * This method is internal to the framework. Subclasses may override this method, but - * should not call this method. - * - * @noreference This method is not intended to be referenced by clients. - */ - public void postPerform() { - // nothing to do by default - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/Query.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/Query.java deleted file mode 100644 index a9acfdfa2..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/Query.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * EclipseSource - ongoing development - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - - -import java.util.Iterator; - -/** - * The superclass of all queries that can be performed on an {@link IQueryable}. - *

    - * - * NOTE: This interface does not follow the proper naming convention. It should - * be IQuery, however, for historic reasons it is Query. This is likely to change. - * - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface Query { - - /** - * Evaluates the query for a specific input. - * - * @param iterator The elements for which to evaluate the query on - * @param result A collector to collect the results. For each element accepted - * by the query,{@link Collector#accept(Object)} must be called. - * @return The results of the query. The collector returned must be - * the collector passed in. - */ - public abstract Collector perform(Iterator iterator, Collector result); - - /** - * Gets the ID for this Query. - */ - public String getId(); - - /** - * Gets a particular property of the query. - * @param property The property to retrieve - */ - public Object getProperty(String property); -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/QueryHelpers.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/QueryHelpers.java deleted file mode 100644 index 0d0a54d82..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/QueryHelpers.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * Static helper methods for the Query API. - */ -public class QueryHelpers { - /** - * Gets the ID for a Query. - */ - public static String getId(Query query) { - return query.getClass().getName(); - } - - /** - * Gets a particular property of a query. - * @param query The query to retrieve the property from - * @param property The property to retrieve - */ - public static Object getProperty(Query query, String property) { - Class clazz = query.getClass(); - Object result = null; - try { - Method method = clazz.getMethod("get" + property, new Class[0]); //$NON-NLS-1$ - result = method.invoke(query, new Object[0]); - } catch (SecurityException e) { - return null; - } catch (NoSuchMethodException e) { - return null; - } catch (IllegalArgumentException e) { - return null; - } catch (IllegalAccessException e) { - return null; - } catch (InvocationTargetException e) { - return null; - } - return result; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/UpdateQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/UpdateQuery.java deleted file mode 100644 index 6774bcbfb..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/internal/provisional/p2/metadata/query/UpdateQuery.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.query; - -import org.eclipse.equinox.internal.provisional.p2.metadata.*; - -public class UpdateQuery extends MatchQuery { - private IInstallableUnit updateFrom; - - public UpdateQuery(IInstallableUnit updateFrom) { - this.updateFrom = updateFrom; - } - - public boolean isMatch(Object obj) { - if (!(obj instanceof IInstallableUnit)) - return false; - if (obj instanceof IInstallableUnitPatch) { - IInstallableUnitPatch potentialPatch = (IInstallableUnitPatch) obj; - IRequiredCapability lifeCycle = potentialPatch.getLifeCycle(); - if (lifeCycle == null) - return false; - return updateFrom.satisfies(lifeCycle); - } - IInstallableUnit candidate = (IInstallableUnit) obj; - IUpdateDescriptor descriptor = candidate.getUpdateDescriptor(); - if (descriptor != null && descriptor.isUpdateOf(updateFrom) && updateFrom.getVersion().compareTo(candidate.getVersion()) < 0) - return true; - return false; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IArtifactKey.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IArtifactKey.java new file mode 100644 index 000000000..fdcba7a80 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IArtifactKey.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + + +/** + * Provide standardised artifact information to uniquely identify the + * corresponding bytes (perhaps not stored as a file). + *

    + * Artifact keys represent both a unique opaque identifier as well as structured + * and standardised pieces of information. + * + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface IArtifactKey extends IVersionedId { + + /** + * Returns the classifier for this artifact key. The returned value can be empty. + * @return the classifier segment of the key. + */ + public String getClassifier(); + + /** + * Returns the id for this artifact key. + * @return the id segment of the key. + */ + public String getId(); + + /** + * Returns the version for this artifact key. + * @return the version segment of the key. + */ + public Version getVersion(); + + /** + * Returns the canonical string form of this artifact key. + * @return the canonical string representing this key + */ + public String toExternalForm(); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ICopyright.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ICopyright.java new file mode 100644 index 000000000..d8ad2bd43 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ICopyright.java @@ -0,0 +1,39 @@ +/******************************************************************************* +* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + +import java.net.URI; + +/** + * The ICopyright interface represents a software copyright. A copyright has + * required body text which may be the full text or a summary. An optional location field can be specified + * which links to full text. + * + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface ICopyright { + + /** + * Returns the location of a document containing the copyright notice. + * + * @return The location of the copyright notice, or null + */ + public URI getLocation(); + + /** + * Returns the license body. + * + * @return the license body, never null + */ + public String getBody(); + +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IInstallableUnit.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IInstallableUnit.java new file mode 100644 index 000000000..fbc39cbb4 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IInstallableUnit.java @@ -0,0 +1,293 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 IBM Corporation and others. All rights reserved. This + * program and the accompanying materials are made available under the terms of + * the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Genuitec, LLC - added license support + * EclipseSource - ongoing development + ******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + +import java.util.*; +import org.osgi.framework.Filter; + +/** + * An installable unit represents an atomic, indivisible unit of installable functionality + * in a provisioned system. Everything that can be installed or uninstalled in a system, + * including both concrete artifacts and instructions describing steps to be performed + * during install, must be expressed as one or more installable units. Thus the set of + * installable units present in a system, together with the existing environment + * (operating system, etc), completely describes the initial installed state of that system. + *

    + * Installable units may have dependencies on functionality provided by other installable + * units, such that the unit cannot be installed unless some other installable unit + * is present in the installed system that provides a matching capability. Such + * dependencies are referred to as required capabilities. Conversely, + * installable units may declared provided capabilities, describing the + * capabilities that they make available to other units in the system. Note the + * weak coupling at work here: installable units never directly depend on each other, + * but instead depend on abstract capabilities that any other installable unit may provide. + *

    + * + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface IInstallableUnit extends IVersionedId, Comparable { + + /** + * A capability namespace representing a particular InstallableUnit by id. + * Each InstallableUnit automatically provides a capability in this namespace representing + * itself, and other InstallableUnits can require such a capability to state that they + * require a particular InstallableUnit to be present. + * + * @see IInstallableUnit#getId() + */ + public static final String NAMESPACE_IU_ID = "org.eclipse.equinox.p2.iu"; //$NON-NLS-1$ + + /** + * A property key (value "org.eclipse.equinox.p2.partial.iu") for a + * boolean property indicating the IU is generated from incomplete information and + * should be replaced by the complete IU if available. + * + * @see #getProperty(String) + */ + public static final String PROP_PARTIAL_IU = "org.eclipse.equinox.p2.partial.iu"; //$NON-NLS-1$ + + /** + * A property key (value "org.eclipse.equinox.p2.contact") for a + * String property containing a contact address where problems can be reported, + * such as an email address. + * + * @see #getProperty(String) + */ + public static final String PROP_CONTACT = "org.eclipse.equinox.p2.contact"; //$NON-NLS-1$ + /** + * A property key (value "org.eclipse.equinox.p2.description") for a + * String property containing a human-readable description of the installable unit. + * + * @see #getProperty(String) + */ + public static final String PROP_DESCRIPTION = "org.eclipse.equinox.p2.description"; //$NON-NLS-1$ + + /** + * A property key (value "org.eclipse.equinox.p2.description.url") for a + * String property containing a URL to the description of the installable unit. + * + * @see #getProperty(String) + */ + public static final String PROP_DESCRIPTION_URL = "org.eclipse.equinox.p2.description.url"; //$NON-NLS-1$ + /** + * A property key (value "org.eclipse.equinox.p2.doc.url") for a + * String property containing a URL for documentation about the installable unit. + * + * @see #getProperty(String) + */ + public static final String PROP_DOC_URL = "org.eclipse.equinox.p2.doc.url"; //$NON-NLS-1$ + + /** + * A property key (value "org.eclipse.equinox.p2.bundle.localization") for a String + * property containing the bundle localization property file name + */ + public static final String PROP_BUNDLE_LOCALIZATION = "org.eclipse.equinox.p2.bundle.localization"; //$NON-NLS-1$ + + /** + * A property key (value "org.eclipse.equinox.p2.name") for a + * String property containing a human-readable name for the installable unit. + * + * @see #getProperty(String) + */ + public static final String PROP_NAME = "org.eclipse.equinox.p2.name"; //$NON-NLS-1$ + /** + * A property key (value "org.eclipse.equinox.p2.provider") for a + * String property containing information about the vendor or provider of the + * installable unit. + * + * @see #getProperty(String) + */ + public static final String PROP_PROVIDER = "org.eclipse.equinox.p2.provider"; //$NON-NLS-1$ + + /** + * Returns the collection of artifacts associated with this installable unit. + * Installing this unit into a system will cause these artifacts to be fetched from + * a repository and applied to the installed system. Uninstalling this unit + * will cause these artifacts to be removed from the system. + * + * @return The artifacts associated with this installable unit + */ + public Collection getArtifacts(); + + /** + * Returns the filter on this installable unit. The filter is matched against + * the properties of the environment the unit is installed into. An installable + * unit will not be installed if it has a filter condition that is not satisfied by the + * properties of the environment. + * + * @return The installation filter for this unit, or null + */ + public Filter getFilter(); + + /** + * Returns the fragments that have been bound to this installable unit, or + * null if this unit is not resolved. + * + * @see #isResolved() + * @return The fragments bound to this installable unit, or null + */ + public List getFragments(); + + /** + * Returns an unmodifiable copy of the properties + * associated with the installable unit. + * + * @return an unmodifiable copy of the properties of this installable unit. + */ + public Map getProperties(); + + /** + * Returns the untranslated property of this installable unit associated with the given key. + * Returns null if no such property is defined. + *

    + * If the property value has been externalized, this method will return a string containing + * the translation key rather than a human-readable string. For this reason, clients + * wishing to obtain the value for a property that is typically translated should use + * {@link #getProperty(String, String)} instead. + *

    + * + * @param key The property key to retrieve a property value for + * @return the property that applies to this installable unit or null + */ + public String getProperty(String key); + + /** + * Returns the property of this installable unit associated with the given key. + * Returns null if no such property is defined or no applicable + * translation is available. + * + * @param key The property key to retrieve a property value for + * @param locale The locale to translate the property for, or null to use the current locale. + * @return the property that applies to this installable unit or null + */ + public String getProperty(String key, String locale); + + /** + * Returns the collection of capabilities provided by this installable unit. + * + * @return The collection of capabilities provided by this installable unit. + */ + public Collection getProvidedCapabilities(); + + public Collection getRequiredCapabilities(); + + public Collection getMetaRequiredCapabilities(); + + public List getTouchpointData(); + + public ITouchpointType getTouchpointType(); + + /** + * Returns whether this installable unit has been resolved. A resolved + * installable unit represents the union of an installable unit and some + * fragments. + * + * @see #getFragments() + * @see #unresolved() + * @return true if this installable unit is resolved, and + * false otherwise. + */ + public boolean isResolved(); + + /** + * Returns whether this installable unit is a singleton. Only one singleton + * installable unit with a given id is allowed to exist in a given installed system. + * Attempting to install multiple versions of a singleton will fail. + * @return true if this unit is a singleton, and false otherwise + */ + public boolean isSingleton(); + + /** + * Returns whether this unit has a provided capability that satisfies the given + * requirement. + * @return true if this unit satisfies the given requirement, and false otherwise. + */ + public boolean satisfies(IRequirement candidate); + + /** + * Returns the unresolved equivalent of this installable unit. If this unit is + * already unresolved, this method returns the receiver. Otherwise, this + * method returns an installable unit with the same id and version, but without + * any fragments attached. + * + * @see #getFragments() + * @see #isResolved() + * @return The unresolved equivalent of this unit + */ + public IInstallableUnit unresolved(); + + /** + * Returns information about what this installable unit is an update of. + * @return The lineage information about the installable unit + */ + public IUpdateDescriptor getUpdateDescriptor(); + + /** + * Returns the untranslated licenses that apply to this installable unit. + *

    + * If the license text has been externalized, this method will return strings containing + * the translation keys rather than human-readable strings. For this reason, clients + * wishing to obtain a license for display to an end user should use {@link #getLicenses(String)} + * instead. + *

    + * @return the licenses that apply to this installable unit + */ + public Collection getLicenses(); + + /** + * Returns the licenses that apply to this installable unit. Any translation of the + * licenses for the given locale will be applied. Returns an empty array if this + * unit has no licenses, or if the available licenses are externalized and do not + * have translations available for the given locale. + * + * @param locale The locale to translate the license for, or null to use the current locale. + * @return the translated licenses that apply to this installable unit + */ + public ILicense[] getLicenses(String locale); + + /** + * Returns the untranslated copyright that applies to this installable unit. + *

    + * If the copyright text has been externalized, this method will return strings containing + * the translation keys rather than human-readable strings. For this reason, clients + * wishing to obtain a copyright for display to an end user should use {@link #getCopyright(String)} + * instead. + *

    + * @return the copyright that applies to this installable unit or null + */ + public ICopyright getCopyright(); + + /** + * Returns the copyright that applies to this installable unit. Any translation of the + * copyright for the given locale will be applied. Returns null if this + * unit has no copyright, or if the copyright is externalized and no translations are + * available for the given locale. + * + * @param locale The locale to translate the copyright for, or null to use the current locale. + * @return the copyright that applies to this installable unit or null + */ + public ICopyright getCopyright(String locale); + + /** + * Returns whether this InstallableUnit is equal to the given object. + * + * This method returns true if: + *
      + *
    • Both this object and the given object are of type IInstallableUnit + *
    • The result of getId() on both objects are equal + *
    • The result of getVersion() on both objects are equal + *
    + */ + public boolean equals(Object obj); +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IInstallableUnitFragment.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IInstallableUnitFragment.java new file mode 100644 index 000000000..d9c93283d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IInstallableUnitFragment.java @@ -0,0 +1,20 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + +/** + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface IInstallableUnitFragment extends IInstallableUnit { + public IRequirement[] getHost(); +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IInstallableUnitPatch.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IInstallableUnitPatch.java new file mode 100644 index 000000000..600a9f325 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IInstallableUnitPatch.java @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + +import java.util.List; + +/** + * An installable unit patch is an installable unit that alters the required capabilities of another + * installable unit. + * + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface IInstallableUnitPatch extends IInstallableUnit { + /** + * The applicability scope of a patch describes the installable units that this + * patch should be applied to. Specifically, this patch will be applied to all installable + * units that satisfy all of the required capabilities in one or more of the given + * required capability arrays. + *

    + * The returned two-dimensional array can be considered + * as a boolean expression, where items in the inner array are connected by + * AND operators, and each of the arrays are separated by OR operators. For example + * a scope of [[r1, r2, r3], [r4, r5]] will match any unit whose provided capabilities + * satisfy the expression ((r1 ^ r2 ^ r3) | (r4 ^ r5)). + */ + IRequirement[][] getApplicabilityScope(); + + /** + * Returns the requirement changes imposed by the patch. + * @return The patch requirement changes. + */ + List getRequirementsChange(); + + /** + * Returns the required capability that defines the lifecycle of this patch. The + * patch will be installed into a profile if and only if the lifecycle capability + * is satisfied by some IU in the profile. If a future provisioning operation causes + * the requirement to no longer be satisfied, the patch will be uninstalled. + */ + IRequirement getLifeCycle(); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ILicense.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ILicense.java new file mode 100644 index 000000000..5d613ad9b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ILicense.java @@ -0,0 +1,58 @@ +/******************************************************************************* +* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation + * IBM - ongoing development +******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + +import java.net.URI; + +/** + * The ILicense interface represents a software license. A license has required body text + * which may be the full text or an annotation. An optional URL field can be specified + * which links to full text. Licenses can be easily compared using their digests. + * + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface ILicense { + + /** + * Returns the location of a document containing the full license. + * + * @return the location of the license document, or null + */ + public URI getLocation(); + + /** + * Returns the license body. + * @return the license body, never null + */ + public String getBody(); + + /** + * Returns the message digest of the license body. The digest is calculated on a normalized + * version of the license where all whitespace has been reduced to one space. + * + * @return the message digest as a BigInteger, never null + */ + public String getUUID(); + + /** + * Returns whether this license is equal to the given object. + * + * This method returns true if: + *

      + *
    • Both this object and the given object are of type ILicense + *
    • The result of getDigest() on both objects are equal + *
    + */ + public boolean equals(Object obj); + +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IProvidedCapability.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IProvidedCapability.java new file mode 100644 index 000000000..0496e8925 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IProvidedCapability.java @@ -0,0 +1,41 @@ +/******************************************************************************* +* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation + * IBM - ongoing development +******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + +/** + * Describes a capability as exposed or required by an installable unit + * + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface IProvidedCapability { + + public String getName(); + + public String getNamespace(); + + public Version getVersion(); + + /** + * Returns whether this provided capability is equal to the given object. + * + * This method returns true if: + *
      + *
    • Both this object and the given object are of type IProvidedCapability + *
    • The result of getName() on both objects are equal + *
    • The result of getNamespace() on both objects are equal + *
    • The result of getVersion() on both objects are equal + *
    + */ + public boolean equals(Object other); + +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IRequirement.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IRequirement.java new file mode 100644 index 000000000..cc866e2fa --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IRequirement.java @@ -0,0 +1,38 @@ +/******************************************************************************* +* Copyright (c) 2009 IBM and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* IBM - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + +import org.eclipse.equinox.p2.metadata.expression.IMatchExpression; +import org.osgi.framework.Filter; + +/** + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface IRequirement { + + int getMin(); + + int getMax(); + + Filter getFilter(); + + /** + * Returns a boolean match expression that will return true for any + * {@link IInstallableUnit} that matches the requirement. + * @return A boolean match expression for installable unit matching. + */ + IMatchExpression getMatches(); + + boolean isMatch(IInstallableUnit iu); + + boolean isGreedy(); +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IRequirementChange.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IRequirementChange.java new file mode 100644 index 000000000..16c21098b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IRequirementChange.java @@ -0,0 +1,38 @@ +/******************************************************************************* +* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; + +/** + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface IRequirementChange { + + public IRequiredCapability applyOn(); + + public IRequiredCapability newValue(); + + public boolean matches(IRequiredCapability toMatch); + + /** + * Returns whether this requirement change is equal to the given object. + * + * This method returns true if: + *
      + *
    • Both this object and the given object are of type IRequiredCapability + *
    • The result of applyOn() on both objects are equal + *
    • The result of newValue() on both objects are equal + *
    + */ + public boolean equals(Object other); +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ITouchpointData.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ITouchpointData.java new file mode 100644 index 000000000..3ab8b8c93 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ITouchpointData.java @@ -0,0 +1,52 @@ +/******************************************************************************* +* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + +import java.util.Map; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; + +/** + * ITouchpoint data instances contain the additional information needed by a touchpoint + * to execute each engine phase it participates in. This includes the sequence of + * instruction statements to be executed during each phase, and any additional + * supporting data needed to perform the phase. + * + * @see MetadataFactory#createTouchpointData(Map) + * + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface ITouchpointData { + + /** + * Returns the touchpoint instruction corresponding to the given key. + */ + public ITouchpointInstruction getInstruction(String instructionKey); + + /** + * Returns an unmodifiable map of the touchpoint instructions. The map + * keys are strings, and the values are instances of {@link ITouchpointInstruction}. + * + * @return the touchpoint instructions + */ + public Map getInstructions(); + + /** + * Returns whether this TouchpointData is equal to the given object. + * + * This method returns true if: + *
      + *
    • Both this object and the given object are of type ITouchpointData + *
    • The result of getInstructions() on both objects are equal + *
    + */ + public boolean equals(Object obj); +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ITouchpointInstruction.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ITouchpointInstruction.java new file mode 100644 index 000000000..e7c9b49b9 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ITouchpointInstruction.java @@ -0,0 +1,73 @@ +/******************************************************************************* +* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + +/** + * A touchpoint instruction contains either a sequence of instruction statements + * to be executed during a particular engine phase, or some simple string value + * that is needed by a touchpoint to execute its phases. + *

    + * The format of a touchpoint instruction statement sequence is as follows: + * + * statement-sequence : + * | statement ';' + * | statement-sequence statement + * ; + * + *Where a statement is of the format: + * + * statement : + * | actionName '(' parameters ')' + * ; + * + * parameters : + * | // empty + * | parameter + * | parameters ',' parameter + * ; + * + * parameter : + * | paramName ':' paramValue + * ; + * + * actionName, paramName, paramValue : + * | String + * ; + * + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface ITouchpointInstruction { + + /** + * Returns the body of this touchpoint instruction. The body is either a sequence + * of instruction statements, or a simple string value. + * + * @return The body of this touchpoint instruction + */ + public String getBody(); + + //TODO What is this? Please doc + public String getImportAttribute(); + + /** + * Returns whether this TouchpointInstruction is equal to the given object. + * + * This method returns true if: + *

      + *
    • Both this object and the given object are of type ITouchpointInstruction + *
    • The result of getBody() on both objects are equal + *
    • The result of getImportAttribute() on both objects are equal + *
    + */ + public boolean equals(Object obj); + +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ITouchpointType.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ITouchpointType.java new file mode 100644 index 000000000..02218f760 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/ITouchpointType.java @@ -0,0 +1,54 @@ +/******************************************************************************* +* Copyright (c) 2008, 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + + +/** + * Identifies a particular touchpoint. A touchpoint is identified by an id + * and a version. + * + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface ITouchpointType { + + /** + * A touchpoint type indicating an undefined touchpoint type. Identity (==) + * must be used to test for the NONE type. + */ + public static final ITouchpointType NONE = new ITouchpointType() { + + public String getId() { + return "null"; //$NON-NLS-1$ + } + + public Version getVersion() { + return Version.emptyVersion; + } + }; + + public String getId(); + + public Version getVersion(); + + /** + * Returns whether this TouchpointInstruction is equal to the given object. + * + * This method returns true if: + *
      + *
    • Both this object and the given object are of type ITouchpointType + *
    • The result of getId() on both objects are equal + *
    • The result of getVersion() on both objects are equal + *
    + */ + public boolean equals(Object obj); + +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IUpdateDescriptor.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IUpdateDescriptor.java new file mode 100644 index 000000000..047eb9f43 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IUpdateDescriptor.java @@ -0,0 +1,53 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + + +/** + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface IUpdateDescriptor { + public final int NORMAL = 0; + public final int HIGH = 1; + + /** + * The identifier of an installable unit that the installable unit containing this object is an update for. + * @return An installable unit id + */ + public String getId(); + + /** + * The range of the installable unit that the installable unit containing this object is an update for. + * @return A version range + */ + public VersionRange getRange(); + + /** + * The description of the update. This allows to explain what the update is about. + * @return A description + */ + public String getDescription(); + + /** + * The importance of the update descriptor represented as a int. + * @return The severity. + */ + public int getSeverity(); + + /** + * Helper method indicating whether or not an installable unit is an update for the installable unit passed + * @param iu the installable unit checked + * @return A boolean indicating whether or not an installable unit is an update. + */ + public boolean isUpdateOf(IInstallableUnit iu); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IVersionFormat.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IVersionFormat.java new file mode 100644 index 000000000..e87df3624 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IVersionFormat.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + +/** + *

    The IVersionFormat represents the Omni Version Format in compiled form. It + * is also a parser for versions of that format.

    + *

    An instance of IVersionFormat is immutable and thus thread safe. The parser + * does not maintain any state.

    + * @since 2.0 + */ +public interface IVersionFormat { + + /** + * The string that by default will be interpreted as the logical max string when parsing + * optional elements of type string and a default that is the empty string (i.e. OSGi) + */ + static final String DEFAULT_MAX_STRING_TRANSLATION = "zzz"; //$NON-NLS-1$ + + /** + * The string that by default will be interpreted as the logical min string when parsing + * optional elements of type string and a default that is the max string (i.e. Maven triplets) + */ + static final String DEFAULT_MIN_STRING_TRANSLATION = "-"; //$NON-NLS-1$ + + /** + * Appends the string representation of this compiled format to + * the given StringBuffer. + * @param sb The buffer that will receive the string representation + */ + void toString(StringBuffer sb); + + /** + * Parse the given version string. + * @param version The version string to parse. + * @return A created version. + * @throws IllegalArgumentException If the version string could not be parsed. + */ + Version parse(String version); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IVersionedId.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IVersionedId.java new file mode 100644 index 000000000..eb8aec341 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/IVersionedId.java @@ -0,0 +1,33 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + * IBM - Ongoing development + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + + +/** + * An interface representing a (id,version) pair. + * @since 2.0 + */ +public interface IVersionedId { + /** + * Returns the id portion of this versioned id. + * + * @return The id portion of this versioned id. + */ + String getId(); + + /** + * Returns the version portion of this versioned id. + * + * @return the version portion of this versioned id. + */ + Version getVersion(); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/Version.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/Version.java new file mode 100644 index 000000000..d92b63630 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/Version.java @@ -0,0 +1,229 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc - initial API and implementation. + *******************************************************************************/ + +package org.eclipse.equinox.p2.metadata; + +import java.io.Serializable; +import org.eclipse.equinox.internal.p2.metadata.*; + +/** + * A class that represents a Version in the Omni Version format. A Version can be though of as an + * array of comparable elements and an optional pad value. The pad value is used when comparing + * two versions with a different number of segments. + * + * The Omni Version can convert almost any version into a raw format that it uses for comparisons. + * This enables a unified order of all such versions and solves problems that arise when the + * version semantics are different. A good example is the OSGi version versus the version used in Maven. + * The lack of qualifier in the OSGi version implies that the qualifier is an empty string. So a version + * without a qualifier is the smallest of all other versions with the same major,minor,micro number. + * With Maven semantics, it's the opposite. If the qualifier is removed, the resulting version is + * considered higher then all other versions with the same major, minor, and micro number. The + * Omni version solves this by using different raw representations of the OSGi and Maven versions. + * + * The Omni version addresses a lot of other issues as well, such as reordering of the elements + * or treating some parts of a version as irrelevant when comparing. + * + * The class is signature compatible with {@link org.osgi.framework.Version} but attempts + * to use it as such might render a {@link UnsupportedOperationException} in case the + * raw vector holds incompatible values. The method {@link #isOSGiCompatible()} can be used + * to test. + * @since 2.0 + */ +public abstract class Version implements Comparable, Serializable { + public static final String RAW_PREFIX = "raw:"; //$NON-NLS-1$ + + /** + * The version that is semantically greater then all other versions. + */ + public static final Version MAX_VERSION = OmniVersion.createMaxVersion(); + + /** + * The version that is semantically less then all other versions. + */ + public static final Version emptyVersion = OmniVersion.createMinVersion(); + + private static final long serialVersionUID = 6218979149720923857L; + + /** + * Compile a version format string into a compiled format.. + * + * @param format The format to compile. + * @return The compiled format + * @throws VersionFormatException If the format could not be compiled + */ + public static IVersionFormat compile(String format) throws VersionFormatException { + return VersionFormat.compile(format, 0, format.length()); + } + + /** + * Parses a version identifier from the specified string. + * + * @param version String representation of the version identifier. Leading + * and trailing whitespace will be ignored. + * @return A Version object representing the version identifier + * or null if version is null or + * an empty string. + * @throws IllegalArgumentException If version is improperly + * formatted. + */ + public static Version create(String version) { + return version == null ? null : VersionParser.parse(version, 0, version.length()); + } + + /** + * Creates an OSGi version identifier from the specified numerical components. + * + *

    + * The qualifier is set to the empty string. + * + * @param major Major component of the version identifier. + * @param minor Minor component of the version identifier. + * @param micro Micro component of the version identifier. + * @throws IllegalArgumentException If the numerical components are + * negative. + */ + public static Version createOSGi(int major, int minor, int micro) { + return createOSGi(major, minor, micro, null); + } + + /** + * Creates an OSGi version identifier from the specified components. + * + * @param major Major component of the version identifier. + * @param minor Minor component of the version identifier. + * @param micro Micro component of the version identifier. + * @param qualifier Qualifier component of the version identifier. If + * null is specified, then the qualifier will be set to + * the empty string. + * @throws IllegalArgumentException If the numerical components are negative + * or the qualifier string is invalid. + */ + public static Version createOSGi(int major, int minor, int micro, String qualifier) { + Comparable logicQualifier; + if (qualifier == null || qualifier.length() == 0) { + if (major == 0 && minor == 0 && micro == 0) + return emptyVersion; + logicQualifier = VersionVector.MINS_VALUE; // So that we can do identity compare + } else if (qualifier.equals(IVersionFormat.DEFAULT_MAX_STRING_TRANSLATION)) + logicQualifier = VersionVector.MAXS_VALUE; + else + logicQualifier = qualifier; + return new OSGiVersion(major, minor, micro, logicQualifier); + } + + /** + * Create an omni version from an OSGi version. + * @param version The OSGi version. Can be null. + * @return The created omni version + */ + public static Version fromOSGiVersion(org.osgi.framework.Version version) { + if (version == null) + return null; + if (version.getMajor() == Integer.MAX_VALUE && version.getMicro() == Integer.MAX_VALUE && version.getMicro() == Integer.MAX_VALUE) + return MAX_VERSION; + return createOSGi(version.getMajor(), version.getMinor(), version.getMicro(), version.getQualifier()); + } + + /** + * Parses a version identifier from the specified string. This method is for backward + * compatibility with OSGi and will return the OSGi "0.0.0" version when + * the provided string is empty or null. + * + * @param version String representation of the version identifier. Leading + * and trailing whitespace will be ignored. + * @return A Version object representing the version + * identifier. If version is null or + * the empty string then the OSGi emptyVersion will be + * returned. + * @throws IllegalArgumentException If version is improperly + * formatted. + * @see #create(String) + */ + public static Version parseVersion(String version) { + if (version == null || version.length() == 0) + return Version.emptyVersion; + Version v = create(version); + return v == null ? Version.emptyVersion : v; + } + + /** + * Convert version into its OSGi equivalent if possible. + * + * @param version The version to convert. Can be null + * @return The converted version or null if the argument was null + * @throws UnsupportedOperationException if the version could not be converted into an OSGi version + */ + public static org.osgi.framework.Version toOSGiVersion(Version version) { + if (version == null) + return null; + if (version == emptyVersion) + return org.osgi.framework.Version.emptyVersion; + if (version == MAX_VERSION) + return new org.osgi.framework.Version(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); + + BasicVersion bv = (BasicVersion) version; + return new org.osgi.framework.Version(bv.getMajor(), bv.getMinor(), bv.getMicro(), bv.getQualifier()); + } + + /** + * Returns the optional format. + */ + public abstract IVersionFormat getFormat(); + + /** + * Returns the original part of the string for this version + * or null if no such part was provided when the version was + * created. An OSGi type version will always return the OSGi string representation. + * + * @return The original part of the version string or + * null if that part was missing. + */ + public abstract String getOriginal(); + + /** + * Returns the pad value used when comparing this versions to + * versions that has a larger number of segments + * @return The pad value or null if not set. + */ + public abstract Comparable getPad(); + + /** + * An element from the raw vector representation of this version. + * @param index The zero based index of the desired element + * @return An element from the raw vector + */ + public abstract Comparable getSegment(int index); + + /** + * Returns the number of elements in the raw vector representation of this version. + * @return The number of elements in the raw vector. + */ + public abstract int getSegmentCount(); + + /** + * Checks if this version is in compliance with the OSGi version spec. + * @return A flag indicating whether the version is OSGi compatible or not. + */ + public abstract boolean isOSGiCompatible(); + + public String toString() { + StringBuffer buf = new StringBuffer(20); + toString(buf); + return buf.toString(); + } + + /** + * Appends the string representation of this version onto the + * sb StringBuffer. + * @param sb The buffer that will receive the version string + */ + public abstract void toString(StringBuffer sb); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/VersionFormatException.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/VersionFormatException.java new file mode 100644 index 000000000..4aeb4c9e1 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/VersionFormatException.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + +/** + * Exception thrown when parsing Omni Version formats. + * @since 2.0 + */ +public class VersionFormatException extends Exception { + + private static final long serialVersionUID = -867104101610941043L; + + public VersionFormatException(String message) { + super(message); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/VersionRange.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/VersionRange.java new file mode 100644 index 000000000..6d93d42a7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/VersionRange.java @@ -0,0 +1,481 @@ +/******************************************************************************* + * Copyright (c) 2003, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Cloudsmith Inc - rewrite to handle non-OSGi versions. + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata; + +import java.io.Serializable; +import org.eclipse.equinox.internal.p2.metadata.*; +import org.eclipse.osgi.util.NLS; + +/** + * This class represents a version range with Omni Version bounds. It is signature + * equivalent with the OSGi {@link org.eclipse.osgi.service.resolver.VersionRange VersionRange} + * + * @Immutable + * @noextend This class is not intended to be subclassed by clients. + * @since 2.0 + */ +public class VersionRange implements Serializable { + private static final long serialVersionUID = 4988030307298088028L; + + /** + * TODO: This should not be OSGi but it has to be that for now since the resolver creates + * a filter where the min and max are converted into strings. When the filter is evaluated an + * attempt is made to recreate them as OSGi versions. + * + * An empty OSGi Version range. + */ + public static final VersionRange emptyRange = new VersionRange(Version.emptyVersion, true, Version.MAX_VERSION, true); + + private final Version minVersion; + private final boolean includeMin; + private final Version maxVersion; + private final boolean includeMax; + + private static int copyEscaped(String vr, int pos, String breakChars, StringBuffer sb) { + int top = vr.length(); + pos = VersionParser.skipWhite(vr, pos); + if (pos >= top) + throw new IllegalArgumentException(); + + char c = vr.charAt(pos); + for (;;) { + if (c == '\\' && ++pos < top) + c = vr.charAt(pos); + else { + if (c <= ' ') + return VersionParser.skipWhite(vr, pos); + if (breakChars != null && breakChars.indexOf(c) >= 0) + break; + } + sb.append(c); + if (++pos >= top) + break; + c = vr.charAt(pos); + } + return pos; + } + + /** + * Constructs a VersionRange with the specified minVersion and maxVersion. + * @param minVersion the minimum version of the range + * @param maxVersion the maximum version of the range + */ + public VersionRange(Version minVersion, boolean includeMin, Version maxVersion, boolean includeMax) { + if (minVersion == null) { + if (maxVersion == null) { + minVersion = Version.emptyVersion; + maxVersion = Version.MAX_VERSION; + } else + minVersion = Version.emptyVersion; + } else { + if (maxVersion == null) + maxVersion = Version.MAX_VERSION; + else { + if (minVersion != maxVersion && minVersion.equals(maxVersion)) + maxVersion = minVersion; + else if (!(minVersion.getFormat() == null ? maxVersion.getFormat() == null : minVersion.getFormat().equals(maxVersion.getFormat()))) { + // We always allow the MIN and MAX boundaries + if (!(minVersion.equals(Version.emptyVersion) || maxVersion.equals(Version.MAX_VERSION))) + throw new IllegalArgumentException(NLS.bind(Messages.range_boundaries_0_and_1_cannot_have_different_formats, minVersion, maxVersion)); + } + } + } + this.minVersion = minVersion; + this.includeMin = includeMin; + this.maxVersion = maxVersion; + this.includeMax = includeMax; + validateRange(); + } + + /** + * Constructs a VersionRange from the given versionRange String. + * @param versionRange a version range String that specifies a range of + * versions. + */ + public VersionRange(String versionRange) { + int top = 0; + int pos = 0; + if (versionRange != null) { + top = versionRange.length(); + pos = VersionParser.skipWhite(versionRange, 0); + top = VersionParser.skipTrailingWhite(versionRange, pos, top); + } + + if (pos >= top) { + minVersion = Version.emptyVersion; + includeMin = true; + maxVersion = Version.MAX_VERSION; + includeMax = true; + return; + } + + char c = versionRange.charAt(pos); + int[] position = new int[1]; + boolean rawPrefix = false; + IVersionFormat fmt = null; + if (VersionParser.isLetter(c)) { + if (versionRange.startsWith("raw:", pos)) { //$NON-NLS-1$ + rawPrefix = true; + pos += 4; + } else { + position[0] = pos; + fmt = parseFormat(versionRange, position); + pos = position[0]; + if (pos >= versionRange.length()) + throw new IllegalArgumentException(NLS.bind(Messages.format_must_be_delimited_by_colon_0, versionRange)); + + c = versionRange.charAt(pos); + if (c != ':') + throw new IllegalArgumentException(NLS.bind(Messages.format_must_be_delimited_by_colon_0, versionRange)); + ++pos; + } + pos = VersionParser.skipWhite(versionRange, pos); + if (pos >= top) + throw new IllegalArgumentException(NLS.bind(Messages.premature_EOS_0, versionRange)); + c = versionRange.charAt(pos); + } else + fmt = VersionFormat.OSGI_FORMAT; + + String minStr; + String maxStr; + StringBuffer sb = new StringBuffer(); + if (c == '[' || c == '(') { + includeMin = (c == '['); + pos = copyEscaped(versionRange, ++pos, ",)]", sb); //$NON-NLS-1$ + if (pos >= top) + throw new IllegalArgumentException(NLS.bind(Messages.premature_EOS_0, versionRange)); + c = versionRange.charAt(pos++); + if (c != ',') + throw new IllegalArgumentException(NLS.bind(Messages.missing_comma_in_range_0, versionRange)); + + minStr = sb.toString(); + sb.setLength(0); + pos = copyEscaped(versionRange, pos, ")]", sb); //$NON-NLS-1$ + if (pos >= top) + throw new IllegalArgumentException(); + maxStr = sb.toString(); + + c = versionRange.charAt(pos++); + includeMax = (c == ']'); + } else { + StringBuffer sbMin = new StringBuffer(); + pos = copyEscaped(versionRange, pos, rawPrefix ? "/" : null, sbMin); //$NON-NLS-1$ + includeMin = includeMax = true; + minStr = sbMin.toString(); + maxStr = null; + } + + if (rawPrefix) { + String origMin = null; + String origMax = null; + pos = VersionParser.skipWhite(versionRange, pos); + if (pos < top && versionRange.charAt(pos) == '/') { + if (++pos == top) + throw new IllegalArgumentException(NLS.bind(Messages.original_stated_but_missing_0, versionRange)); + position[0] = pos; + fmt = parseFormat(versionRange, position); + pos = VersionParser.skipWhite(versionRange, position[0]); + if (pos < top) { + boolean origUseIncDelims = false; + c = versionRange.charAt(pos); + if (c != ':') + throw new IllegalArgumentException(NLS.bind(Messages.original_must_start_with_colon_0, versionRange)); + + pos = VersionParser.skipWhite(versionRange, ++pos); + if (pos == top) + throw new IllegalArgumentException(NLS.bind(Messages.original_stated_but_missing_0, versionRange)); + + c = versionRange.charAt(pos); + if (c == '[' || c == '(') { + if (includeMin != (c == '[') || maxStr == null) + throw new IllegalArgumentException(NLS.bind(Messages.raw_and_original_must_use_same_range_inclusion_0, versionRange)); + pos = VersionParser.skipWhite(versionRange, ++pos); + origUseIncDelims = true; + } + + sb.setLength(0); + if (maxStr == null) { + copyEscaped(versionRange, pos, ",])", sb); //$NON-NLS-1$ + origMin = sb.toString(); + } else { + pos = copyEscaped(versionRange, pos, ",])", sb); //$NON-NLS-1$ + if (pos >= top) + throw new IllegalArgumentException(NLS.bind(Messages.premature_EOS_0, versionRange)); + c = versionRange.charAt(pos++); + if (c != ',') + throw new IllegalArgumentException(NLS.bind(Messages.missing_comma_in_range_0, versionRange)); + origMin = sb.toString(); + + sb.setLength(0); + pos = copyEscaped(versionRange, pos, "])", sb); //$NON-NLS-1$ + if (origUseIncDelims) { + if (pos >= top) + throw new IllegalArgumentException(NLS.bind(Messages.premature_EOS_0, versionRange)); + c = versionRange.charAt(pos++); + if (includeMax != (c == ']')) + throw new IllegalArgumentException(NLS.bind(Messages.raw_and_original_must_use_same_range_inclusion_0, versionRange)); + } + origMax = sb.toString(); + } + } + } + minVersion = VersionFormat.parseRaw(minStr, fmt, origMin); + if (maxStr != null) { + if (maxStr.equals(minStr)) + maxVersion = minVersion; + else + maxVersion = VersionFormat.parseRaw(maxStr, fmt, origMax); + } else + maxVersion = Version.MAX_VERSION; + } else { + if (fmt == null) + fmt = VersionFormat.OSGI_FORMAT; + minVersion = fmt.parse(minStr); + if (maxStr != null) { + if (maxStr.equals(minStr)) + maxVersion = minVersion; + else + maxVersion = fmt.parse(maxStr); + } else { + maxVersion = Version.MAX_VERSION; + } + } + validateRange(); + } + + private static IVersionFormat parseFormat(String versionRange, int[] position) { + int pos = VersionParser.skipWhite(versionRange, position[0]); + if (!versionRange.startsWith("format(", pos)) //$NON-NLS-1$ + return null; + + pos += 7; + int end = VersionParser.findEndOfFormat(versionRange, pos, versionRange.length()); + try { + position[0] = end + 1; + return VersionFormat.compile(versionRange, pos, end); + } catch (VersionFormatException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + /** + * Returns the version format. + */ + public IVersionFormat getFormat() { + return minVersion.equals(Version.emptyVersion) ? maxVersion.getFormat() : minVersion.getFormat(); + } + + /** + * Returns the minimum Version of this VersionRange + * @return the minimum Version of this VersionRange + */ + public Version getMinimum() { + return minVersion; + } + + /** + * Indicates if the minimum version is included in the version range. + * @return true if the minimum version is included in the version range; + * otherwise false is returned + */ + public boolean getIncludeMinimum() { + return includeMin; + } + + /** + * Returns the maximum Version of this VersionRange + * @return the maximum Version of this VersionRange + */ + public Version getMaximum() { + return maxVersion; + } + + /** + * Indicates if the maximum version is included in the version range. + * @return true if the maximum version is included in the version range; + * otherwise false is returned + */ + public boolean getIncludeMaximum() { + return includeMax; + } + + public VersionRange intersect(VersionRange r2) { + int minCompare = minVersion.compareTo(r2.getMinimum()); + int maxCompare = maxVersion.compareTo(r2.getMaximum()); + + boolean resultMinIncluded; + Version resultMin; + if (minCompare == 0) { + if (maxCompare == 0 && includeMin == r2.getIncludeMinimum() && includeMax == r2.getIncludeMaximum()) + return this; + resultMin = minVersion; + resultMinIncluded = includeMin && r2.getIncludeMinimum(); + } else if (minCompare < 0) { + resultMin = r2.getMinimum(); + resultMinIncluded = r2.getIncludeMinimum(); + } else { // minCompare > 0) + resultMin = minVersion; + resultMinIncluded = includeMin; + } + + boolean resultMaxIncluded; + Version resultMax; + if (maxCompare > 0) { + resultMax = r2.getMaximum(); + resultMaxIncluded = r2.getIncludeMaximum(); + } else if (maxCompare < 0) { + resultMax = maxVersion; + resultMaxIncluded = includeMax; + } else {//maxCompare == 0 + resultMax = maxVersion; + resultMaxIncluded = includeMax && r2.getIncludeMaximum(); + } + + int minMaxCmp = resultMin.compareTo(resultMax); + if (minMaxCmp < 0 || (minMaxCmp == 0 && resultMinIncluded && resultMaxIncluded)) + return new VersionRange(resultMin, resultMinIncluded, resultMax, resultMaxIncluded); + + return null; + } + + /** + * Returns whether the given version is included in this VersionRange. + * This will depend on the minimum and maximum versions of this VersionRange + * and the given version. + * + * @param version a version to be tested for inclusion in this VersionRange. + * (may be null) + * @return true if the version is include, + * false otherwise + */ + public boolean isIncluded(Version version) { + if (version == null) + return false; + + if (minVersion == maxVersion) + // Can only happen when both includeMin and includeMax are true + return minVersion.equals(version); + + int minCheck = includeMin ? 0 : -1; + int maxCheck = includeMax ? 0 : 1; + return minVersion.compareTo(version) <= minCheck && maxVersion.compareTo(version) >= maxCheck; + } + + /** + * Checks if the versions of this range is in compliance with the OSGi version spec. + * @return A flag indicating whether the range is OSGi compatible or not. + */ + public boolean isOSGiCompatible() { + return minVersion.isOSGiCompatible() && maxVersion.isOSGiCompatible(); + } + + public boolean equals(Object object) { + if (!(object instanceof VersionRange)) + return false; + VersionRange vr = (VersionRange) object; + return includeMin == vr.includeMin && includeMax == vr.includeMax && minVersion.equals(vr.getMinimum()) && maxVersion.equals(vr.getMaximum()); + } + + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + maxVersion.hashCode(); + result = prime * result + minVersion.hashCode(); + result = prime * result + (includeMax ? 1231 : 1237); + result = prime * result + (includeMin ? 1231 : 1237); + return result; + } + + public String toString() { + StringBuffer result = new StringBuffer(); + toString(result); + return result.toString(); + } + + public void toString(StringBuffer result) { + boolean gtEqual = includeMin && includeMax && Version.MAX_VERSION.equals(maxVersion); + if (gtEqual && Version.emptyVersion.equals(minVersion)) { + minVersion.toString(result); + return; + } + + IVersionFormat fmt = getFormat(); + if (fmt == VersionFormat.OSGI_FORMAT) { + if (gtEqual) { + minVersion.toString(result); + } else { + result.append(includeMin ? '[' : '('); + minVersion.toString(result); + result.append(','); + maxVersion.toString(result); + result.append(includeMax ? ']' : ')'); + } + return; + } + + result.append("raw:"); //$NON-NLS-1$ + if (gtEqual) { + ((BasicVersion) minVersion).rawToString(result, true); + } else { + result.append(includeMin ? '[' : '('); + ((BasicVersion) minVersion).rawToString(result, true); + result.append(','); + ((BasicVersion) maxVersion).rawToString(result, true); + result.append(includeMax ? ']' : ')'); + } + boolean hasOriginal = (minVersion.getOriginal() != null || maxVersion.getOriginal() != null); + if (fmt != null || hasOriginal) { + result.append('/'); + if (fmt != null) + fmt.toString(result); + if (hasOriginal) { + result.append(':'); + if (gtEqual) { + ((BasicVersion) minVersion).originalToString(result, true); + } else { + if (Version.emptyVersion.equals(minVersion)) + ((BasicVersion) minVersion).rawToString(result, true); + else + ((BasicVersion) minVersion).originalToString(result, true); + result.append(','); + ((BasicVersion) maxVersion).originalToString(result, true); + } + } + } + } + + // Preserve singletons during deserialization + private Object readResolve() { + VersionRange vr = this; + if (equals(emptyRange)) + vr = emptyRange; + return vr; + } + + private void validateRange() { + int cmp = minVersion.compareTo(maxVersion); + if (!(cmp < 0 || (cmp == 0 && includeMin && includeMax))) + throw new IllegalArgumentException(NLS.bind(Messages.range_min_0_is_not_less_then_range_max_1, minVersion, maxVersion)); + } + + public static org.eclipse.osgi.service.resolver.VersionRange toOSGiVersionRange(VersionRange range) { + if (range.equals(emptyRange)) + return org.eclipse.osgi.service.resolver.VersionRange.emptyRange; + return new org.eclipse.osgi.service.resolver.VersionRange(Version.toOSGiVersion(range.getMinimum()), range.getIncludeMinimum(), Version.toOSGiVersion(range.getMaximum()), range.getIncludeMinimum()); + } + + public static VersionRange fromOSGiVersionRange(org.eclipse.osgi.service.resolver.VersionRange range) { + if (range.equals(org.eclipse.osgi.service.resolver.VersionRange.emptyRange)) + return emptyRange; + return new VersionRange(Version.fromOSGiVersion(range.getMinimum()), range.getIncludeMinimum(), Version.fromOSGiVersion(range.getMaximum()), range.getIncludeMaximum()); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/ExpressionParseException.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/ExpressionParseException.java new file mode 100644 index 000000000..059f30482 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/ExpressionParseException.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright (c) 2009 - 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.expression; + +/** + * An exception used by an expression parser that indicates that something went wrong when + * parsing. + * @since 2.0 + */ +public class ExpressionParseException extends RuntimeException { + private static final long serialVersionUID = 8432875384760577764L; + + public ExpressionParseException(String message) { + super(message); + } + + public ExpressionParseException(String expression, String message, int position) { + super("Parse error in string \"" + expression + "\": " + message + " at position " + position); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/ExpressionUtil.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/ExpressionUtil.java new file mode 100644 index 000000000..02861aeed --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/ExpressionUtil.java @@ -0,0 +1,179 @@ +/******************************************************************************* + * Copyright (c) 2009 - 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.expression; + +import org.eclipse.equinox.internal.p2.metadata.expression.*; +import org.eclipse.equinox.internal.p2.metadata.expression.parser.ExpressionParser; +import org.eclipse.equinox.internal.p2.metadata.expression.parser.LDAPFilterParser; + +/** + * Global access to factory, parser, and methods for introspection + */ +public abstract class ExpressionUtil { + private static final LDAPFilterParser ldapFilterParser = new LDAPFilterParser(ExpressionFactory.INSTANCE); + private static final ExpressionParser expressionParser = new ExpressionParser(ExpressionFactory.INSTANCE); + + /** + * Returns the global expression factory + * @return The global expression factory. + */ + public static IExpressionFactory getFactory() { + return ExpressionFactory.INSTANCE; + } + + /** + * Creates and returns a new expression parser + * @return The new parser + */ + public static IExpressionParser newParser() { + return new ExpressionParser(getFactory()); + } + + /** + * Parse an LDAP filter from the filter string. If filter is null + * or a string that is empty or only consists of whitespace, then this method returns null. + * @param filter The filter to parse. Can be null or empty. + * @return An expression that corresponds to the LDAP filter or null. + * @throws ExpressionParseException If the syntax was invalid + */ + public static IFilterExpression parseLDAP(String filter) throws IllegalArgumentException { + filter = trimmedOrNull(filter); + return filter == null ? null : ldapFilterParser.parse(filter); + } + + /** + * Parse a boolean Expression from the expression string. If expression is null + * or a string that is empty or only consists of whitespace, then this method returns null. + * @param expression The expression to parse. Can be null or empty. + * @return An expression that corresponds to the LDAP filter or null. + * @throws ExpressionParseException If the syntax was invalid + */ + public static IExpression parse(String expression) { + expression = trimmedOrNull(expression); + return expression == null ? null : expressionParser.parse(expression); + } + + /** + * If str is null, then this method returns null. + * Otherwise str is trimmed from whitespace at both ends. If the result + * of the trim is an empty string, then null is returned, otherwise the + * result of the trim is returned. + * @param str The string to trim. Can be null. + * @return The trimmed string or null. + */ + public static String trimmedOrNull(String str) { + if (str != null) { + str = str.trim(); + if (str.length() == 0) + str = null; + } + return str; + } + + /** + * Obtains the Left Hand Side (LHS) of a binary expression. + * @param expression The expression to introspect + * @return The left hand side operator + * @throws IllegalArgumentException if the expression is not a binary expression + * @see IExpression#TYPE_AT + * @see IExpression#TYPE_EQUALS + * @see IExpression#TYPE_GREATER + * @see IExpression#TYPE_GREATER_EQUAL + * @see IExpression#TYPE_LESS + * @see IExpression#TYPE_LESS_EQUAL + * @see IExpression#TYPE_MATCHES + * @see IExpression#TYPE_NOT_EQUALS + */ + public static IExpression getLHS(IExpression expression) { + if (expression instanceof Binary) + return ((Binary) expression).lhs; + throw new IllegalArgumentException(); + } + + /** + * Obtains the name of a variable or member expression. + * @param expression The expression to introspect + * @return The name of the expression + * @throws IllegalArgumentException if the expression is not a variable or a member + * @see IExpression#TYPE_MEMBER + * @see IExpression#TYPE_VARIABLE + */ + public static String getName(IExpression expression) { + if (expression instanceof Member) + return ((Member) expression).getName(); + if (expression instanceof Variable) + return ((Variable) expression).getName(); + throw new IllegalArgumentException(); + } + + /** + * Obtains the operand of an unary expression + * @param expression The expression to introspect + * @return The expression operand + * @throws IllegalArgumentException if the expression is not an unary expression + * @see IExpression#TYPE_ALL + * @see IExpression#TYPE_EXISTS + * @see IExpression#TYPE_LAMBDA + * @see IExpression#TYPE_NOT + */ + public static IExpression getOperand(IExpression expression) { + if (expression instanceof Unary) + return ((Unary) expression).operand; + throw new IllegalArgumentException(); + } + + /** + * Obtains the operands of an n-ary expression + * @param expression The expression to introspect + * @return The expression operand + * @throws IllegalArgumentException if the expression is not a n-ary expression + * @see IExpression#TYPE_AND + * @see IExpression#TYPE_OR + */ + public static IExpression[] getOperands(IExpression expression) { + if (expression instanceof NAry) + return ((NAry) expression).operands; + throw new IllegalArgumentException(); + } + + /** + * Obtains the Right Hand Side (RHS) of a binary expression. + * @param expression The expression to introspect + * @return The right hand side operator + * @throws IllegalArgumentException if the expression is not a binary expression + * @see IExpression#TYPE_AT + * @see IExpression#TYPE_EQUALS + * @see IExpression#TYPE_GREATER + * @see IExpression#TYPE_GREATER_EQUAL + * @see IExpression#TYPE_LESS + * @see IExpression#TYPE_LESS_EQUAL + * @see IExpression#TYPE_MATCHES + * @see IExpression#TYPE_NOT_EQUALS + */ + public static IExpression getRHS(IExpression expression) { + if (expression instanceof Binary) + return ((Binary) expression).rhs; + throw new IllegalArgumentException(); + } + + /** + * Obtains the value of a literal expression + * @param expression The expression to introspect + * @return The literal value + * @throws IllegalArgumentException if the expression is not a literal + * @see IExpression#TYPE_LITERAL + */ + public static Object getValue(IExpression expression) { + if (expression instanceof Literal) + return ((Literal) expression).value; + throw new IllegalArgumentException(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IEvaluationContext.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IEvaluationContext.java new file mode 100644 index 000000000..4b049c054 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IEvaluationContext.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * Copyright (c) 2009 - 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.expression; + +/** + * The evaluation context. Contexts can be nested and new contexts are pushed for each closure + * during an evaluation of an expression. + * @since 2.0 + */ +public interface IEvaluationContext { + /** + * Retrieve the value of the given variable from this context + * @param variable The variable who's value should be retrieved + * @return The current value for the variable + */ + Object getValue(IExpression variable); + + /** + * Set the current value for the given variable to value + * @param variable The variable who's value should be set + * @param value The new value for the variable. + */ + void setValue(IExpression variable, Object value); + + /** + * Returns the value of the parameter at the given position + * @param position The zero based position for the parameter + * @return The parameter value + */ + Object getParameter(int position); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpression.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpression.java new file mode 100644 index 000000000..889675381 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpression.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2009 - 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.expression; + +/** + * A node in the expression tree + */ +public interface IExpression { + int TYPE_ALL = 1; + int TYPE_AND = 2; + int TYPE_AT = 3; + int TYPE_EQUALS = 4; + int TYPE_EXISTS = 5; + int TYPE_GREATER = 6; + int TYPE_GREATER_EQUAL = 7; + int TYPE_LAMBDA = 8; + int TYPE_LESS = 9; + int TYPE_LESS_EQUAL = 10; + int TYPE_LITERAL = 11; + int TYPE_MATCHES = 12; + int TYPE_MEMBER = 13; + int TYPE_NOT = 14; + int TYPE_NOT_EQUALS = 15; + int TYPE_OR = 16; + int TYPE_PARAMETER = 17; + int TYPE_VARIABLE = 18; + + /** + * Let the visitor visit this instance and all expressions that this + * instance contains. + * @param visitor The visiting visitor. + * @return true if the visitor should continue visiting, false otherwise. + */ + boolean accept(IExpressionVisitor visitor); + + /** + * Evaluate this expression with given context and variables. + * @param context The evaluation context + * @return The result of the evaluation. + */ + Object evaluate(IEvaluationContext context); + + /** + * Returns the expression type (see TYPE_xxx constants). + */ + int getExpressionType(); + + /** + * Appends the string representation of this expression to the collector collector. + */ + void toString(StringBuffer collector); + + /** + * Appends the an LDAP filter representation of this expression to the collector. + * @throws UnsupportedOperationException if the expression contains nodes + * that cannot be represented in an LDAP filter + */ + void toLDAPString(StringBuffer collector); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpressionFactory.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpressionFactory.java new file mode 100644 index 000000000..f76079a5d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpressionFactory.java @@ -0,0 +1,206 @@ +/******************************************************************************* + * Copyright (c) 2009 - 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.expression; + +import java.util.List; + +/** + * This inteface provides all the factory methods needed to create the + * nodes of the expression tree. + */ +public interface IExpressionFactory { + String FUNC_BOOLEAN = "boolean"; //$NON-NLS-1$ + String FUNC_VERSION = "version"; //$NON-NLS-1$ + String FUNC_CLASS = "class"; //$NON-NLS-1$ + String FUNC_RANGE = "range"; //$NON-NLS-1$ + String FUNC_FILTER = "filter"; //$NON-NLS-1$ + + IExpression[] NO_ARGS = new IExpression[0]; + + /** + * Create a collection filter that yields true if the lambda yields true for + * all of the elements of the collection + * @param collection The collection providing the elements to test + * @param lambda The lambda that performs the test + * @return A boolean expression + */ + IExpression all(IExpression collection, IExpression lambda); + + /** + * Create a logical and of its operands. + * @param operands The boolean operands + * @return A boolean expression + */ + IExpression and(IExpression... operands); + + /** + * Create an lookup of key in the target. + * The key expression should evaluate to a string or an integer. + * @param target The target for the lookup + * @param key The key to use for the lookup + * @return A lookup expression + */ + IExpression at(IExpression target, IExpression key); + + /** + * Create an evaluation context with one single variable + * @param params Indexed parameters to use in the expression + * @return the context + */ + IEvaluationContext createContext(Object... params); + + /** + * Create an evaluation context with one single variable + * @param params Indexed parameters to use in the expression + * @param variables The variables that will be maintained by the context + * @return the context + */ + IEvaluationContext createContext(IExpression[] variables, Object... params); + + /** + * Creates an expression that evaluates to the constant value. + * @param value The constant + * @return A constant expression + */ + IExpression constant(Object value); + + /** + * Create an expression that tests if lhs is equal to rhs. + * @param lhs The left hand side value. + * @param rhs The right hand side value. + * @return A boolean expression + */ + IExpression equals(IExpression lhs, IExpression rhs); + + /** + * Create a collection filter that yields true if the lambda yields true for + * at least one of the elements of the collection + * @param collection The collection providing the elements to test + * @param lambda The lambda that performs the test + * @return A boolean expression + */ + IExpression exists(IExpression collection, IExpression lambda); + + /** + * Creates a top level expression suitable for predicate matching + * @param expression The boolean expression + * @return A top level predicate expression + */ + IFilterExpression filterExpression(IExpression expression); + + /** + * Create an expression that tests if lhs is greater than rhs. + * @param lhs The left hand side value. + * @param rhs The right hand side value. + * @return A boolean expression + */ + IExpression greater(IExpression lhs, IExpression rhs); + + /** + * Create an expression that tests if lhs is greater than or equal to rhs. + * @param lhs The left hand side value. + * @param rhs The right hand side value. + * @return A boolean expression + */ + IExpression greaterEqual(IExpression lhs, IExpression rhs); + + /** + * Creates an indexed parameter expression + * @param index The index to use + * @return a parameter expression + */ + IExpression indexedParameter(int index); + + /** + * Creates a lambda expression that takes exactly one variable. Suitable for use + * in most collection expressions. + * @param variable The element variable that the lambda uses + * @param body The body of the lambda + * @return A lambda expression + */ + IExpression lambda(IExpression variable, IExpression body); + + /** + * Create an expression that tests if lhs is less than rhs. + * @param lhs The left hand side value. + * @param rhs The right hand side value. + * @return A boolean expression + */ + IExpression less(IExpression lhs, IExpression rhs); + + /** + * Create an expression that tests if lhs is less than or equal to rhs. + * @param lhs The left hand side value. + * @param rhs The right hand side value. + * @return A boolean expression + */ + IExpression lessEqual(IExpression lhs, IExpression rhs); + + /** + * Performs boolean normalizations on the expression to create a canonical form. + * @param operands The operands to normalize + * @param expressionType The type (must be either {@link IExpression#TYPE_AND} + * or {@link IExpression#TYPE_OR}. + * @return The normalized expression + */ + IExpression normalize(List operands, int expressionType); + + /** + * Create an expression that tests if lhs matches rhs. + * @param lhs The left hand side value. + * @param rhs The right hand side value. + * @return A boolean expression + */ + IExpression matches(IExpression lhs, IExpression rhs); + + /** + * Creates a parameterized top level expression suitable for predicate matching + * @param expression The boolean expression + * @param parameters The parameters to use in the call + * @return A top level predicate expression + */ + IMatchExpression matchExpression(IExpression expression, Object... parameters); + + /** + * Creates a member accessor expression. + * @param target The target for the member access + * @param name The name of the member + * @return A member expression + */ + IExpression member(IExpression target, String name); + + /** + * Creates an expression that negates the result of evaluating its operand. + * @param operand The boolean expression to negate + * @return A boolean expression + */ + IExpression not(IExpression operand); + + /** + * Create a logical or of its operands. + * @param operands The boolean operands + * @return A boolean expression + */ + IExpression or(IExpression... operands); + + /** + * Returns the variable that represents this in an expression + * @return The this variable. + */ + IExpression thisVariable(); + + /** + * Creates an expression that represents a variable + * @param name The name of the variable + * @return A variable expression + */ + IExpression variable(String name); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpressionParser.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpressionParser.java new file mode 100644 index 000000000..6e716af06 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpressionParser.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * Copyright (c) 2009 - 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.expression; + +/** + * A parser that produces an expression tree based on a string representation. An + * implementation will use the {@link IExpressionFactory} to create the actual expressions + * @since 2.0 + */ +public interface IExpressionParser { + /** + * Create a new expression. The expression will have access to the global + * variable and to the context parameters. + * @param exprString The string representing the boolean expression. + * @return The resulting expression tree. + */ + IExpression parse(String exprString); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpressionVisitor.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpressionVisitor.java new file mode 100644 index 000000000..1c314d804 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IExpressionVisitor.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * Copyright (c) 2009 - 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.expression; + +/** + * A general purpose visitor that will visit each node in an expression tree. + * @since 2.0 + */ +public interface IExpressionVisitor { + /** + * The method that will be called for each expression that is + * visited. + * @param expression The expression that the visitor visits. + * @return true to continue visiting other expressions or + * false to break out. + */ + boolean visit(IExpression expression); +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IFilterExpression.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IFilterExpression.java new file mode 100644 index 000000000..8e5bcba92 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IFilterExpression.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2009 - 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.expression; + +import java.util.Map; +import org.osgi.framework.Filter; + +/** + * An interface that combines the IExpression with the LDAP filter. The + * string representation is the LDAP filter syntax. + * @since 2.0 + */ +public interface IFilterExpression extends IExpression, Filter { + /** + * Filter using a Map. This Filter is + * executed using the specified Map's keys and values. + * The keys are case insensitively matched with this Filter. + * + * @param map The Map whose keys are used in the + * match. + * @return true if the map's keys and + * values match this filter; false otherwise. + * @throws IllegalArgumentException If map contains case + * variants of the same key name. + */ + boolean match(Map map); + + /** + * Filter with case sensitivity using a Map. This + * Filter is executed using the specified + * Map's keys and values. The keys are case sensitively + * matched with this Filter. + * + * @param map The Map whose keys are used in the + * match. + * @return true if the map's keys and + * values match this filter; false otherwise. + */ + boolean matchCase(Map map); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IMatchExpression.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IMatchExpression.java new file mode 100644 index 000000000..419e3f4ba --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/IMatchExpression.java @@ -0,0 +1,53 @@ +/******************************************************************************* + * Copyright (c) 2009 - 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.expression; + +/** + * A match expression is a boolean expression matching a candidate of a + * specific type. An {@link IEvaluationContext} is needed in order to evaluate + * a match and this class provides two ways of doing that. Either a context + * is created first and then reused in several subsequent calls to + * {@link #isMatch(IEvaluationContext, Object)} or, if no repeated calls are + * expected, the {@link #isMatch(Object)} method can be used. It will then + * create a context on each call. + */ +public interface IMatchExpression extends IExpression { + /** + *

    Creates a new context to be passed to repeated subsequent evaluations. The context + * will introduce 'this' as an uninitialized variable and make the parameters available. + * @return A new evaluation context. + */ + IEvaluationContext createContext(); + + /** + * Returns the parameters that this match expression was created with. + * @return An array of parameters, possibly empty but never null. + */ + Object[] getParameters(); + + /** + * This method creates a new evaluation context and assigns the candidate + * to the 'this' variable of the context and then evaluates the expression. + * This is essentially a short form for

    isMatch(createContext(), candidate)
    . + * @param candidate The object to test. + * @return the result of the evaluation. + */ + boolean isMatch(T candidate); + + /** + * This method assigns candidate to the 'this' variable of the + * context and then evaluates the expression. + * @param context A context + * @param candidate The object to test. + * @return the result of the evaluation. + */ + boolean isMatch(IEvaluationContext context, T candidate); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/SimplePattern.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/SimplePattern.java new file mode 100644 index 000000000..12087cb94 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/expression/SimplePattern.java @@ -0,0 +1,159 @@ +/******************************************************************************* + * Copyright (c) 2009 - 2010 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.expression; + +import java.io.Serializable; + +/** + * A simple compiled pattern. It supports two kinds of wildcards. The '*' (any character zero to many times) + * and the '?' (any character exactly one time). + * @since 2.0 + */ +public class SimplePattern implements Serializable, Comparable { + private static final long serialVersionUID = -2477990705739062410L; + + /** + * Matches the value with the compiled expression. The value + * is considered matching if all characters are matched by the expression. A + * partial match is not enough. + * @param value The value to match + * @return true if the value was a match. + */ + public synchronized boolean isMatch(CharSequence value) { + if (node == null) + node = parse(pattern, 0); + return node.match(value, 0); + } + + public String toString() { + return pattern; + } + + public int compareTo(SimplePattern o) { + return pattern.compareTo(o.pattern); + } + + public boolean equals(Object o) { + return o == this || (o instanceof SimplePattern && ((SimplePattern) o).pattern.equals(pattern)); + } + + public int hashCode() { + return 3 * pattern.hashCode(); + } + + private final String pattern; + private transient Node node; + + private SimplePattern(String pattern, Node node) { + this.pattern = pattern; + this.node = node; + } + + private static class RubberBandNode extends Node { + RubberBandNode(Node next) { + super(next); + } + + boolean match(CharSequence value, int pos) { + if (next == null) + return true; + + int top = value.length(); + while (pos < top) { + if (next.match(value, pos++)) + return true; + } + return false; + } + } + + private static class AnyCharacterNode extends Node { + AnyCharacterNode(Node next) { + super(next); + } + + boolean match(CharSequence value, int pos) { + int top = value.length(); + return next == null ? pos + 1 == top : next.match(value, pos + 1); + } + } + + private static class ConstantNode extends Node { + final String constant; + + ConstantNode(Node next, String constant) { + super(next); + this.constant = constant; + } + + boolean match(CharSequence value, int pos) { + int vtop = value.length(); + int ctop = constant.length(); + if (ctop + pos > vtop) + return false; + + for (int idx = 0; idx < ctop; ++idx, ++pos) + if (constant.charAt(idx) != value.charAt(pos)) + return false; + + return next == null ? true : next.match(value, pos); + } + } + + private static abstract class Node { + final Node next; + + Node(Node next) { + this.next = next; + } + + abstract boolean match(CharSequence value, int pos); + } + + public static SimplePattern compile(String pattern) { + if (pattern == null) + throw new IllegalArgumentException("Pattern can not be null"); //$NON-NLS-1$ + return new SimplePattern(pattern, null); + } + + private static Node parse(String pattern, int pos) { + int top = pattern.length(); + StringBuffer bld = null; + Node parsedNode = null; + while (pos < top) { + char c = pattern.charAt(pos); + switch (c) { + case '*' : + parsedNode = new RubberBandNode(parse(pattern, pos + 1)); + break; + case '?' : + parsedNode = new AnyCharacterNode(parse(pattern, pos + 1)); + break; + case '\\' : + if (++pos == top) + throw new IllegalArgumentException("Pattern ends with escape"); //$NON-NLS-1$ + c = pattern.charAt(pos); + // fall through + default : + if (bld == null) + bld = new StringBuffer(); + bld.append(c); + ++pos; + continue; + } + break; + } + + if (bld != null) + parsedNode = new ConstantNode(parsedNode, bld.toString()); + return parsedNode; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/CategoryMemberQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/CategoryMemberQuery.java new file mode 100644 index 000000000..d6324d360 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/CategoryMemberQuery.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.query; + +import java.util.Collection; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; +import org.eclipse.equinox.p2.query.MatchQuery; + +/** +/** + * A query matching every {@link IInstallableUnit} that is a member + * of the specified category. + * + * @since 2.0 + */ +public class CategoryMemberQuery extends MatchQuery { + private final Collection required; + + /** + * Creates a new query that will return the members of the + * given category. If the specified {@link IInstallableUnit} + * is not a category, then no installable unit will satisfy the query. + * + * @param category The category + */ + public CategoryMemberQuery(IInstallableUnit category) { + if (CategoryQuery.isCategory(category)) + this.required = category.getRequiredCapabilities(); + else + this.required = CollectionUtils.emptyList(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.metadata.query.MatchQuery#isMatch(java.lang.Object) + */ + public boolean isMatch(IInstallableUnit candidate) { + // since a category lists its members as requirements, then meeting + // any requirement means the candidate is a member of the category. + for (IRequirement req : required) { + if (candidate.satisfies(req)) + return true; + } + return false; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/CategoryQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/CategoryQuery.java new file mode 100644 index 000000000..d1d86f912 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/CategoryQuery.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.query; + +import org.eclipse.equinox.internal.p2.metadata.query.IUPropertyQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.MatchQuery; + +/** + * A query matching every {@link IInstallableUnit} that is a category. + * @since 2.0 + */ +public final class CategoryQuery extends MatchQuery { + private static final String PROP_TYPE_CATEGORY = "org.eclipse.equinox.p2.type.category"; //$NON-NLS-1$ + private IUPropertyQuery query; + + public CategoryQuery() { + query = new IUPropertyQuery(PROP_TYPE_CATEGORY, null); + } + + public boolean isMatch(IInstallableUnit candidate) { + return query.isMatch(candidate); + } + + /** + * Test if the {@link IInstallableUnit} is a category. + * @param iu the element being tested. + * @return true if the parameter is a category. + */ + public static boolean isCategory(IInstallableUnit iu) { + String value = iu.getProperty(PROP_TYPE_CATEGORY); + if (value != null && (value.equals(Boolean.TRUE.toString()))) + return true; + return false; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/ExpressionQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/ExpressionQuery.java new file mode 100644 index 000000000..ea0cb676b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/ExpressionQuery.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.query; + +import org.eclipse.equinox.internal.p2.metadata.expression.ExpressionFactory; +import org.eclipse.equinox.p2.metadata.expression.*; +import org.eclipse.equinox.p2.query.MatchQuery; + +/** + * A query that matches candidates against an expression. + */ +public class ExpressionQuery extends MatchQuery { + private final IMatchExpression expression; + private final IEvaluationContext context; + private final Class matchingClass; + + public ExpressionQuery(Class matchingClass, IExpression expression, Object... parameters) { + this(matchingClass, ExpressionUtil.getFactory(). matchExpression(expression, parameters)); + } + + public ExpressionQuery(Class matchingClass, IMatchExpression expression) { + this.matchingClass = matchingClass; + this.expression = expression; + this.context = expression.createContext(); + } + + @Override + public boolean isMatch(T candidate) { + if (!matchingClass.isInstance(candidate)) + return false; + ExpressionFactory.THIS.setValue(context, candidate); + return Boolean.TRUE == expression.evaluate(context); + } + + public IMatchExpression getExpression() { + return expression; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/FragmentQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/FragmentQuery.java new file mode 100644 index 000000000..fc70dd9e9 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/FragmentQuery.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.query; + +import org.eclipse.equinox.p2.metadata.IInstallableUnitFragment; + +import org.eclipse.equinox.internal.p2.metadata.query.IUPropertyQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.MatchQuery; + +/** + * A query matching every {@link IInstallableUnit} that is a category. + * @since 2.0 + */ +public final class FragmentQuery extends MatchQuery { + private static final String PROP_TYPE_FRAGMENT = "org.eclipse.equinox.p2.type.fragment"; //$NON-NLS-1$ + private IUPropertyQuery query; + + public FragmentQuery() { + query = new IUPropertyQuery(PROP_TYPE_FRAGMENT, null); + } + + public boolean isMatch(IInstallableUnit candidate) { + return query.isMatch(candidate); + } + + /** + * Test if the {@link IInstallableUnit} is a fragment. + * @param iu the element being tested. + * @return true if the parameter is a fragment. + */ + public static boolean isFragment(IInstallableUnit iu) { + if (iu instanceof IInstallableUnitFragment) + return true; + // String value = iu.getProperty(PROP_TYPE_FRAGMENT); + // if (value != null && (value.equals(Boolean.TRUE.toString()))) + // return true; + return false; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/GroupQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/GroupQuery.java new file mode 100644 index 000000000..298b04a2f --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/GroupQuery.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.query; + +import org.eclipse.equinox.internal.p2.metadata.query.IUPropertyQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.MatchQuery; + +/** + * A query matching every {@link IInstallableUnit} that is a group. + * @since 2.0 + */ +public final class GroupQuery extends MatchQuery { + private static final String PROP_TYPE_GROUP = "org.eclipse.equinox.p2.type.group"; //$NON-NLS-1$ + private IUPropertyQuery query; + + public GroupQuery() { + query = new IUPropertyQuery(PROP_TYPE_GROUP, null); + } + + public boolean isMatch(IInstallableUnit candidate) { + return query.isMatch(candidate); + } + + /** + * Test if the {@link IInstallableUnit} is a group. + * @param iu the element being tested. + * @return true if the parameter is a group. + */ + public static boolean isGroup(IInstallableUnit iu) { + String value = iu.getProperty(PROP_TYPE_GROUP); + if (value != null && (value.equals(Boolean.TRUE.toString()))) + return true; + return false; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/InstallableUnitQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/InstallableUnitQuery.java new file mode 100644 index 000000000..ac2110b03 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/InstallableUnitQuery.java @@ -0,0 +1,106 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.query; + +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; + +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IVersionedId; +import org.eclipse.equinox.p2.query.MatchQuery; + +/** + * A query that matches on the id and version of an {@link IInstallableUnit}. + * @since 2.0 + */ +public class InstallableUnitQuery extends MatchQuery { + /** + * A convenience query that will match any {@link IInstallableUnit} + * it encounters. + */ + public static final InstallableUnitQuery ANY = new InstallableUnitQuery((String) null); + + private String id; + private final VersionRange range; + + /** + * Creates a query that will match any {@link IInstallableUnit} with the given + * id, regardless of version. + * + * @param id The installable unit id to match, or null to match any id + */ + public InstallableUnitQuery(String id) { + this.id = id; + this.range = null; + } + + /** + * Creates a query that will match any {@link IInstallableUnit} with the given + * id, and whose version falls in the provided range. + * + * @param id The installable unit id to match, or null to match any id + * @param range The version range to match + */ + public InstallableUnitQuery(String id, VersionRange range) { + this.id = id; + this.range = range; + } + + /** + * Creates a query that will match any {@link IInstallableUnit} with the given + * id and version. + * + * @param id The installable unit id to match, or null to match any id + * @param version The precise version that a matching unit must have + */ + public InstallableUnitQuery(String id, Version version) { + this.id = id; + this.range = (version == null || Version.emptyVersion.equals(version)) ? null : new VersionRange(version, true, version, true); + } + + /** + * Creates a query that will match any {@link IInstallableUnit} with the given + * id and version. + * + * @param versionedId The precise id/version combination that a matching unit must have + */ + public InstallableUnitQuery(IVersionedId versionedId) { + this(versionedId.getId(), versionedId.getVersion()); + } + + /** + * Returns the id that this query will match against. + * @return The installable unit it + */ + public String getId() { + return id; + } + + /** + * Returns the version range that this query will match against. + * @return The installable unit version range. + */ + public VersionRange getRange() { + return range; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.query2.Query#isMatch(java.lang.Object) + */ + public boolean isMatch(IInstallableUnit candidate) { + if (id != null && !id.equals(candidate.getId())) + return false; + if (range != null && !range.isIncluded(candidate.getVersion())) + return false; + return true; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/PatchQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/PatchQuery.java new file mode 100644 index 000000000..d066db376 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/metadata/query/PatchQuery.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.metadata.query; + +import org.eclipse.equinox.internal.p2.metadata.query.IUPropertyQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.MatchQuery; + +/** + * A query matching every {@link IInstallableUnit} that is a patch. + * @since 2.0 + */ +public final class PatchQuery extends MatchQuery { + private static final String PROP_TYPE_PATCH = "org.eclipse.equinox.p2.type.patch"; //$NON-NLS-1$ + private IUPropertyQuery query; + + public PatchQuery() { + query = new IUPropertyQuery(PROP_TYPE_PATCH, Boolean.TRUE.toString()); + } + + public boolean isMatch(IInstallableUnit candidate) { + return query.isMatch(candidate); + } + + /** + * Test if the {@link IInstallableUnit} is a patch. + * @param iu the element being tested. + * @return true if the parameter is a patch. + */ + public static boolean isPatch(IInstallableUnit iu) { + String value = iu.getProperty(PROP_TYPE_PATCH); + if (value != null && (value.equals(Boolean.TRUE.toString()))) + return true; + return false; + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/Collector.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/Collector.java new file mode 100644 index 000000000..f7e36e07d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/Collector.java @@ -0,0 +1,172 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * EclipseSource - ongoing development + *******************************************************************************/ +package org.eclipse.equinox.p2.query; + +import java.lang.reflect.Array; +import java.util.*; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; +import org.eclipse.equinox.internal.p2.metadata.Messages; + +/** + * A collector is a generic visitor that collects objects passed to it, + * and can then express the result of the visit in various forms. The collector + * can also short-circuit a traversal by returning false from + * its {@link #accept(Object)} method. + *

    + * This default collector just accepts all objects passed to it. Clients may subclass + * to perform different processing on the objects passed to it. + * @param The type of object accepted by this collector + * @since 2.0 + */ +public class Collector implements IQueryResult { + private Set collected = null; + + public static final Collector EMPTY_COLLECTOR = new Collector() { + public boolean accept(Object val) { + return false; + } + }; + + @SuppressWarnings("unchecked") + public static final Collector emptyCollector() { + return (Collector) EMPTY_COLLECTOR; + } + + /** + * Creates a new collector. + */ + public Collector() { + super(); + } + + /** + * Accepts an object. + *

    + * This default implementation adds the objects to a list. Clients may + * override this method to perform additional filtering, add different objects + * to the list, short-circuit the traversal, or process the objects directly without + * collecting them. + * + * @param object the object to collect or visit + * @return true if the traversal should continue, + * or false to indicate the traversal should stop. + */ + public boolean accept(T object) { + getCollection().add(object); + return true; + } + + /** + * Adds the elements from one collector to this collector + * @param queryResult The collector from which the elements should be retrieved + */ + public void addAll(IQueryResult queryResult) { + boolean keepGoing = true; + for (Iterator iter = queryResult.iterator(); iter.hasNext() && keepGoing;) { + keepGoing = accept(iter.next()); + } + } + + /** + * Returns the collection that is being used to collect results. Unlike {@linkplain #toSet()}, + * this returns the actual modifiable collection that is being used to store results. The + * return value is only intended to be used within subclasses and should not be exposed + * outside of a collection class. + * + * @return the collection being used to collect results. + */ + protected Collection getCollection() { + if (collected == null) + collected = new HashSet(); + return collected; + } + + /** + * Returns whether this collector is empty. + * @return true if this collector has accepted any results, + * and false otherwise. + */ + public boolean isEmpty() { + return collected == null || collected.isEmpty(); + } + + /** + * Returns an iterator on the collected objects. + * + * @return an iterator of the collected objects. + */ + public Iterator iterator() { + return collected == null ? CollectionUtils. emptyList().iterator() : collected.iterator(); + } + + /** + * Returns the number of collected objects. + */ + public int size() { + return collected == null ? 0 : collected.size(); + } + + /** + * Returns the collected objects as an array + * + * @param clazz The type of array to return + * @return The array of results + * @throws ArrayStoreException the runtime type of the specified array is + * not a supertype of the runtime type of every collected object + */ + public T[] toArray(Class clazz) { + int size = collected == null ? 0 : collected.size(); + @SuppressWarnings("unchecked") + T[] result = (T[]) Array.newInstance(clazz, size); + if (size != 0) + collected.toArray(result); + return result; + } + + /** + * Returns a copy of the collected objects. + * + * @return An unmodifiable collection of the collected objects + */ + public Set toSet() { + return collected == null ? new HashSet() : new HashSet(collected); + } + + /** + * Performs a query on this results of this collector. + */ + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + IQueryResult result; + if (monitor == null) + monitor = new NullProgressMonitor(); + try { + monitor.beginTask(Messages.performing_subquery, 1); + result = query.perform(iterator()); + monitor.worked(1); + } finally { + monitor.done(); + } + return result; + } + + /** + * Returns the collected objects as an immutable collection. + * + * @return An unmodifiable collection of the collected objects + */ + @SuppressWarnings("unchecked") + public Set unmodifiableSet() { + return collected == null ? Collections.EMPTY_SET : Collections.unmodifiableSet(collected); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/CompoundQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/CompoundQuery.java new file mode 100644 index 000000000..594738036 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/CompoundQuery.java @@ -0,0 +1,252 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * EclipseSource - ongoing development + *******************************************************************************/ +package org.eclipse.equinox.p2.query; + +import java.lang.reflect.Array; +import java.util.*; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.equinox.internal.p2.query.QueryHelpers; + +/** + * A query that combines a group of sub-queries.

    + * + * In a CompoundQuery each sub-query is executed and the results are combined using + * either logical AND or logical OR operations.

    + * + * Clients are expected to call {@link CompoundQuery#createCompoundQuery(IQuery[], boolean)} + * to create a concrete instance of a CompoundQuery. If all Queries are instances of + * {@link IMatchQuery} then the resulting compound query will be a MatchCompoundQuery, otherwise the + * resulting compound query will be a {@link ContextQuery}. + * + * @noextend This class is not intended to be subclassed by clients. + * @since 2.0 + */ +public abstract class CompoundQuery implements ICompositeQuery { + protected IQuery[] queries; + protected boolean and; + + /** + * Creates a compound query that combines the given queries. The queries + * will be performed by the compound query in the given order. This method + * might not perform all queries if it can determine the result of the compound + * expression without doing so. + * + * If all the queries are instances of {@link IMatchQuery} then the resulting + * compound query will be an instance of IMatchQuery, otherwise the resulting + * compound query will be a context query. + * + * @param queries The queries to perform + * @param and true if this query represents a logical 'and', and + * false if this query represents a logical 'or'. + */ + public static CompoundQuery createCompoundQuery(IQuery[] queries, boolean and) { + if (isMatchQueries(queries)) { + return new CompoundQuery.MatchCompoundQuery(queries, and); + } + return new CompoundQuery.ContextCompoundQuery(queries, and); + } + + @SuppressWarnings("unchecked") + public static CompoundQuery createCompoundQuery(IQuery query1, IQuery query2, boolean and) { + return createCompoundQuery(new IQuery[] {query1, query2}, and); + } + + /** + * Returns the queries that make up this compound query + */ + public List> getQueries() { + return Arrays.asList(queries); + } + + /** + * Returns whether this compound query combines its queries with a logical + * 'and' or 'or'. + * @return true if this query represents a logical 'and', and + * false if this query represents a logical 'or'. + */ + public boolean isAnd() { + return and; + } + + protected CompoundQuery(IQuery[] queries, boolean and) { + this.queries = queries; + this.and = and; + } + + /** + * @param queries + */ + private static boolean isMatchQueries(IQuery[] queries) { + for (int i = 0; i < queries.length; i++) { + if (!(queries[i] instanceof IMatchQuery)) { + return false; + } + } + return true; + } + + /** + * Gets the ID for this Query. + */ + public String getId() { + return QueryHelpers.getId(this); + } + + /** + * Gets a particular property of the query. + * @param property The property to retrieve + */ + public Object getProperty(String property) { + return QueryHelpers.getProperty(this, property); + } + + /** + * The compound query instantiated when all queries are Match Queries. + */ + private static class MatchCompoundQuery extends CompoundQuery implements IMatchQuery { + + protected MatchCompoundQuery(IQuery[] queries, boolean and) { + super(queries, and); + } + + public boolean isMatch(T candidate) { + for (int i = 0; i < queries.length; i++) { + boolean valid = ((IMatchQuery) queries[i]).isMatch(candidate); + // if we are OR'ing then the first time we find a requirement that is met, return success + if (valid && !and) + return true; + // if we are AND'ing then the first time we find a requirement that is NOT met, return failure + if (!valid && and) + return false; + } + // if we get past the requirements check and we are AND'ing then return true + // since all requirements must have been met. If we are OR'ing then return false + // since none of the requirements were met. + return and; + } + + /** + * Performs this query on the given iterator, passing all objects in the iterator + * that match the criteria of this query to the given result. + */ + public final IQueryResult perform(Iterator iterator) { + prePerform(); + Collector result = new Collector(); + try { + while (iterator.hasNext()) { + T candidate = iterator.next(); + if (isMatch(candidate)) + if (!result.accept(candidate)) + break; + } + } finally { + postPerform(); + } + return result; + } + + public void prePerform() { + for (int i = 0; i < queries.length; i++) { + ((IMatchQuery) queries[i]).prePerform(); + } + } + + public void postPerform() { + for (int i = 0; i < queries.length; i++) { + ((IMatchQuery) queries[i]).postPerform(); + } + } + } + + /** + * The compound query instantiated when any of the queries are not + * match queries. + */ + private static class ContextCompoundQuery extends CompoundQuery { + + protected ContextCompoundQuery(IQuery[] queries, boolean and) { + super(queries, and); + } + + /* + * A collector that takes the set to puts the elements in. + */ + static class SetCollector implements IQueryResult { + private final Set s; + + public SetCollector(Set s) { + this.s = s; + } + + public boolean isEmpty() { + return s.isEmpty(); + } + + public Iterator iterator() { + return s.iterator(); + } + + @SuppressWarnings("unchecked") + public T[] toArray(Class clazz) { + return s.toArray((T[]) Array.newInstance(clazz, s.size())); + } + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return query.perform(iterator()); + } + + public Set toSet() { + return new HashSet(s); + } + + public Set unmodifiableSet() { + return Collections.unmodifiableSet(s); + } + } + + public IQueryResult perform(Iterator iterator) { + if (queries.length < 1) + return Collector.emptyCollector(); + + if (queries.length == 1) + return queries[0].perform(iterator); + + Collection data = new ArrayList(); + while (iterator.hasNext()) + data.add(iterator.next()); + + Set result; + if (isAnd()) { + result = queries[0].perform(data.iterator()).unmodifiableSet(); + for (int i = 1; i < queries.length && result.size() > 0; i++) { + HashSet retained = new HashSet(); + Iterator itor = queries[i].perform(data.iterator()).iterator(); + while (itor.hasNext()) { + T nxt = itor.next(); + if (result.contains(nxt)) + retained.add(nxt); + } + result = retained; + } + } else { + result = queries[0].perform(data.iterator()).toSet(); + for (int i = 1; i < queries.length; i++) { + Iterator itor = queries[i].perform(data.iterator()).iterator(); + while (itor.hasNext()) { + result.add(itor.next()); + } + } + } + return new SetCollector(result); + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/CompoundQueryable.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/CompoundQueryable.java new file mode 100644 index 000000000..bbfd2bd20 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/CompoundQueryable.java @@ -0,0 +1,147 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.query; + +import java.lang.reflect.Array; +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; + +/** + * A queryable that holds a number of other IQueryables and provides + * a mechanism for querying the entire set. + * @since 2.0 + */ +public class CompoundQueryable implements IQueryable { + + private IQueryable[] queryables; + + private CompoundQueryable(IQueryable[] queryables) { + this.queryables = queryables; + } + + @SuppressWarnings("unchecked") + public CompoundQueryable(Collection> queryables) { + this(queryables.toArray(new IQueryable[queryables.size()])); + } + + @SuppressWarnings("unchecked") + public CompoundQueryable(IQueryable q) { + this(new IQueryable[] {q}); + } + + @SuppressWarnings("unchecked") + public CompoundQueryable(IQueryable q1, IQueryable q2) { + this(new IQueryable[] {q1, q2}); + } + + @SuppressWarnings("unchecked") + public CompoundQueryable(IQueryable q1, IQueryable q2, IQueryable q3) { + this(new IQueryable[] {q1, q2, q3}); + } + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + IQueryResult subResults = null; + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + boolean isMatchQuery = query instanceof IMatchQuery; + int totalWork = isMatchQuery ? queryables.length : queryables.length + 1; + + try { + SubMonitor subMonitor = SubMonitor.convert(monitor, totalWork * 10); + Collector results; + if (!isMatchQuery) { + // If it is not a match query, then collect the results + // as a list, we will query this list for the final results + results = new ListCollector(); + } else + results = new Collector(); + + for (int i = 0; i < queryables.length; i++) { + if (subMonitor.isCanceled()) + break; + subResults = queryables[i].query(query, subMonitor.newChild(10)); + results.addAll(subResults); + } + + if (isMatchQuery) + return results; + + // If it is not a MatchQuery then we must query the results. + return results.query(query, subMonitor.newChild(10)); + } finally { + monitor.done(); + } + } + + /** + * A list collector. + * + * This is a collector backed as a list. + * + * The list collector is not intended to be used outside of this class. It is only public + * for testing purposes. + * + * @noinstantiate This class is not intended to be instantiated by clients. + * @noextend This class is not intended to be subclassed by clients. + * + */ + public static class ListCollector extends Collector { + private List collected; + + public ListCollector() { + super(); + } + + protected Collection getCollection() { + if (collected == null) + collected = new ArrayList(); + return collected; + } + + public boolean isEmpty() { + return collected == null || collected.isEmpty(); + } + + @SuppressWarnings("unchecked") + public T[] toArray(Class clazz) { + int size = collected == null ? 0 : collected.size(); + T[] result = (T[]) Array.newInstance(clazz, size); + if (size != 0) + collected.toArray(result); + return result; + } + + public boolean accept(T object) { + if (collected == null) + collected = new ArrayList(); + collected.add(object); + return true; + } + + /** + * Returns the collected objects as an immutable collection. + * + * @return An unmodifiable collection of the collected objects + */ + public Set toSet() { + return collected == null ? new HashSet() : new HashSet(collected); + } + + public Iterator iterator() { + return collected == null ? CollectionUtils. emptyList().iterator() : collected.iterator(); + } + + public int size() { + return collected == null ? 0 : collected.size(); + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/ContextQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/ContextQuery.java new file mode 100644 index 000000000..f65aa8a52 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/ContextQuery.java @@ -0,0 +1,60 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.query; + +import java.util.Iterator; +import org.eclipse.equinox.internal.p2.query.QueryHelpers; + +/** + * ContextQuery is the abstract superclass for Queries that require the entire + * input to evaluate the results. Queries must consider the group of elements before + * processing the results.

    + * + * ContextQueries must also be transitive. That is, if run on a subset of the + * input, the order in which they are executed must not matter. If there is the + * need for a non-transitive query, please see: + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=261403 + *

    + * Users of this query must call {@link #perform(Iterator)} to compute + * the results.

    + * This class may be subclassed by clients. Subclasses should specify the type + * of object they support querying on. Subclasses are also encouraged to clearly + * specify their match algorithm, and expose the parameters involved in the match + * computation, to allow {@link IQueryable} implementations to optimize their + * execution of the query.

    + * + * @since 2.0 + */ +public abstract class ContextQuery implements IQuery { + + /** + * Evaluates the query for a specific input. + * + * @param iterator The elements for which to evaluate the query on + * @return The results of the query. The collector returned must be + * the collector passed in. + */ + public abstract IQueryResult perform(Iterator iterator); + + /** + * Gets the ID for this Query. + */ + public String getId() { + return QueryHelpers.getId(this); + } + + /** + * Gets a particular property of the query. + * @param property The property to retrieve + */ + public Object getProperty(String property) { + return QueryHelpers.getProperty(this, property); + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/ICompositeQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/ICompositeQuery.java new file mode 100644 index 000000000..1b0baeae5 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/ICompositeQuery.java @@ -0,0 +1,27 @@ +/******************************************************************************* +* Copyright (c) 2009, 2010 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.query; + +import java.util.List; + +/** + * A query that contains a number of sub queries. All queries that support sub-queries + * should implement this interface so clients can access the sub queries. + * @since 2.0 + */ +public interface ICompositeQuery extends IQuery { + + /** + * Returns all the child queries of a CompositeQuery. + * @return All the child queries. + */ + public List> getQueries(); + +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IMatchQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IMatchQuery.java new file mode 100644 index 000000000..b25b044b6 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IMatchQuery.java @@ -0,0 +1,60 @@ +/******************************************************************************* +* Copyright (c) 2009, 2010 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.query; + +/** + * A query in which the elements can be evaluated by calling isMatch on. Each + * element can be evaluated independently of all other elements. Match queries + * can be evaluated in parallel as each call {@link #isMatch(Object)} is mutually + * exclusive from all other calls.

    + * + * @noimplement This interface is not intended to be implemented by clients. Clients + * creating custom queries must extend {@link MatchQuery} instead. + * @since 2.0 + */ +public interface IMatchQuery extends IQuery { + + /** + * Returns whether the given object satisfies the parameters of this query. + * + * @param candidate The object to perform the query against + * @return true if the unit satisfies the parameters + * of this query, and false otherwise + * + * @noreference This method is not intended to be referenced by clients. + */ + public boolean isMatch(T candidate); + + /** + * Execute any pre-processing that must be done before this query is performed against + * a particular iterator. This method may be used by subclasses to do any calculations, + * caching, or other preparation for the query. + *

    + * This method is internal to the framework. Subclasses may override this method, but + * should not call this method. + * + * @noreference This method is not intended to be referenced by clients. + */ + public void prePerform(); + + /** + * Execute any post-processing that must be done after this query has been performed against + * a particular iterator. This method may be used by subclasses to clear caches or any other + * cleanup that should occur after a query. + *

    + * This method will be called even if the query does not complete successfully. + *

    + * This method is internal to the framework. Subclasses may override this method, but + * should not call this method. + * + * @noreference This method is not intended to be referenced by clients. + */ + public void postPerform(); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IQuery.java new file mode 100644 index 000000000..9c61de05f --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IQuery.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * EclipseSource - ongoing development + *******************************************************************************/ +package org.eclipse.equinox.p2.query; + + +import java.util.Iterator; + +/** + * The superclass of all queries that can be performed on an {@link IQueryable}. + *

    + * + * @noimplement This interface is not intended to be implemented by clients. + * @noextend This interface is not intended to be extended by clients. + * @since 2.0 + */ +public interface IQuery { + + /** + * Evaluates the query for a specific input. + * + * @param iterator The elements for which to evaluate the query on + * @return The results of the query. The collector returned must be + * the collector passed in. + */ + public abstract IQueryResult perform(Iterator iterator); + + /** + * Gets the ID for this Query. + */ + public String getId(); + + /** + * Gets a particular property of the query. + * @param property The property to retrieve + */ + public Object getProperty(String property); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IQueryResult.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IQueryResult.java new file mode 100644 index 000000000..12e0cbf1c --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IQueryResult.java @@ -0,0 +1,57 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.query; + +import java.util.Iterator; +import java.util.Set; + +/** + * An IQueryResult represents the results of a query. + * @since 2.0 + * + */ +public interface IQueryResult extends IQueryable { + /** + * Returns whether this QueryResult is empty. + * @return true if this QueryResult has accepted any results, + * and false otherwise. + */ + public boolean isEmpty(); + + /** + * Returns an iterator on the collected objects. + * + * @return an iterator of the collected objects. + */ + public Iterator iterator(); + + /** + * Returns the collected objects as an array + * + * @param clazz The type of array to return + * @return The array of results + * @throws ArrayStoreException the runtime type of the specified array is + * not a supertype of the runtime type of every collected object + */ + public T[] toArray(Class clazz); + + /** + * Creates a new Set copy with the contents of this query result. The + * copy can be altered without any side effects on its origin. + * @return A detached copy of the result. + */ + public Set toSet(); + + /** + * Returns a Set backed by this query result. The set is immutable. + * @return A Set backed by this query result. + */ + public Set unmodifiableSet(); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IQueryable.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IQueryable.java new file mode 100644 index 000000000..22b4d8bd7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/IQueryable.java @@ -0,0 +1,36 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.query; + +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * An IQueryable contains objects, and is able to perform queries on those objects. + *

    + * This interface may be implemented by clients. + * @since 2.0 + */ +public interface IQueryable { + /** + * Performs a query, passing any objects that satisfy the + * query to the provided collector. + *

    + * This method is long-running; progress and cancellation are provided + * by the given progress monitor. + *

    + * + * @param query The query to perform + * @param monitor a progress monitor, or null if progress + * reporting is not desired + * @return The collector argument + */ + public IQueryResult query(IQuery query, IProgressMonitor monitor); +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/LimitQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/LimitQuery.java new file mode 100644 index 000000000..6da75ca1f --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/LimitQuery.java @@ -0,0 +1,57 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.query; + +import java.util.*; + +/** + * A limit query can be used to limit the number of query results returned. Once + * the limit is reached, the query is terminated. + * @since 2.0 + */ +public class LimitQuery extends ContextQuery implements ICompositeQuery { + + private final IQuery query; + private final int limit; + + public LimitQuery(IQuery query, int limit) { + this.query = query; + this.limit = limit; + } + + public IQueryResult perform(Iterator iterator) { + if (limit == 0) + return Collector.emptyCollector(); + + int count = 0; + Collector result = new Collector(); + if (query instanceof IMatchQuery) { + IMatchQuery matchQuery = (IMatchQuery) query; + while (iterator.hasNext()) { + T candidate = iterator.next(); + if (matchQuery.isMatch(candidate)) { + result.accept(candidate); + if (++count >= limit) + break; + } + } + } else { + iterator = query.perform(iterator).iterator(); + while (++count <= limit && iterator.hasNext()) + result.accept(iterator.next()); + } + return result; + } + + public List> getQueries() { + return Collections.singletonList(query); + } + +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/MatchQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/MatchQuery.java new file mode 100644 index 000000000..f8e4e8a2d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/MatchQuery.java @@ -0,0 +1,107 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +* IBM Corporation - ongoing development +******************************************************************************/ +package org.eclipse.equinox.p2.query; + +import java.util.Iterator; +import org.eclipse.equinox.internal.p2.query.QueryHelpers; + +/** + * This class represents the superclass of most of p2's queries. Every element + * in the query can be evaluated by calling isMatch on it. If {@link #isMatch(Object)} returns true, + * then the element WILL be included in the query result. If {@link #isMatch(Object)} returns false, then + * the element WILL NOT be included in the query result. + *

    + * This class may be subclassed by clients. Subclasses should specify the type + * of object they support querying on. Subclasses are also encouraged to clearly + * specify their match algorithm, and expose the parameters involved in the match + * computation, to allow {@link IQueryable} implementations to optimize their + * execution of the query. + * @since 2.0 + */ +public abstract class MatchQuery implements IMatchQuery { + + /** + * Returns whether the given object satisfies the parameters of this query. + * + * @param candidate The object to perform the query against + * @return true if the unit satisfies the parameters + * of this query, and false otherwise + * + * @noreference This method is not intended to be referenced by clients. + * Clients should call {@link #perform(Iterator)} + */ + public abstract boolean isMatch(T candidate); + + /** + * Gets the ID for this Query. + */ + public String getId() { + return QueryHelpers.getId(this); + } + + /** + * Gets a particular property of the query. + * @param property The property to retrieve + */ + public Object getProperty(String property) { + return QueryHelpers.getProperty(this, property); + } + + /** + * Performs this query on the given iterator, passing all objects in the iterator + * that match the criteria of this query to the given result. + */ + public final IQueryResult perform(Iterator iterator) { + Collector result = new Collector(); + prePerform(); + try { + while (iterator.hasNext()) { + T candidate = iterator.next(); + if (candidate != null && isMatch(candidate)) + if (!result.accept(candidate)) + break; + } + } finally { + postPerform(); + } + return result; + } + + /** + * Execute any pre-processing that must be done before this query is performed against + * a particular iterator. This method may be used by subclasses to do any calculations, + * caching, or other preparation for the query. + *

    + * This method is internal to the framework. Subclasses may override this method, but + * should not call this method. + * + * @noreference This method is not intended to be referenced by clients. + */ + public void prePerform() { + // nothing to do by default + } + + /** + * Execute any post-processing that must be done after this query has been performed against + * a particular iterator. This method may be used by subclasses to clear caches or any other + * cleanup that should occur after a query. + *

    + * This method will be called even if the query does not complete successfully. + *

    + * This method is internal to the framework. Subclasses may override this method, but + * should not call this method. + * + * @noreference This method is not intended to be referenced by clients. + */ + public void postPerform() { + // nothing to do by default + } +} diff --git a/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/PipedQuery.java b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/PipedQuery.java new file mode 100644 index 000000000..07147a1cf --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.metadata/src/org/eclipse/equinox/p2/query/PipedQuery.java @@ -0,0 +1,66 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.query; + +import java.util.*; +import org.eclipse.equinox.internal.p2.query.QueryHelpers; + +/** + * A PipedQuery is an aggregate query in which each sub-query + * is executed in succession. The results from the ith sub-query + * are piped as input into the i+1th sub-query. + * @since 2.0 + */ +public class PipedQuery implements ICompositeQuery { + protected final IQuery[] queries; + + public PipedQuery(IQuery[] queries) { + this.queries = queries; + } + + @SuppressWarnings("unchecked") + public PipedQuery(IQuery query1, IQuery query2) { + this(new IQuery[] {query1, query2}); + } + + /** + * Gets the ID for this Query. + */ + public String getId() { + return QueryHelpers.getId(this); + } + + /** + * Gets a particular property of the query. + * @param property The property to retrieve + */ + public Object getProperty(String property) { + return QueryHelpers.getProperty(this, property); + } + + /** + * Returns the queries that make up this compound query + */ + public List> getQueries() { + return Arrays.asList(queries); + } + + public IQueryResult perform(Iterator iterator) { + IQueryResult last = Collector.emptyCollector(); + if (queries.length > 0) { + last = queries[0].perform(iterator); + for (int i = 1; i < queries.length; i++) + // Take the results of the previous query and using them + // to drive the next one (i.e. composing queries) + last = queries[i].perform(last.iterator()); + } + return last; + } +} diff --git a/bundles/org.eclipse.equinox.p2.operations/.classpath b/bundles/org.eclipse.equinox.p2.operations/.classpath new file mode 100644 index 000000000..64c5e31b7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/bundles/org.eclipse.equinox.p2.operations/.cvsignore b/bundles/org.eclipse.equinox.p2.operations/.cvsignore new file mode 100644 index 000000000..c5e82d745 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/.cvsignore @@ -0,0 +1 @@ +bin \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.operations/.project b/bundles/org.eclipse.equinox.p2.operations/.project new file mode 100644 index 000000000..e5272e277 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/.project @@ -0,0 +1,34 @@ + + + org.eclipse.equinox.p2.operations + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.pde.api.tools.apiAnalysisBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + org.eclipse.pde.api.tools.apiAnalysisNature + + diff --git a/bundles/org.eclipse.equinox.p2.operations/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.operations/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..69f49b645 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,329 @@ +#Tue Dec 29 23:18:33 CET 2009 +eclipse.preferences.version=1 +org.eclipse.jdt.core.builder.cleanOutputFolder=clean +org.eclipse.jdt.core.builder.duplicateResourceTask=warning +org.eclipse.jdt.core.builder.invalidClasspath=abort +org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch +org.eclipse.jdt.core.circularClasspath=error +org.eclipse.jdt.core.classpath.exclusionPatterns=enabled +org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.doc.comment.support=enabled +org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=error +org.eclipse.jdt.core.compiler.problem.emptyStatement=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.fieldHiding=warning +org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=error +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=warning +org.eclipse.jdt.core.compiler.problem.invalidJavadoc=error +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private +org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=enabled +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public +org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=public +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=warning +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=warning +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=enabled +org.eclipse.jdt.core.compiler.problem.unusedImport=error +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.5 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false +org.eclipse.jdt.core.formatter.comment.format_block_comments=false +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=false +org.eclipse.jdt.core.formatter.comment.format_line_comments=false +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=false +org.eclipse.jdt.core.formatter.comment.indent_root_tags=false +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert +org.eclipse.jdt.core.formatter.comment.line_length=80 +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.lineSplit=800 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false +org.eclipse.jdt.core.formatter.tabulation.char=tab +org.eclipse.jdt.core.formatter.tabulation.size=4 +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.incompatibleJDKLevel=ignore +org.eclipse.jdt.core.incompleteClasspath=error diff --git a/bundles/org.eclipse.equinox.p2.operations/.settings/org.eclipse.jdt.ui.prefs b/bundles/org.eclipse.equinox.p2.operations/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 000000000..dbe72f165 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,57 @@ +#Sun Sep 23 11:59:14 EDT 2007 +eclipse.preferences.version=1 +editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true +formatter_profile=_core +formatter_settings_version=11 +org.eclipse.jdt.ui.ignorelowercasenames=true +org.eclipse.jdt.ui.importorder=; +org.eclipse.jdt.ui.ondemandthreshold=3 +org.eclipse.jdt.ui.staticondemandthreshold=3 +org.eclipse.jdt.ui.text.custom_code_templates= +sp_cleanup.add_default_serial_version_id=true +sp_cleanup.add_generated_serial_version_id=false +sp_cleanup.add_missing_annotations=true +sp_cleanup.add_missing_deprecated_annotations=true +sp_cleanup.add_missing_nls_tags=false +sp_cleanup.add_missing_override_annotations=true +sp_cleanup.add_serial_version_id=false +sp_cleanup.always_use_blocks=true +sp_cleanup.always_use_parentheses_in_expressions=false +sp_cleanup.always_use_this_for_non_static_field_access=false +sp_cleanup.always_use_this_for_non_static_method_access=false +sp_cleanup.convert_to_enhanced_for_loop=false +sp_cleanup.format_source_code=true +sp_cleanup.make_local_variable_final=false +sp_cleanup.make_parameters_final=false +sp_cleanup.make_private_fields_final=true +sp_cleanup.make_variable_declarations_final=true +sp_cleanup.never_use_blocks=false +sp_cleanup.never_use_parentheses_in_expressions=true +sp_cleanup.on_save_use_additional_actions=false +sp_cleanup.organize_imports=true +sp_cleanup.qualify_static_field_accesses_with_declaring_class=false +sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +sp_cleanup.qualify_static_member_accesses_with_declaring_class=false +sp_cleanup.qualify_static_method_accesses_with_declaring_class=false +sp_cleanup.remove_private_constructors=true +sp_cleanup.remove_trailing_whitespaces=false +sp_cleanup.remove_trailing_whitespaces_all=true +sp_cleanup.remove_trailing_whitespaces_ignore_empty=false +sp_cleanup.remove_unnecessary_casts=true +sp_cleanup.remove_unnecessary_nls_tags=false +sp_cleanup.remove_unused_imports=false +sp_cleanup.remove_unused_local_variables=false +sp_cleanup.remove_unused_private_fields=true +sp_cleanup.remove_unused_private_members=false +sp_cleanup.remove_unused_private_methods=true +sp_cleanup.remove_unused_private_types=true +sp_cleanup.sort_members=false +sp_cleanup.sort_members_all=false +sp_cleanup.use_blocks=false +sp_cleanup.use_blocks_only_for_return_and_throw=false +sp_cleanup.use_parentheses_in_expressions=false +sp_cleanup.use_this_for_non_static_field_access=false +sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true +sp_cleanup.use_this_for_non_static_method_access=false +sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/bundles/org.eclipse.equinox.p2.operations/.settings/org.eclipse.pde.core.prefs b/bundles/org.eclipse.equinox.p2.operations/.settings/org.eclipse.pde.core.prefs new file mode 100644 index 000000000..6904bd96c --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/.settings/org.eclipse.pde.core.prefs @@ -0,0 +1,4 @@ +#Sat Aug 11 20:17:52 EDT 2007 +eclipse.preferences.version=1 +pluginProject.extensions=false +resolve.requirebundle=false diff --git a/bundles/org.eclipse.equinox.p2.operations/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.operations/META-INF/MANIFEST.MF new file mode 100644 index 000000000..8f2ab8892 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/META-INF/MANIFEST.MF @@ -0,0 +1,35 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: org.eclipse.equinox.p2.operations;singleton:=true +Bundle-Name: %pluginName +Bundle-Vendor: %providerName +Bundle-Localization: plugin +Bundle-Version: 2.0.0.qualifier +Bundle-Activator: org.eclipse.equinox.internal.p2.operations.Activator +Import-Package: org.eclipse.equinox.internal.p2.core.helpers, + org.eclipse.equinox.internal.p2.engine, + org.eclipse.equinox.internal.p2.engine.phases, + org.eclipse.equinox.internal.p2.metadata, + org.eclipse.equinox.internal.p2.repository.helpers, + org.eclipse.equinox.internal.provisional.configurator, + org.eclipse.equinox.internal.provisional.p2.core, + org.eclipse.equinox.internal.provisional.p2.core.eventbus, + org.eclipse.equinox.internal.provisional.p2.director, + org.eclipse.equinox.internal.provisional.p2.metadata, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.engine.query, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.metadata, + org.osgi.framework;version="1.4.0" +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 +Export-Package: org.eclipse.equinox.p2.operations +Require-Bundle: org.eclipse.core.runtime, + org.eclipse.equinox.common;bundle-version="[3.3.0,4.0)" +Bundle-ActivationPolicy: lazy diff --git a/bundles/org.eclipse.equinox.p2.operations/about.html b/bundles/org.eclipse.equinox.p2.operations/about.html new file mode 100644 index 000000000..460233046 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/about.html @@ -0,0 +1,28 @@ + + + + +About + + +

    About This Content

    + +

    June 2, 2006

    +

    License

    + +

    The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise +indicated below, the Content is provided to you under the terms and conditions of the +Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available +at http://www.eclipse.org/legal/epl-v10.html. +For purposes of the EPL, "Program" will mean the Content.

    + +

    If you did not receive this Content directly from the Eclipse Foundation, the Content is +being redistributed by another party ("Redistributor") and different terms and conditions may +apply to your use of any object code in the Content. Check the Redistributor's license that was +provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise +indicated below, the terms and conditions of the EPL still apply to any source code in the Content +and such source code may be obtained at http://www.eclipse.org.

    + + + \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.operations/build.properties b/bundles/org.eclipse.equinox.p2.operations/build.properties new file mode 100644 index 000000000..ca5030900 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/build.properties @@ -0,0 +1,19 @@ +############################################################################### +# Copyright (c) 2005, 2007 IBM Corporation and others. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# IBM Corporation - initial API and implementation +############################################################################### +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + about.html,\ + plugin.properties +src.includes = about.html +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.operations/plugin.properties b/bundles/org.eclipse.equinox.p2.operations/plugin.properties new file mode 100644 index 000000000..3c8feb57a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/plugin.properties @@ -0,0 +1,12 @@ +############################################################################### +# Copyright (c) 2007, 2009 IBM Corporation and others. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# IBM Corporation - initial API and implementation +############################################################################### +pluginName = Equinox Provisioning Update Checker +providerName = Eclipse.org - Equinox diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/Activator.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/Activator.java new file mode 100644 index 000000000..9580bc9f7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/Activator.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.operations; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +/** + * Activator class that registers the update checker service. + */ +public class Activator implements BundleActivator { + public static final String ID = "org.eclipse.equinox.p2.operations"; //$NON-NLS-1$ + private static BundleContext context; + + public static BundleContext getContext() { + return context; + } + + public void start(BundleContext bundleContext) throws Exception { + Activator.context = bundleContext; + } + + public void stop(BundleContext bundleContext) throws Exception { + Activator.context = null; + } +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/DownloadPhaseSet.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/DownloadPhaseSet.java new file mode 100644 index 000000000..bd0f4a5d1 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/DownloadPhaseSet.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +/** + * + */ +package org.eclipse.equinox.internal.p2.operations; + +import org.eclipse.equinox.internal.p2.engine.Phase; +import org.eclipse.equinox.internal.p2.engine.PhaseSet; +import org.eclipse.equinox.internal.p2.engine.phases.Collect; + + +public class DownloadPhaseSet extends PhaseSet { + public DownloadPhaseSet() { + super(new Phase[] {new Collect(10)}); + } +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/IStatusCodes.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/IStatusCodes.java new file mode 100644 index 000000000..34f92df10 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/IStatusCodes.java @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.operations; + +/** + * IStatusCodes defines codes for common status conditions when + * performing provisioning operations. + * + * This interface is not intended to be implemented + * + * @since 2.0 + * @noimplement This interface is not intended to be implemented by clients. + */ +public interface IStatusCodes { + + //Operation status codes [10000-10999] - note these cannot conflict with the core codes + //in ProvisionException or we'll see strange results. + + public static final int NOTHING_TO_UPDATE = 10000; + + // Status codes associated with profile change request or plans being altered from the original intent + public static final int PROFILE_CHANGE_ALTERED = 10001; + public static final int IU_REQUEST_ALTERED = 10002; + public static final int ALTERED_IMPLIED_UPDATE = 10003; + public static final int ALTERED_IGNORED_IMPLIED_DOWNGRADE = 10004; + public static final int ALTERED_IGNORED_ALREADY_INSTALLED = 10005; + public static final int ALTERED_PARTIAL_INSTALL = 10006; + public static final int ALTERED_PARTIAL_UNINSTALL = 10007; + public static final int ALTERED_SIDE_EFFECT_UPDATE = 10008; + public static final int ALTERED_SIDE_EFFECT_REMOVE = 10009; + public static final int ALTERED_SIDE_EFFECT_INSTALL = 10010; + public static final int ALTERED_IGNORED_INSTALL_REQUEST = 10011; + public static final int ALTERED_IGNORED_UNINSTALL_REQUEST = 10012; + public static final int ALTERED_IGNORED_IMPLIED_UPDATE = 10013; + + // Status codes associated with inability to perform an operation + public static final int UNEXPECTED_NOTHING_TO_DO = 10050; + public static final int EXPECTED_NOTHING_TO_DO = 10051; + public static final int OPERATION_ALREADY_IN_PROGRESS = 10052; + + // Status codes associated with repositories + public static final int INVALID_REPOSITORY_LOCATION = 10100; +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/Messages.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/Messages.java new file mode 100644 index 000000000..55e98c177 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/Messages.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.internal.p2.operations; + +import org.eclipse.osgi.util.NLS; + +/** + * @since 2.0 + * + */ +public class Messages extends NLS { + private static final String BUNDLE_NAME = "org.eclipse.equinox.internal.p2.operations.messages"; //$NON-NLS-1$ + + public static String InstallOperation_ComputeProfileChangeProgress; + + public static String InstallOperation_InstallJobName; + public static String InstallOperation_ResolveJobName; + + public static String ProfileChangeOperation_NoProfileChangeRequest; + public static String ProfileChangeOperation_ResolveTaskName; + + public static String ProvisioningJob_GenericErrorStatusMessage; + public static String ProvisioningSession_AgentNotFound; + + public static String ProvisioningSession_InstallPlanConfigurationError; + + public static String PlanAnalyzer_IgnoringInstall; + public static String PlanAnalyzer_LockedImpliedUpdate0; + public static String PlanAnalyzer_PartialInstall; + public static String PlanAnalyzer_PartialUninstall; + public static String PlanAnalyzer_SideEffectInstall; + public static String PlanAnalyzer_SideEffectUninstall; + public static String PlannerResolutionJob_NullProvisioningPlan; + + public static String PlanAnalyzer_IgnoringImpliedDowngrade; + public static String PlanAnalyzer_ImpliedUpdate; + public static String PlanAnalyzer_Items; + public static String PlanAnalyzer_NothingToDo; + + public static String PlanAnalyzer_NoUpdates; + public static String PlanAnalyzer_AlreadyInstalled; + public static String PlanAnalyzer_AnotherOperationInProgress; + public static String PlanAnalyzer_RequestAltered; + public static String PlanAnalyzer_UnexpectedError; + + public static String RepositoryTracker_DuplicateLocation; + public static String RepositoryTracker_InvalidLocation; + + public static String ResolutionResult_SummaryStatus; + + public static String SizingPhaseSet_PhaseSetName; + + public static String UninstallOperation_ProvisioningJobName; + public static String UninstallOperation_ResolveJobName; + + public static String UpdateOperation_ProfileChangeRequestProgress; + public static String UpdateOperation_ResolveJobName; + public static String UpdateOperation_UpdateJobName; + + static { + // initialize resource bundle + NLS.initializeMessages(BUNDLE_NAME, Messages.class); + } + + private Messages() { + } +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/PlanAnalyzer.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/PlanAnalyzer.java new file mode 100644 index 000000000..6a0a709f2 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/PlanAnalyzer.java @@ -0,0 +1,154 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.internal.p2.operations; + +import java.util.Map.Entry; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.internal.provisional.p2.director.RequestStatus; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.osgi.util.NLS; + +/** + * This class analyzes a profile change request and the resultant provisioning plan, + * and reports problems in a way that can be communicated to a user. + * + * @since 3.5 + */ +public class PlanAnalyzer { + + public static IStatus getStatus(int statusCode, IInstallableUnit affectedIU) { + switch (statusCode) { + case IStatusCodes.NOTHING_TO_UPDATE : + return new Status(IStatus.INFO, Activator.ID, statusCode, Messages.PlanAnalyzer_NoUpdates, null); + case IStatusCodes.PROFILE_CHANGE_ALTERED : + return new MultiStatus(Activator.ID, statusCode, Messages.PlanAnalyzer_RequestAltered, null); + case IStatusCodes.ALTERED_IMPLIED_UPDATE : + return new Status(IStatus.INFO, Activator.ID, statusCode, NLS.bind(Messages.PlanAnalyzer_ImpliedUpdate, getIUString(affectedIU)), null); + case IStatusCodes.ALTERED_IGNORED_IMPLIED_UPDATE : + return new Status(IStatus.WARNING, Activator.ID, statusCode, NLS.bind(Messages.PlanAnalyzer_LockedImpliedUpdate0, getIUString(affectedIU)), null); + case IStatusCodes.ALTERED_IGNORED_IMPLIED_DOWNGRADE : + return new Status(IStatus.WARNING, Activator.ID, statusCode, NLS.bind(Messages.PlanAnalyzer_IgnoringImpliedDowngrade, getIUString(affectedIU)), null); + case IStatusCodes.ALTERED_IGNORED_ALREADY_INSTALLED : + return new Status(IStatus.WARNING, Activator.ID, statusCode, NLS.bind(Messages.PlanAnalyzer_AlreadyInstalled, getIUString(affectedIU)), null); + case IStatusCodes.ALTERED_PARTIAL_INSTALL : + return new Status(IStatus.INFO, Activator.ID, statusCode, NLS.bind(Messages.PlanAnalyzer_PartialInstall, getIUString(affectedIU)), null); + case IStatusCodes.ALTERED_PARTIAL_UNINSTALL : + return new Status(IStatus.INFO, Activator.ID, statusCode, NLS.bind(Messages.PlanAnalyzer_PartialUninstall, getIUString(affectedIU)), null); + case IStatusCodes.UNEXPECTED_NOTHING_TO_DO : + return new Status(IStatus.ERROR, Activator.ID, statusCode, NLS.bind(Messages.PlanAnalyzer_NothingToDo, getIUString(affectedIU)), null); + case IStatusCodes.OPERATION_ALREADY_IN_PROGRESS : + return new Status(IStatus.ERROR, Activator.ID, statusCode, Messages.PlanAnalyzer_AnotherOperationInProgress, null); + default : + return new Status(IStatus.ERROR, Activator.ID, statusCode, NLS.bind(Messages.PlanAnalyzer_UnexpectedError, new Integer(statusCode), getIUString(affectedIU)), null); + } + } + + public static MultiStatus getProfileChangeAlteredStatus() { + return (MultiStatus) getStatus(IStatusCodes.PROFILE_CHANGE_ALTERED, null); + } + + public static ResolutionResult computeResolutionResult(ProfileChangeRequest originalRequest, IProvisioningPlan plan, MultiStatus originalStatus) { + Assert.isNotNull(originalRequest); + Assert.isNotNull(plan); + Assert.isNotNull(originalStatus); + + ResolutionResult report = new ResolutionResult(); + + // If the plan was canceled, no further analysis is needed + if (plan.getStatus().getSeverity() == IStatus.CANCEL) { + report.addSummaryStatus(plan.getStatus()); + return report; + } + + if (nothingToDo(originalRequest)) { + report.addSummaryStatus(getStatus(IStatusCodes.UNEXPECTED_NOTHING_TO_DO, null)); + IStatus[] details = originalStatus.getChildren(); + for (int i = 0; i < details.length; i++) + report.addSummaryStatus(details[i]); + return report; + } + + // If there was already some status supplied before resolution, this should get included + // with the report. For example, this might contain information about the profile request + // being altered before resolution began. + if (originalStatus != null && originalStatus.getChildren().length > 0) { + report.addSummaryStatus(originalStatus); + } + + // If the overall plan had a non-OK status, capture that in the report. + if (!plan.getStatus().isOK()) + report.addSummaryStatus(plan.getStatus()); + + // Now we compare what was requested with what is going to happen. + // In the long run, when a RequestStatus can provide actual explanation/status + // about failures, we might want to add this information to the overall status. + // As it stands now, if the provisioning plan is in error, that info is more detailed + // than the request status. So we will only add request status info to the overall + // status when the overall status is not in error. + if (plan.getStatus().getSeverity() != IStatus.ERROR) { + IInstallableUnit[] iusAdded = originalRequest.getAddedInstallableUnits(); + for (int i = 0; i < iusAdded.length; i++) { + RequestStatus rs = (RequestStatus) plan.getRequestStatus(iusAdded[i]); + if (rs.getSeverity() == IStatus.ERROR) { + // This is a serious error so it must also appear in the overall status + IStatus fail = new Status(IStatus.ERROR, Activator.ID, IStatusCodes.ALTERED_IGNORED_INSTALL_REQUEST, NLS.bind(Messages.PlanAnalyzer_IgnoringInstall, getIUString(iusAdded[i])), null); + report.addStatus(iusAdded[i], fail); + report.addSummaryStatus(fail); + } + } + IInstallableUnit[] iusRemoved = originalRequest.getRemovedInstallableUnits(); + for (int i = 0; i < iusRemoved.length; i++) { + RequestStatus rs = (RequestStatus) plan.getRequestStatus(iusRemoved[i]); + if (rs.getSeverity() == IStatus.ERROR) { + // TODO see https://bugs.eclipse.org/bugs/show_bug.cgi?id=255984 + // We are making assumptions here about why the planner chose to ignore an uninstall. + // Assume it could not be uninstalled because of some other dependency, yet the planner did not view + // this as an error. So we inform the user that we can only uninstall parts of it. The root property will be + // removed per the original change request. + IStatus fail = new Status(IStatus.INFO, Activator.ID, IStatusCodes.ALTERED_PARTIAL_UNINSTALL, NLS.bind(Messages.PlanAnalyzer_PartialUninstall, getIUString(iusRemoved[i])), null); + report.addStatus(iusRemoved[i], fail); + report.addSummaryStatus(fail); + } + } + } + + // Now process the side effects + for (Entry entry : plan.getSideEffectChanges().entrySet()) { + IInstallableUnit iu = entry.getKey(); + RequestStatus rs = (RequestStatus) entry.getValue(); + if (rs.getInitialRequestType() == RequestStatus.ADDED) { + report.addStatus(iu, new Status(rs.getSeverity(), Activator.ID, IStatusCodes.ALTERED_SIDE_EFFECT_INSTALL, NLS.bind(Messages.PlanAnalyzer_SideEffectInstall, getIUString(iu)), null)); + } else { + report.addStatus(iu, new Status(rs.getSeverity(), Activator.ID, IStatusCodes.ALTERED_SIDE_EFFECT_REMOVE, NLS.bind(Messages.PlanAnalyzer_SideEffectUninstall, getIUString(iu)), null)); + } + } + + return report; + + } + + private static String getIUString(IInstallableUnit iu) { + if (iu == null) + return Messages.PlanAnalyzer_Items; + // Get the iu name in the default locale + String name = iu.getProperty(IInstallableUnit.PROP_NAME, null); + if (name != null) + return name; + return iu.getId(); + } + + private static boolean nothingToDo(ProfileChangeRequest request) { + return request.getAddedInstallableUnits().length == 0 && request.getRemovedInstallableUnits().length == 0 && request.getInstallableUnitProfilePropertiesToAdd().size() == 0 && request.getInstallableUnitProfilePropertiesToRemove().size() == 0; + } +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/PlannerResolutionJob.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/PlannerResolutionJob.java new file mode 100644 index 000000000..14ed2c330 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/PlannerResolutionJob.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.operations; + +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.operations.*; + +/** + * Class representing a provisioning profile plan + * + * @since 2.0 + */ +public class PlannerResolutionJob extends ProvisioningJob implements IProfileChangeJob { + + ProfileChangeRequest request; + String profileId; + IProvisioningPlan plan; + MultiStatus additionalStatus; + ResolutionResult report; + ProvisioningContext provisioningContext; + + public static MultiStatus getProfileChangeRequestAlteredStatus() { + return PlanAnalyzer.getProfileChangeAlteredStatus(); + } + + public PlannerResolutionJob(String label, ProvisioningSession session, String profileId, ProfileChangeRequest request, ProvisioningContext provisioningContext, MultiStatus additionalStatus) { + super(label, session); + this.request = request; + this.profileId = profileId; + if (provisioningContext == null) + this.provisioningContext = new ProvisioningContext(); + else + this.provisioningContext = provisioningContext; + Assert.isNotNull(additionalStatus); + this.additionalStatus = additionalStatus; + } + + public IProvisioningPlan getProvisioningPlan() { + return plan; + } + + public ProfileChangeRequest getProfileChangeRequest() { + return request; + } + + public ProvisioningContext getProvisioningContext() { + return provisioningContext; + } + + public void setProvisioningContext(ProvisioningContext context) { + this.provisioningContext = context; + } + + public IStatus runModal(IProgressMonitor monitor) { + plan = getSession().getPlanner().getProvisioningPlan(request, provisioningContext, monitor); + if (plan == null) { + return new Status(IStatus.ERROR, Activator.ID, Messages.PlannerResolutionJob_NullProvisioningPlan); + } + return plan.getStatus(); + + } + + public ResolutionResult getResolutionResult() { + if (report == null) { + report = PlanAnalyzer.computeResolutionResult(request, plan, additionalStatus); + } + return report; + } + + public String getProfileId() { + return profileId; + } +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/ResolutionResult.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/ResolutionResult.java new file mode 100644 index 000000000..0d0d90bab --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/ResolutionResult.java @@ -0,0 +1,125 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.internal.p2.operations; + +import java.util.HashMap; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; + +/** + * ResolutionResult describes problems in a provisioning plan in a structured + * way that can be presented to a user. + * + * @since 2.0 + */ +public class ResolutionResult { + private static final String NESTING_INDENT = " "; //$NON-NLS-1$ + + private final HashMap iuToStatusMap = new HashMap(); + private MultiStatus summaryStatus; + + public IStatus getSummaryStatus() { + if (summaryStatus != null) + return summaryStatus; + return Status.OK_STATUS; + } + + public void addSummaryStatus(IStatus status) { + if (summaryStatus == null) { + summaryStatus = new MultiStatus(Activator.ID, 0, Messages.ResolutionResult_SummaryStatus, null); + } + summaryStatus.add(status); + } + + public IStatus statusOf(IInstallableUnit iu) { + return iuToStatusMap.get(iu); + } + + public void addStatus(IInstallableUnit iu, IStatus status) { + MultiStatus iuSummaryStatus = iuToStatusMap.get(iu); + if (iuSummaryStatus == null) { + iuSummaryStatus = new MultiStatus(Activator.ID, IStatusCodes.IU_REQUEST_ALTERED, new IStatus[] {status}, getIUString(iu), null); + } else + iuSummaryStatus.add(status); + } + + private String getIUString(IInstallableUnit iu) { + if (iu == null) + return Messages.PlanAnalyzer_Items; + // Get the iu name in the default locale + String name = iu.getProperty(IInstallableUnit.PROP_NAME, null); + if (name != null) + return name; + return iu.getId(); + } + + public String getSummaryReport() { + if (summaryStatus != null) { + StringBuffer buffer = new StringBuffer(); + appendDetailText(summaryStatus, buffer, -1, false); + return buffer.toString(); + } + return ""; //$NON-NLS-1$ + } + + // Answers null if there is nothing to say about the ius + public String getDetailedReport(IInstallableUnit[] ius) { + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < ius.length; i++) { + MultiStatus iuStatus = iuToStatusMap.get(ius[i]); + if (iuStatus != null) + appendDetailText(iuStatus, buffer, 0, true); + } + String report = buffer.toString(); + if (report.length() == 0) + return null; + return report; + } + + void appendDetailText(IStatus status, StringBuffer buffer, int indent, boolean includeTopLevelMessage) { + if (includeTopLevelMessage) { + for (int i = 0; i < indent; i++) + buffer.append(NESTING_INDENT); + if (status.getMessage() != null) + buffer.append(status.getMessage()); + } + Throwable t = status.getException(); + if (t != null) { + // A provision (or core) exception occurred. Get its status message or if none, its top level message. + // Indent by one more level (note the <=) + buffer.append('\n'); + for (int i = 0; i <= indent; i++) + buffer.append(NESTING_INDENT); + if (t instanceof CoreException) { + IStatus exceptionStatus = ((CoreException) t).getStatus(); + if (exceptionStatus != null && exceptionStatus.getMessage() != null) + buffer.append(exceptionStatus.getMessage()); + else { + String details = t.getLocalizedMessage(); + if (details != null) + buffer.append(details); + } + } else { + String details = t.getLocalizedMessage(); + if (details != null) + buffer.append(details); + } + } + // Now print the children status info (if there are children) + IStatus[] children = status.getChildren(); + for (int i = 0; i < children.length; i++) { + if (buffer.length() > 0) + buffer.append('\n'); + appendDetailText(children[i], buffer, indent + 1, true); + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/SizingPhaseSet.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/SizingPhaseSet.java new file mode 100644 index 000000000..1b433695b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/SizingPhaseSet.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +/** + * + */ +package org.eclipse.equinox.internal.p2.operations; + +import org.eclipse.equinox.internal.p2.engine.Phase; +import org.eclipse.equinox.internal.p2.engine.PhaseSet; +import org.eclipse.equinox.internal.p2.engine.phases.Sizing; + + +public class SizingPhaseSet extends PhaseSet { + + private static Sizing sizing; + + public SizingPhaseSet() { + super(new Phase[] {sizing = new Sizing(100, Messages.SizingPhaseSet_PhaseSetName)}); + } + + public Sizing getSizing() { + return sizing; + } +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/messages.properties b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/messages.properties new file mode 100644 index 000000000..24c99f571 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/internal/p2/operations/messages.properties @@ -0,0 +1,44 @@ +############################################################################### +# Copyright (c) 2009 IBM Corporation and others. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# IBM Corporation - initial API and implementation +############################################################################### +InstallOperation_ComputeProfileChangeProgress=Checking the install request +InstallOperation_InstallJobName=Installing Software +InstallOperation_ResolveJobName=Computing install requirements +ProfileChangeOperation_NoProfileChangeRequest=Could not interpret the installation request. +ProfileChangeOperation_ResolveTaskName=Analyzing the install operation +ProvisioningJob_GenericErrorStatusMessage=Error encountered while running {0} +ProvisioningSession_AgentNotFound=No provisioning agent could be found +ProvisioningSession_InstallPlanConfigurationError=A problem was encountered while preparing the system for the installation +PlanAnalyzer_IgnoringInstall="{0}" is not applicable to the current configuration and will not be installed. +PlanAnalyzer_LockedImpliedUpdate0={0} will be ignored because it is already installed, and updates are not permitted. +PlanAnalyzer_PartialInstall="{0}" is already present because other installed software requires it. It will be added to the installed software list. +PlanAnalyzer_PartialUninstall= "{0}" cannot be fully uninstalled because other installed software requires it. The parts that are not required will be uninstalled. +PlanAnalyzer_SideEffectInstall="{0}" will also be installed in order to complete this operation. +PlanAnalyzer_SideEffectUninstall="{0}" must be uninstalled in order to complete this operation. +PlannerResolutionJob_NullProvisioningPlan=Could not obtain provisioning plan. No details were available. +PlanAnalyzer_IgnoringImpliedDowngrade="{0}" will be ignored because a newer version is already installed. +PlanAnalyzer_ImpliedUpdate="{0}" is already installed, so an update will be performed instead. +PlanAnalyzer_Items=Items +PlanAnalyzer_NothingToDo=Cannot complete the request. See the error log for details. +PlanAnalyzer_NoUpdates=No updates were found. +PlanAnalyzer_AlreadyInstalled="{0}" will be ignored because it is already installed. +PlanAnalyzer_AnotherOperationInProgress=Cannot continue the operation. There is another install operation in progress. +PlanAnalyzer_RequestAltered=Your original request has been modified. +PlanAnalyzer_UnexpectedError=Unexpected error code {0} encountered for {1}. +RepositoryTracker_DuplicateLocation=Duplicate location +RepositoryTracker_InvalidLocation=The location "{0}" is not a valid software site location. +ResolutionResult_SummaryStatus=Operation details +SizingPhaseSet_PhaseSetName=Compute sizes + +UninstallOperation_ProvisioningJobName=Uninstalling Software +UninstallOperation_ResolveJobName=Calculating Uninstall Validity +UpdateOperation_ProfileChangeRequestProgress=Computing update request +UpdateOperation_ResolveJobName=Computing Update Requirements +UpdateOperation_UpdateJobName=Updating Software diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/IProfileChangeJob.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/IProfileChangeJob.java new file mode 100644 index 000000000..c415ed5b6 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/IProfileChangeJob.java @@ -0,0 +1,29 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.p2.operations; + +/** + * Interface for a provisioning job that operates on a + * profile. + * + * @since 2.0 + */ +public interface IProfileChangeJob { + + /** + * Return the string id of the profile involved in this job. + * + * @return the id of the profile + */ + public String getProfileId(); + +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/InstallOperation.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/InstallOperation.java new file mode 100644 index 000000000..b20f96edb --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/InstallOperation.java @@ -0,0 +1,145 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.p2.operations; + +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.operations.*; +import org.eclipse.equinox.internal.provisional.p2.director.PlannerHelper; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.query.UserVisibleRootQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.metadata.query.PatchQuery; +import org.eclipse.equinox.p2.query.IQueryResult; + +/** + * An InstallOperation describes an operation that installs IInstallableUnits into + * a profile. + * + * The following snippet shows how one might use an InstallOperation to perform a synchronous resolution and + * then kick off an install in the background: + * + *
    + * InstallOperation op = new InstallOperation(session, new IInstallableUnit [] { myIU });
    + * IStatus result = op.resolveModal(monitor);
    + * if (result.isOK()) {
    + *   op.getProvisioningJob(monitor).schedule();
    + * }
    + * 
    + * + * @since 2.0 + * @see ProfileChangeOperation + * @noextend This class is not intended to be subclassed by clients. + */ +public class InstallOperation extends ProfileChangeOperation { + + private IInstallableUnit[] toInstall; + + /** + * Create an install operation on the specified provisioning session that installs + * the supplied IInstallableUnits. Unless otherwise specified, the operation will + * be associated with the currently running profile. + * + * @param session the session to use for obtaining provisioning services + * @param toInstall the IInstallableUnits to be installed into the profile. + */ + public InstallOperation(ProvisioningSession session, IInstallableUnit[] toInstall) { + super(session); + this.toInstall = toInstall; + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.ProfileChangeOperation#computeProfileChangeRequest(org.eclipse.core.runtime.MultiStatus, org.eclipse.core.runtime.IProgressMonitor) + */ + protected void computeProfileChangeRequest(MultiStatus status, IProgressMonitor monitor) { + request = ProfileChangeRequest.createByProfileId(profileId); + IProfile profile; + profile = session.getProfileRegistry().getProfile(profileId); + SubMonitor sub = SubMonitor.convert(monitor, Messages.InstallOperation_ComputeProfileChangeProgress, toInstall.length); + for (int i = 0; i < toInstall.length; i++) { + // If the user is installing a patch, we mark it optional. This allows + // the patched IU to be updated later by removing the patch. + if (PatchQuery.isPatch(toInstall[i])) + request.setInstallableUnitInclusionRules(toInstall[i], PlannerHelper.createOptionalInclusionRule(toInstall[i])); + + // Check to see if it is already installed. This may alter the request. + IQueryResult alreadyInstalled = profile.query(new InstallableUnitQuery(toInstall[i].getId()), null); + // TODO ideally we should only do this check if the iu is a singleton, but in practice many iu's that should + // be singletons are not, so we don't check this (yet) + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=230878 + if (!alreadyInstalled.isEmpty()) { // && installedIU.isSingleton() + IInstallableUnit installedIU = alreadyInstalled.iterator().next(); + int compareTo = toInstall[i].getVersion().compareTo(installedIU.getVersion()); + // If the iu is a newer version of something already installed, consider this an + // update request + if (compareTo > 0) { + boolean lockedForUpdate = false; + String value = profile.getInstallableUnitProperty(installedIU, IProfile.PROP_PROFILE_LOCKED_IU); + if (value != null) + lockedForUpdate = (Integer.parseInt(value) & IProfile.LOCK_UPDATE) == IProfile.LOCK_UPDATE; + if (lockedForUpdate) { + // Add a status telling the user that this implies an update, but the + // iu should not be updated + status.merge(PlanAnalyzer.getStatus(IStatusCodes.ALTERED_IGNORED_IMPLIED_UPDATE, toInstall[i])); + } else { + request.addInstallableUnits(toInstall[i]); + request.removeInstallableUnit(installedIU); + // Add a status informing the user that the update has been inferred + status.merge(PlanAnalyzer.getStatus(IStatusCodes.ALTERED_IMPLIED_UPDATE, toInstall[i])); + // Mark it as a root if it hasn't been already + if (!UserVisibleRootQuery.isUserVisible(installedIU, profile)) + request.setInstallableUnitProfileProperty(toInstall[i], IProfile.PROP_PROFILE_ROOT_IU, Boolean.toString(true)); + } + } else if (compareTo < 0) { + // An implied downgrade. We will not put this in the plan, add a status informing the user + status.merge(PlanAnalyzer.getStatus(IStatusCodes.ALTERED_IGNORED_IMPLIED_DOWNGRADE, toInstall[i])); + } else { + // if (rootMarkerKey != null) { + if (UserVisibleRootQuery.isUserVisible(installedIU, profile)) + // It is already a root, nothing to do. We tell the user it was already installed + status.merge(PlanAnalyzer.getStatus(IStatusCodes.ALTERED_IGNORED_ALREADY_INSTALLED, toInstall[i])); + else { + // It was already installed but not as a root. Tell the user that parts of it are already installed and mark + // it as a root. + status.merge(PlanAnalyzer.getStatus(IStatusCodes.ALTERED_PARTIAL_INSTALL, toInstall[i])); + request.setInstallableUnitProfileProperty(toInstall[i], IProfile.PROP_PROFILE_ROOT_IU, Boolean.toString(true)); + } + // } + } + } else { + // Install it and mark as a root + request.addInstallableUnits(new IInstallableUnit[] {toInstall[i]}); + // if (rootMarkerKey != null) + request.setInstallableUnitProfileProperty(toInstall[i], IProfile.PROP_PROFILE_ROOT_IU, Boolean.toString(true)); + } + sub.worked(1); + } + sub.done(); + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.ProfileChangeOperation#getResolveJobName() + */ + protected String getResolveJobName() { + return Messages.InstallOperation_ResolveJobName; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.ProfileChangeOperation#getProvisioningJobName() + */ + protected String getProvisioningJobName() { + return Messages.InstallOperation_InstallJobName; + + } +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProfileChangeOperation.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProfileChangeOperation.java new file mode 100644 index 000000000..7667e88ec --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProfileChangeOperation.java @@ -0,0 +1,353 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.p2.operations; + +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.operations.*; +import org.eclipse.equinox.internal.p2.operations.Messages; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; + +/** + * ProfileChangeOperation describes a provisioning operation that modifies a profile. + * The operation must first be resolved, followed by the actual provisioning + * work being performed. This two-pass nature of the ProfileChangeOperation allows + * resolution status to be reported to a client to determine whether the operation + * should proceed. Each phase of the operation can be performed synchronously or in + * the background as a job. To perform the operation synchronously: + * + *
    + *     IStatus result = op.resolveModal(monitor);
    + *     if (result.isOK())
    + *       op.getProvisioningJob(null).runModal(monitor);
    + *     else {
    + *       // interpret the result
    + *     }
    + *  
    + * + * To perform the resolution synchronously and the provisioning job in the + * background: + * + *
    + *     IStatus status = op.resolveModal(monitor);
    + *     if (status.isOK()) {
    + *       ProvisioningJob job = op.getProvisioningJob(monitor);
    + *       job.schedule();
    + *     } else {
    + *       // interpret the result
    + *     }
    + *  
    + * + * To resolve in the background and perform the job when it is complete: + * + *
    + *     ProvisioningJob job = op.getResolveJob(monitor);
    + *     job.addJobChangeListener(new JobChangeAdapter() {
    + *       public void done (JobChangeEvent event) {
    + *         if (event.getResult().isOK() {
    + *            op.getProvisioningJob(monitor).schedule();
    + *         } else {
    + *            // interpret the result
    + *         }
    + *       }
    + *     });
    + *     job.schedule();
    + *     
    + *  
    + * + * In general, it is expected that clients create a new ProfileChangeOperation if + * the resolution result of the current operation is not satisfactory. However, + * subclasses may prescribe a different life cycle where appropriate. + * + * When retrieving the resolution and provisioning jobs managed by this operation, + * a client may supply a progress monitor to be used by the job. When the job is + * run by the platform job manager, both the platform job manager progress indicator + * and the monitor supplied by the client will be updated. + * + * @noextend This class is not intended to be subclassed by clients. + * @since 2.0 + */ +public abstract class ProfileChangeOperation implements IProfileChangeJob { + + ProvisioningSession session; + String profileId; + ProvisioningContext context; + MultiStatus noChangeRequest; + PlannerResolutionJob job; + ProfileChangeRequest request; + + /** + * Create an operation using the provided provisioning session. + * Unless otherwise specified by the client, the operation is + * performed on the currently running profile. + * + * @param session the provisioning session providing the services + */ + protected ProfileChangeOperation(ProvisioningSession session) { + this.session = session; + this.profileId = IProfileRegistry.SELF; + } + + /** + * Resolve the operation in the current thread using the specified progress + * monitor. Return a status describing the result of the resolution. + * + * @param monitor the progress monitor to use + * @return a status describing the resolution results + */ + public final IStatus resolveModal(IProgressMonitor monitor) { + if (monitor == null) + monitor = new NullProgressMonitor(); + prepareToResolve(); + makeResolveJob(monitor); + if (job != null) { + job.runModal(monitor); + } + return getResolutionResult(); + + } + + /** + * Set the id of the profile that will be modified by this operation. + * @param id the profile id + */ + public void setProfileId(String id) { + this.profileId = id; + } + + /** + * Return a job that can be used to resolve this operation in the background. + * + * @param monitor a progress monitor that should be used to report the job's progress in addition + * to the standard job progress reporting. Can be null. If provided, this monitor + * will be called from a background thread. + * + * @return a job that can be scheduled to perform the provisioning operation. + */ + public final ProvisioningJob getResolveJob(IProgressMonitor monitor) { + SubMonitor mon = SubMonitor.convert(monitor, Messages.ProfileChangeOperation_ResolveTaskName, 1000); + prepareToResolve(); + makeResolveJob(mon.newChild(100)); + job.setAdditionalProgressMonitor(mon.newChild(900)); + return job; + } + + /** + * Perform any processing that must occur just before resolving this operation. + */ + protected void prepareToResolve() { + // default is to do nothing + } + + private void makeResolveJob(IProgressMonitor monitor) { + noChangeRequest = PlanAnalyzer.getProfileChangeAlteredStatus(); + if (session.hasScheduledOperationsFor(profileId)) { + noChangeRequest.add(PlanAnalyzer.getStatus(IStatusCodes.OPERATION_ALREADY_IN_PROGRESS, null)); + } else { + computeProfileChangeRequest(noChangeRequest, monitor); + } + if (request == null) { + if (noChangeRequest.getChildren().length == 0) + // No explanation for failure was provided. It shouldn't happen, but... + noChangeRequest = new MultiStatus(Activator.ID, IStatusCodes.UNEXPECTED_NOTHING_TO_DO, new IStatus[] {PlanAnalyzer.getStatus(IStatusCodes.UNEXPECTED_NOTHING_TO_DO, null)}, Messages.ProfileChangeOperation_NoProfileChangeRequest, null); + return; + } + createPlannerResolutionJob(); + } + + /** + * Compute the profile change request for this operation, adding any relevant intermediate status + * to the supplied status. + * + * @param status a multi-status to be used to add relevant status. If a profile change request cannot + * be computed for any reason, a status should be added to explain the problem. + * + * @param monitor the progress monitor to use for computing the profile change request + */ + protected abstract void computeProfileChangeRequest(MultiStatus status, IProgressMonitor monitor); + + private void createPlannerResolutionJob() { + job = new PlannerResolutionJob(getResolveJobName(), session, profileId, request, context, noChangeRequest); + } + + /** + * Return an appropriate name for the resolution job. + * + * @return the resolution job name. + */ + protected abstract String getResolveJobName(); + + /** + * Return an appropriate name for the provisioning job. + * + * @return the provisioning job name. + */ + protected abstract String getProvisioningJobName(); + + /** + * Return a status indicating the result of resolving this + * operation. A null return indicates that + * resolving has not occurred yet. + * + * @return the status of the resolution, or null + * if resolution has not yet occurred. + */ + public IStatus getResolutionResult() { + if (job != null && job.getResolutionResult() != null) + return job.getResolutionResult().getSummaryStatus(); + if (request == null && noChangeRequest != null) { + // If there is only one child message, use the specific message + if (noChangeRequest.getChildren().length == 1) + return noChangeRequest.getChildren()[0]; + return noChangeRequest; + } + return null; + } + + /** + * Return a string that can be used to describe the results of the resolution + * to a client. + * + * @return a string describing the resolution details, or null if the + * operation has not been resolved. + */ + public String getResolutionDetails() { + if (job != null && job.getResolutionResult() != null) + return job.getResolutionResult().getSummaryReport(); + return null; + + } + + /** + * Return a string that describes the specific resolution results + * related to the supplied {@link IInstallableUnit}. + * + * @param iu the IInstallableUnit for which resolution details are requested + * + * @return a string describing the results for the installable unit, or null if + * there are no specific results available for the installable unit. + */ + public String getResolutionDetails(IInstallableUnit iu) { + if (job != null && job.getResolutionResult() != null) + return job.getResolutionResult().getDetailedReport(new IInstallableUnit[] {iu}); + return null; + + } + + /** + * Return the provisioning plan obtained by resolving the receiver. + * + * @return the provisioning plan. This may be null if the operation + * has not been resolved, or if a plan could not be obtained when attempting to + * resolve. If the plan is null and the operation has been resolved, then the + * resolution result will explain the problem. + * + * @see #hasResolved() + * @see #getResolutionResult() + */ + public IProvisioningPlan getProvisioningPlan() { + if (job != null) + return job.getProvisioningPlan(); + return null; + } + + /** + * Return the profile change request that describes the receiver. + * + * @return the profile change request. This may be null if the operation + * has not been resolved, or if a profile change request could not be assembled given + * the operation's state. If the profile change request is null and the operation has + * been resolved, the the resolution result will explain the problem. + * + * @see #hasResolved() + * @see #getResolutionResult() + */ + public ProfileChangeRequest getProfileChangeRequest() { + if (job != null) + return job.getProfileChangeRequest(); + return null; + } + + /** + * Return a provisioning job that can be used to perform the resolved operation. + * + * @param monitor a progress monitor that should be used to report the job's progress in addition + * to the standard job progress reporting. Can be null. If provided, this monitor + * will be called from a background thread. + * + * @return a job that can be used to perform the provisioning operation. This may be null + * if the operation has not been resolved, or if a plan could not be obtained when attempting to + * resolve. If the job is null and the operation has been resolved, then the resolution result + * will explain the problem. + * + * @see #hasResolved() + * @see #getResolutionResult() + */ + public ProvisioningJob getProvisioningJob(IProgressMonitor monitor) { + IStatus status = getResolutionResult(); + if (status.getSeverity() != IStatus.CANCEL && status.getSeverity() != IStatus.ERROR) { + if (job.getProvisioningPlan() != null) { + ProfileModificationJob pJob = new ProfileModificationJob(getProvisioningJobName(), session, profileId, job.getProvisioningPlan(), context); + pJob.setAdditionalProgressMonitor(monitor); + return pJob; + } + } + return null; + } + + /** + * Set the provisioning context that should be used to resolve and perform the provisioning for + * the operation. This must be set before an attempt is made to resolve the operation + * for it to have any effect. + * + * @param context the provisioning context. + */ + public void setProvisioningContext(ProvisioningContext context) { + this.context = context; + if (job != null) + job.setProvisioningContext(context); + } + + /** + * Get the provisioning context that will be used to resolve and perform the provisioning for + * the operation. + * + * @return the provisioning context + */ + public ProvisioningContext getProvisioningContext() { + return context; + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.IProfileChangeJob#getProfileId() + */ + public String getProfileId() { + return profileId; + } + + /** + * Return a boolean indicating whether the operation has been resolved. This method + * should be used to determine whether a client can expect to retrieve a profile + * change request, provisioning plan, or resolution result. It is possible that this + * method return false while resolution is taking place if it is performed + * in the background. + * + * @return true if the operation has been resolved, false + * if it has not resolved. + */ + public boolean hasResolved() { + return getResolutionResult() != null; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProfileModificationJob.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProfileModificationJob.java new file mode 100644 index 000000000..24a3bf888 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProfileModificationJob.java @@ -0,0 +1,114 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.operations; + +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.engine.PhaseSet; +import org.eclipse.equinox.p2.engine.*; + +/** + * A job that modifies a profile according to a specified provisioning plan. + * + * @since 2.0 + * @noextend This class is not intended to be subclassed by clients. + */ +public class ProfileModificationJob extends ProvisioningJob implements IProfileChangeJob { + + IProvisioningPlan plan; + String profileId; + PhaseSet phaseSet = new DefaultPhaseSet(); + ProvisioningContext provisioningContext; + int restartPolicy = ProvisioningJob.RESTART_OR_APPLY; + private String taskName; + + /** + * Create a job that will update a profile according to the specified provisioning plan. + * + * @param name the name of the job + * @param session the provisioning session to use to obtain provisioning services + * @param profileId the id of the profile to be altered + * @param plan the provisioning plan describing how the profile is to be altered + * @param context the provisioning context describing how the operation is to be performed + */ + public ProfileModificationJob(String name, ProvisioningSession session, String profileId, IProvisioningPlan plan, ProvisioningContext context) { + super(name, session); + this.plan = plan; + this.profileId = profileId; + this.provisioningContext = context; + } + + /** + * Set the phase set to be used when running the provisioning plan. This method need only + * be used when the default phase set is not sufficient. For example, clients could + * use this method to perform a sizing or to download artifacts without provisioning them. + * + * @param phaseSet the provisioning phases to be run during provisioning. + */ + public void setPhaseSet(PhaseSet phaseSet) { + this.phaseSet = phaseSet; + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.IProfileChangeJob#getProfileId() + */ + public String getProfileId() { + return profileId; + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.ProvisioningJob#runModal(org.eclipse.core.runtime.IProgressMonitor) + */ + public IStatus runModal(IProgressMonitor monitor) { + String task = taskName; + IStatus status = Status.OK_STATUS; + if (task == null) + task = getName(); + monitor.beginTask(task, 1000); + try { + status = getSession().performProvisioningPlan(plan, phaseSet, provisioningContext, new SubProgressMonitor(monitor, 1000)); + } finally { + monitor.done(); + } + return status; + } + + /** + * Sets the top level task name for progress when running this operation. + * + * @param label the label to be used for the task name + */ + public void setTaskName(String label) { + this.taskName = label; + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.ProvisioningJob#getRestartPolicy() + */ + public int getRestartPolicy() { + return restartPolicy; + } + + /** + * Set the restart policy that describes whether restart is needed after + * performing this job. + * + * @param policy an integer describing the restart policy + * @see ProvisioningJob#RESTART_NONE + * @see ProvisioningJob#RESTART_ONLY + * @see ProvisioningJob#RESTART_OR_APPLY + */ + public void setRestartPolicy(int policy) { + restartPolicy = policy; + } +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProvisioningJob.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProvisioningJob.java new file mode 100644 index 000000000..3e834b4a5 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProvisioningJob.java @@ -0,0 +1,227 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.operations; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import org.eclipse.core.runtime.*; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.equinox.internal.p2.operations.Activator; +import org.eclipse.equinox.internal.p2.operations.Messages; +import org.eclipse.osgi.util.NLS; + +/** + * Abstract class representing provisioning jobs. Provisioning jobs + * can be run in the background by scheduling them, or they can + * be run by a client in a modal context. An additional progress monitor + * can be set into the job for progress reporting. + * + * @since 2.0 + */ +public abstract class ProvisioningJob extends Job { + + /** + * Class for multiplexing progress across multiple progress monitors. + */ + private static class DoubleProgressMonitor extends ProgressMonitorWrapper { + + IProgressMonitor additionalMonitor; + + protected DoubleProgressMonitor(IProgressMonitor monitor1, IProgressMonitor monitor2) { + super(monitor1); + additionalMonitor = monitor2; + } + + public void beginTask(String name, int totalWork) { + super.beginTask(name, totalWork); + additionalMonitor.beginTask(name, totalWork); + } + + public void clearBlocked() { + super.clearBlocked(); + if (additionalMonitor instanceof IProgressMonitorWithBlocking) + ((IProgressMonitorWithBlocking) additionalMonitor).clearBlocked(); + } + + public void done() { + super.done(); + additionalMonitor.done(); + } + + public void internalWorked(double work) { + super.internalWorked(work); + additionalMonitor.internalWorked(work); + } + + public boolean isCanceled() { + if (super.isCanceled()) + return true; + return additionalMonitor.isCanceled(); + } + + public void setBlocked(IStatus reason) { + super.setBlocked(reason); + if (additionalMonitor instanceof IProgressMonitorWithBlocking) + ((IProgressMonitorWithBlocking) additionalMonitor).setBlocked(reason); + } + + public void setCanceled(boolean b) { + super.setCanceled(b); + additionalMonitor.setCanceled(b); + } + + public void setTaskName(String name) { + super.setTaskName(name); + additionalMonitor.setTaskName(name); + } + + public void subTask(String name) { + super.subTask(name); + additionalMonitor.subTask(name); + } + + public void worked(int work) { + super.worked(work); + additionalMonitor.worked(work); + } + } + + /** + * Constant which indicates that the job does not require a restart + * upon completion. This constant is typically used for operations that + * do not modify the running profile. + * + * @since 2.0 + */ + public static final int RESTART_NONE = 1; + + /** + * Constant which indicates that the job requires the user to either + * restart or apply the configuration changes in order to pick up the + * changes performed by the job. This constant is typically used for + * operations that modify the running profile. + * + * @since 2.0 + */ + public static final int RESTART_OR_APPLY = 2; + /** + * Constant which indicates that the job requires the user to restart + * in order to pick up the changes performed by the job. This constant + * is typically used for operations that modify the running profile but don't + * handle dynamic changes without restarting the workbench. + * + * @since 2.0 + */ + public static final int RESTART_ONLY = 3; + + private ProvisioningSession session; + private IProgressMonitor additionalMonitor; + + /** + * Create a provisioning job with the given name that uses the + * provided provisioning session for retrieving any services + * needed. + * + * @param name the name of the job + * @param session the session providing the services + */ + public ProvisioningJob(String name, ProvisioningSession session) { + super(name); + this.session = session; + } + + /** + * Return the provisioning session that is used by the receiver + * when retrieving necessary provisioning services. + * + * @return the session + * @see ProvisioningSession + */ + protected ProvisioningSession getSession() { + return session; + } + + private IProgressMonitor getCombinedProgressMonitor(IProgressMonitor mon1, IProgressMonitor mon2) { + if (mon1 == null) + return mon2; + if (mon2 == null) + return mon1; + return new DoubleProgressMonitor(mon1, mon2); + } + + public void setAdditionalProgressMonitor(IProgressMonitor monitor) { + additionalMonitor = monitor; + } + + /** + * Executes this job. Returns the result of the execution. + * This method is overridden to look for a wrapped progress monitor for + * reporting progress. + * + * @noreference This method is not intended to be referenced by clients. + * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) + * + */ + public final IStatus run(IProgressMonitor monitor) { + IProgressMonitor wrappedMonitor = getCombinedProgressMonitor(monitor, additionalMonitor); + IStatus status = Status.OK_STATUS; + try { + status = runModal(wrappedMonitor); + } catch (OperationCanceledException e) { + status = Status.CANCEL_STATUS; + } + return status; + } + + /** + * Perform the specific work involved in running this job in + * the current thread. This method can be called directly by + * clients, or in the course of running the job in the + * background. + * + * @param monitor + * the progress monitor to use for the operation + * + * @return a status indicating the result of the operation. + * + */ + public abstract IStatus runModal(IProgressMonitor monitor); + + /** + * Return the restart policy that is appropriate for this job. + * + * @return a constant indicating the restart policy + * + * @see #RESTART_NONE + * @see #RESTART_ONLY + * @see #RESTART_OR_APPLY + */ + public int getRestartPolicy() { + return RESTART_NONE; + } + + /** + * Return an error status that can be used to report the specified exception. + * + * @param message the message that should be used in the status + * @param e the exception to be reported + * @return a status that can be used to describe the exception + */ + protected IStatus getErrorStatus(String message, ProvisionException e) { + if (message == null) + if (e == null) + message = NLS.bind(Messages.ProvisioningJob_GenericErrorStatusMessage, getName()); + else + message = e.getLocalizedMessage(); + return new Status(IStatus.ERROR, Activator.ID, message, e); + } + +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProvisioningSession.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProvisioningSession.java new file mode 100644 index 000000000..9a91bdc5a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/ProvisioningSession.java @@ -0,0 +1,317 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.p2.operations; + +import java.io.IOException; +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.core.runtime.jobs.*; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.internal.p2.engine.PhaseSet; +import org.eclipse.equinox.internal.p2.operations.*; +import org.eclipse.equinox.internal.provisional.configurator.Configurator; +import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.query.UserVisibleRootQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; + +/** + * ProvisioningSession provides the context for a provisioning session, including + * the provisioning services that should be used. It also provides utility + * methods for commonly performed provisioning tasks. + * + * @since 2.0 + * @noextend This class is not intended to be subclassed by clients. + */ +public class ProvisioningSession { + private IProvisioningAgent agent; + + private Set scheduledJobs = Collections.synchronizedSet(new HashSet()); + + /** + * A constant indicating that there was nothing to size (there + * was no valid plan that could be used to compute + * size). + */ + public static final long SIZE_NOTAPPLICABLE = -3L; + /** + * Indicates that the size is unavailable (an + * attempt was made to compute size but it failed) + */ + public static final long SIZE_UNAVAILABLE = -2L; + /** + * Indicates that the size is currently unknown + */ + public static final long SIZE_UNKNOWN = -1L; + + /** + * A status code used to indicate that there were no updates found when + * looking for updates. + */ + public static final int STATUS_NOTHING_TO_UPDATE = IStatusCodes.NOTHING_TO_UPDATE; + + /** + * A status code used to indicate that a repository location was not valid. + */ + public static final int STATUS_INVALID_REPOSITORY_LOCATION = IStatusCodes.INVALID_REPOSITORY_LOCATION; + + /** + * Create a provisioning session using the services of the supplied agent. + * @param agent the provisioning agent that supplies services. Must not be null. + */ + public ProvisioningSession(IProvisioningAgent agent) { + Assert.isNotNull(agent, Messages.ProvisioningSession_AgentNotFound); + this.agent = agent; + } + + /** + * Return the provisioning agent used to retrieve provisioning services. + * @return the provisioning agent + */ + public IProvisioningAgent getProvisioningAgent() { + return agent; + } + + /** + * Return the agent location for this session + * @return the agent location + */ + public IAgentLocation getAgentLocation() { + return (IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME); + } + + /** + * Return the artifact repository manager for this session + * @return the repository manager + */ + public IArtifactRepositoryManager getArtifactRepositoryManager() { + return (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME); + } + + /** + * Return the metadata repository manager for this session + * @return the repository manager + */ + public IMetadataRepositoryManager getMetadataRepositoryManager() { + return (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME); + } + + /** + * Return the profile registry for this session + * @return the profile registry + */ + public IProfileRegistry getProfileRegistry() { + return (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME); + } + + /** + * Return the provisioning engine for this session + * @return the provisioning engine + */ + public IEngine getEngine() { + return (IEngine) agent.getService(IEngine.SERVICE_NAME); + } + + /** + * Return the provisioning event bus used for dispatching events. + * @return the event bus + */ + public IProvisioningEventBus getProvisioningEventBus() { + return (IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME); + } + + /** + * Return the planner used for this session + * @return the planner + */ + public IPlanner getPlanner() { + return (IPlanner) agent.getService(IPlanner.SERVICE_NAME); + } + + /** + * Get sizing information about the specified plan. + * + * @param plan the provisioning plan + * @param context the provisioning context to be used for the sizing + * @param monitor the progress monitor + * + * @return a long integer describing the disk size required for the provisioning plan. + * + * @see #SIZE_UNKNOWN + * @see #SIZE_UNAVAILABLE + * @see #SIZE_NOTAPPLICABLE + */ + public long getSize(IProvisioningPlan plan, ProvisioningContext context, IProgressMonitor monitor) { + // If there is nothing to size, return 0 + if (plan == null) + return SIZE_NOTAPPLICABLE; + if (countPlanElements(plan) == 0) + return 0; + long installPlanSize = 0; + SubMonitor mon = SubMonitor.convert(monitor, 300); + if (plan.getInstallerPlan() != null) { + SizingPhaseSet set = new SizingPhaseSet(); + IStatus status = getEngine().perform(plan.getInstallerPlan(), set, mon.newChild(100)); + if (status.isOK()) + installPlanSize = set.getSizing().getDiskSize(); + } else { + mon.worked(100); + } + SizingPhaseSet set = new SizingPhaseSet(); + IStatus status = getEngine().perform(plan, set, mon.newChild(200)); + if (status.isOK()) + return installPlanSize + set.getSizing().getDiskSize(); + return SIZE_UNAVAILABLE; + } + + private int countPlanElements(IProvisioningPlan plan) { + return new CompoundQueryable(plan.getAdditions(), plan.getRemovals()).query(InstallableUnitQuery.ANY, null).unmodifiableSet().size(); + } + + /** + * Perform the specified provisioning plan. + * + * @param plan the provisioning plan to be performed + * @param phaseSet the phase set to be used for the plan + * @param context the provisioning context to be used during provisioning + * @param monitor the progress monitor to use while performing the plan + * @return a status describing the result of performing the plan + */ + public IStatus performProvisioningPlan(IProvisioningPlan plan, PhaseSet phaseSet, ProvisioningContext context, IProgressMonitor monitor) { + PhaseSet set; + if (phaseSet == null) + set = new DefaultPhaseSet(); + else + set = phaseSet; + + // 300 ticks for download, 100 to install handlers, 100 to compute the plan, 100 to install the rest + SubMonitor mon = SubMonitor.convert(monitor, 600); + int ticksUsed = 0; + + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=272355 + // The exact profile instance used in the profile change request and passed to the engine must be used for all + // of these operations, otherwise we can get profile out of synch errors. + IProfile profile = plan.getProfile(); + + if (plan.getInstallerPlan() != null) { + if (set instanceof DefaultPhaseSet) { + // If the phase set calls for download and install, then we want to download everything atomically before + // applying the install plan. This way, we can be sure to install the install handler only if we know + // we will be able to get everything else. + ProfileChangeRequest downloadRequest = new ProfileChangeRequest(profile); + downloadRequest.setAbsoluteMode(true); + downloadRequest.addInstallableUnits(new CompoundQueryable(plan.getAdditions(), plan.getInstallerPlan().getAdditions()).query(InstallableUnitQuery.ANY, null)); + + PhaseSet download = new DownloadPhaseSet(); + IProvisioningPlan downloadPlan = getPlanner().getProvisioningPlan(downloadRequest, context, mon.newChild(100)); + IStatus downloadStatus = getEngine().perform(downloadPlan, download, mon.newChild(300)); + if (!downloadStatus.isOK()) { + mon.done(); + return downloadStatus; + } + ticksUsed = 300; + } + // we pre-downloaded if necessary. Now perform the plan against the original phase set. + IStatus installerPlanStatus = getEngine().perform(plan.getInstallerPlan(), set, mon.newChild(100)); + if (!installerPlanStatus.isOK()) { + mon.done(); + return installerPlanStatus; + } + ticksUsed += 100; + // Apply the configuration + Configurator configChanger = (Configurator) ServiceHelper.getService(Activator.getContext(), Configurator.class.getName()); + try { + configChanger.applyConfiguration(); + } catch (IOException e) { + mon.done(); + return new Status(IStatus.ERROR, Activator.ID, Messages.ProvisioningSession_InstallPlanConfigurationError, e); + } + } + return getEngine().perform(plan, set, mon.newChild(500 - ticksUsed)); + } + + /** + * Return a boolean indicating whether any other provisioning operations are + * scheduled for the specified profile. + * + * @param profileId the id of the profile in question + * @return true if there are pending provisioning operations for + * this profile, false if there are not. + * @see #rememberJob(Job) + */ + public boolean hasScheduledOperationsFor(String profileId) { + Job[] jobs = getScheduledJobs(); + for (int i = 0; i < jobs.length; i++) { + if (jobs[i] instanceof IProfileChangeJob) { + String id = ((IProfileChangeJob) jobs[i]).getProfileId(); + if (profileId.equals(id)) + return true; + } + } + return false; + } + + private Job[] getScheduledJobs() { + synchronized (scheduledJobs) { + return scheduledJobs.toArray(new Job[scheduledJobs.size()]); + } + } + + /** + * Remember the specified job. Remembered jobs are + * checked when callers want to know what work is scheduled for + * a particular profile. + * + * @param job the job to be remembered + * @see #hasScheduledOperationsFor(String) + */ + public void rememberJob(Job job) { + scheduledJobs.add(job); + job.addJobChangeListener(new JobChangeAdapter() { + public void done(IJobChangeEvent event) { + scheduledJobs.remove(event.getJob()); + } + }); + } + + /** + * Get the IInstallable units for the specified profile + * + * @param profileId the profile in question + * @param all true if all IInstallableUnits in the profile should + * be returned, false only those IInstallableUnits marked as (user visible) roots + * should be returned. + * + * @return an array of IInstallableUnits installed in the profile. + */ + public IInstallableUnit[] getInstalledIUs(String profileId, boolean all) { + IProfile profile = getProfileRegistry().getProfile(profileId); + if (profile == null) + return new IInstallableUnit[0]; + IQuery query; + if (all) + query = InstallableUnitQuery.ANY; + else + query = new UserVisibleRootQuery(); + IQueryResult queryResult = profile.query(query, null); + return queryResult.toArray(IInstallableUnit.class); + } + +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/RepositoryTracker.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/RepositoryTracker.java new file mode 100644 index 000000000..8ef818e3c --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/RepositoryTracker.java @@ -0,0 +1,275 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.operations; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.io.File; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; +import org.eclipse.equinox.internal.p2.operations.*; +import org.eclipse.equinox.internal.p2.repository.helpers.RepositoryHelper; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.osgi.util.NLS; + +/** + * RepositoryTracker defines a service that retrieves repositories, tracks their status, and + * reports errors. + * + * @since 2.0 + */ +public abstract class RepositoryTracker { + + // What repositories to show + private int artifactRepositoryFlags = IRepositoryManager.REPOSITORIES_NON_SYSTEM; + private int metadataRepositoryFlags = IRepositoryManager.REPOSITORIES_NON_SYSTEM; + /** + * List of repositories that have already been reported to the user as not found. + */ + private final List reposNotFound = Collections.synchronizedList(new ArrayList()); + + /** + * Return an array of repository locations known for the specified provisioning session. + * + * @param session the provisioning session providing the provisioning services + * @return an array of repository locations known by this tracker + */ + public abstract URI[] getKnownRepositories(ProvisioningSession session); + + /** + * Return a status appropriate for reporting an invalid repository location. + * @param locationText the text representation of the location + * @return a status that describes an invalid location + */ + public IStatus getInvalidLocationStatus(String locationText) { + return new Status(IStatus.ERROR, Activator.ID, IStatusCodes.INVALID_REPOSITORY_LOCATION, NLS.bind(Messages.RepositoryTracker_InvalidLocation, locationText), null); + } + + /** + * Return a repository location represented by the supplied string. The provided + * string should either be an unencoded string representation of a URI, or a + * local file system path. This method is generally suitable for converting a + * location string entered by an end user into a suitable URI representation. + * + * @param locationString a text representation of the location + * @return a repository location URI, or null if the + * text could not be interpreted. + */ + public URI locationFromString(String locationString) { + URI userLocation; + try { + userLocation = URIUtil.fromString(locationString); + } catch (URISyntaxException e) { + return null; + } + // If a path separator char was used, interpret as a local file URI + String uriString = URIUtil.toUnencodedString(userLocation); + if (uriString.length() > 0 && (uriString.charAt(0) == '/' || uriString.charAt(0) == File.separatorChar)) + return RepositoryHelper.localRepoURIHelper(userLocation); + return userLocation; + } + + /** + * Validate the specified repository location. + * + * @param session the provisioning session providing the repository services + * @param location the location in question + * @param contactRepositories true if the appropriate repository manager(s) should be + * consulted regarding the validity of the location, or false if the repository manager + * should not be consulted. + * @param monitor the progress monitor + * @return a status indicating the current status of the repository + */ + + public IStatus validateRepositoryLocation(ProvisioningSession session, URI location, boolean contactRepositories, IProgressMonitor monitor) { + // First validate syntax issues + IStatus localValidationStatus = RepositoryHelper.checkRepositoryLocationSyntax(location); + if (!localValidationStatus.isOK()) { + // bad syntax, but it could just be non-absolute. + // In this case, use the helper + String locationString = URIUtil.toUnencodedString(location); + if (locationString.length() > 0 && (locationString.charAt(0) == '/' || locationString.charAt(0) == File.separatorChar)) { + location = RepositoryHelper.localRepoURIHelper(location); + localValidationStatus = RepositoryHelper.checkRepositoryLocationSyntax(location); + } + } + + if (!localValidationStatus.isOK()) + return localValidationStatus; + + // Syntax was ok, now look for duplicates + URI[] knownRepositories = getKnownRepositories(session); + for (int i = 0; i < knownRepositories.length; i++) { + if (URIUtil.sameURI(knownRepositories[i], location)) { + localValidationStatus = new Status(IStatus.ERROR, Activator.ID, IStatusCodes.INVALID_REPOSITORY_LOCATION, Messages.RepositoryTracker_DuplicateLocation, null); + break; + } + } + + if (!localValidationStatus.isOK()) + return localValidationStatus; + + if (contactRepositories) + return validateRepositoryLocationWithManager(session, location, monitor); + + return localValidationStatus; + } + + /** + * Validate the specified repository location using the appropriate repository manager. + * + * @param session the provisioning session providing the repository services + * @param location the location in question + * @param monitor the progress monitor + * @return a status indicating the current status of the repository + */ + protected abstract IStatus validateRepositoryLocationWithManager(ProvisioningSession session, URI location, IProgressMonitor monitor); + + /** + * Add the specified location to the list of "not found" repositories. + * This list is used to ensure that errors are not reported multiple times + * for the same repository. + * + * The caller is already assumed to have reported any errors if necessary. + * + * @param location the location of the repository that cannot be found + */ + public void addNotFound(URI location) { + reposNotFound.add(location); + } + + /** + * Answer a boolean indicating whether not found status has already been + * reported for the specified location. + * + * @param location the location in question + * @return true if the repository has already been reported as + * being not found, false if no status has been reported for this + * location. + */ + public boolean hasNotFoundStatusBeenReported(URI location) { + // We don't check for things like case variants or end slash variants + // because we know that the repository managers already did this. + return reposNotFound.contains(location); + } + + /** + * Clear the list of repositories that have already been reported as not found. + */ + public void clearRepositoriesNotFound() { + reposNotFound.clear(); + } + + /** + * Remove the specified repository from the list of repositories that + * have already been reported as not found. This method has no effect + * if the repository has never been reported as not found. + * + * @param location the location in question + */ + public void clearRepositoryNotFound(URI location) { + reposNotFound.remove(location); + } + + /** + * Return the repository flags suitable for retrieving known repositories from + * a repository manager + * + * @return the repository flags + * + */ + public int getArtifactRepositoryFlags() { + return artifactRepositoryFlags; + } + + /** + * Set the repository flags suitable for retrieving known repositories from + * a repository manager + * + * @param flags the repository flags + * + */ + public void setArtifactRepositoryFlags(int flags) { + artifactRepositoryFlags = flags; + } + + /** + * Return the repository flags suitable for retrieving known repositories from + * a repository manager + * + * @return the repository flags + * + */ + public int getMetadataRepositoryFlags() { + return metadataRepositoryFlags; + } + + /** + * Set the repository flags suitable for retrieving known repositories from + * a repository manager + * + * @param flags the repository flags + * + */ + + public void setMetadataRepositoryFlags(int flags) { + metadataRepositoryFlags = flags; + } + + /** + * Report a failure to load the specified repository. + *

    + * This default implementation simply logs the failure. Subclasses may override + * to provide additional error reporting. + *

    + * @param location the location of the failed repository + * @param exception the failure that occurred + */ + public void reportLoadFailure(final URI location, ProvisionException exception) { + // special handling when the repo location is bad. We don't want to continually report it + int code = exception.getStatus().getCode(); + if (code == IStatusCodes.INVALID_REPOSITORY_LOCATION || code == ProvisionException.REPOSITORY_INVALID_LOCATION || code == ProvisionException.REPOSITORY_NOT_FOUND) { + if (hasNotFoundStatusBeenReported(location)) + return; + addNotFound(location); + } + + LogHelper.log(exception.getStatus()); + } + + /** + * Add a repository at the specified location. + * + * @param location the location of the new repository + * @param nickname the nickname for the repository, or null if there is no nickname + * @param session the session to use for provisioning services + */ + public abstract void addRepository(URI location, String nickname, ProvisioningSession session); + + /** + * Remove the repositories at the specified locations + * + * @param locations the locations + * @param session the session to use for provisioning services + */ + public abstract void removeRepositories(URI[] locations, ProvisioningSession session); + + /** + * Refresh the repositories at the specified locations + * @param locations the locations + * @param session the session to use for provisioning services + * @param monitor the progress monitor to use + */ + public abstract void refreshRepositories(URI[] locations, ProvisioningSession session, IProgressMonitor monitor); +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/UninstallOperation.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/UninstallOperation.java new file mode 100644 index 000000000..1de60db2c --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/UninstallOperation.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.p2.operations; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.MultiStatus; +import org.eclipse.equinox.internal.p2.operations.Messages; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; + +/** + * An UninstallOperation describes an operation that uninstalls {@link IInstallableUnit}s from + * a profile. + * + * The following snippet shows how one might use an UninstallOperation to perform a synchronous resolution and + * then kick off an uninstall in the background: + * + *
    + * UninstallOperation op = new UninstallOperation(session, new IInstallableUnit [] { removeThisIU });
    + * IStatus result = op.resolveModal(monitor);
    + * if (result.isOK()) {
    + *   op.getProvisioningJob(monitor).schedule();
    + * }
    + * 
    + * @noextend This class is not intended to be subclassed by clients. + * @since 2.0 + */ +public class UninstallOperation extends ProfileChangeOperation { + + private IInstallableUnit[] toUninstall; + + /** + * Create an uninstall operation on the specified provisioning session that uninstalls + * the specified IInstallableUnits. Unless otherwise specified, the operation will + * be associated with the currently running profile. + * + * @param session the session to use for obtaining provisioning services + * @param toUninstall the IInstallableUnits to be installed into the profile. + */ + public UninstallOperation(ProvisioningSession session, IInstallableUnit[] toUninstall) { + super(session); + this.toUninstall = toUninstall; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.ProfileChangeOperation#computeProfileChangeRequest(org.eclipse.core.runtime.IProgressMonitor) + */ + protected void computeProfileChangeRequest(MultiStatus status, IProgressMonitor monitor) { + request = ProfileChangeRequest.createByProfileId(profileId); + request.removeInstallableUnits(toUninstall); + // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=255984 + // We ask to remove the the profile root property in addition to removing the IU. In theory this + // should be redundant, but there are cases where the planner decides not to uninstall something because + // it is needed by others. We still want to remove the root in this case. + // if (rootMarkerKey != null) + for (int i = 0; i < toUninstall.length; i++) + request.removeInstallableUnitProfileProperty(toUninstall[i], IProfile.PROP_PROFILE_ROOT_IU); + + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.ProfileChangeOperation#getProvisioningJobName() + */ + protected String getProvisioningJobName() { + return Messages.UninstallOperation_ProvisioningJobName; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.ProfileChangeOperation#getResolveJobName() + */ + protected String getResolveJobName() { + return Messages.UninstallOperation_ResolveJobName; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/Update.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/Update.java new file mode 100644 index 000000000..8188710e3 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/Update.java @@ -0,0 +1,72 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.p2.operations; + +import org.eclipse.equinox.p2.metadata.IInstallableUnit; + +/** + * A simple data structure describing a possible update. + * + * @noextend This class is not intended to be subclassed by clients. + * @since 2.0 + */ +public class Update { + + public IInstallableUnit toUpdate; + public IInstallableUnit replacement; + + /** + * Creates a new update description. + * @param toUpdate The installable unit to update + * @param replacement The replacement installable unit + */ + public Update(IInstallableUnit toUpdate, IInstallableUnit replacement) { + this.toUpdate = toUpdate; + this.replacement = replacement; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof Update)) + return false; + if (toUpdate == null) + return false; + if (replacement == null) + return false; + Update other = (Update) obj; + return toUpdate.equals(other.toUpdate) && replacement.equals(other.replacement); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((toUpdate == null) ? 0 : toUpdate.hashCode()); + result = prime * result + ((replacement == null) ? 0 : replacement.hashCode()); + return result; + } + + /*(non-Javadoc) + * @see java.lang.Object#toString() + */ + public String toString() { + return "Update " + toUpdate.toString() + " ==> " + replacement.toString(); //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/UpdateOperation.java b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/UpdateOperation.java new file mode 100644 index 000000000..13b295bb1 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/UpdateOperation.java @@ -0,0 +1,277 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.p2.operations; + +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.operations.*; +import org.eclipse.equinox.internal.provisional.p2.director.PlannerHelper; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.metadata.query.PatchQuery; +import org.eclipse.equinox.p2.query.IQueryResult; + +/** + * An UpdateOperation describes an operation that updates {@link IInstallableUnit}s in + * a profile. + * + * The following snippet shows how one might use an UpdateOperation to check for updates + * to the profile and then install them in the background. + * + *
    + * UpdateOperation op = new UpdateOperation(session);
    + * IStatus result = op.resolveModal(monitor);
    + * if (result.isOK()) {
    + *   op.getProvisioningJob(monitor).schedule();
    + * }
    + * 
    + * + * The life cycle of an UpdateOperation is different than that of the other + * operations. Since assembling the list of possible updates may be costly, + * clients should not have to create a new update operation if the desired updates + * to be applied need to change. In this case, the client can set a new set of + * chosen updates on the update operation and resolve again. + * + *
    + * UpdateOperation op = new UpdateOperation(session);
    + * IStatus result = op.resolveModal(monitor);
    + * if (result.isOK()) {
    + *   op.getProvisioningJob(monitor).schedule();
    + * } else if (result.getSeverity() == IStatus.ERROR) {
    + *   Update [] chosenUpdates = letUserPickFrom(op.getPossibleUpdates());
    + *   op.setSelectedUpdates(chosenUpdates);
    + *   IStatus result = op.resolveModal(monitor);
    + * }
    + * 
    + * + * @noextend This class is not intended to be subclassed by clients. + * @since 2.0 + */ +public class UpdateOperation extends ProfileChangeOperation { + + private IInstallableUnit[] iusToUpdate; + private HashMap> possibleUpdatesByIU = new HashMap>(); + private List defaultUpdates; + + /** + * Create an update operation on the specified provisioning session that updates + * the specified IInstallableUnits. Unless otherwise specified, the operation will + * be associated with the currently running profile. + * + * @param session the session to use for obtaining provisioning services + * @param toBeUpdated the IInstallableUnits to be updated. + */ + public UpdateOperation(ProvisioningSession session, IInstallableUnit[] toBeUpdated) { + super(session); + this.iusToUpdate = toBeUpdated; + } + + /** + * Create an update operation that will update all of the user-visible installable + * units in the profile (the profile roots). + * + * @param session the session providing the provisioning services + */ + public UpdateOperation(ProvisioningSession session) { + this(session, null); + } + + /** + * Set the updates that should be selected from the set of available updates. + * If the selected updates are not specified, then the latest available update + * for each IInstallableUnit with updates will be chosen. + * + * @param defaultUpdates the updates that should be chosen from all of the available + * updates. + */ + public void setSelectedUpdates(Update[] defaultUpdates) { + this.defaultUpdates = Arrays.asList(defaultUpdates); + } + + /** + * Get the updates that have been selected from the set of available updates. + * If none have been specified by the client, then the latest available update + * for each IInstallableUnit with updates will be chosen. + * + * @return the updates that should be chosen from all of the available updates + */ + public Update[] getSelectedUpdates() { + if (defaultUpdates == null) + return new Update[0]; + return defaultUpdates.toArray(new Update[defaultUpdates.size()]); + } + + /** + * Get the list of all possible updates. This list may include multiple versions + * of updates for the same IInstallableUnit, as well as patches to the IInstallableUnit. + * + * @return an array of all possible updates + */ + public Update[] getPossibleUpdates() { + ArrayList all = new ArrayList(); + for (List updates : possibleUpdatesByIU.values()) + all.addAll(updates); + return all.toArray(new Update[all.size()]); + } + + private Update[] updatesFor(IInstallableUnit iu, IProfile profile, IProgressMonitor monitor) { + List updates; + if (possibleUpdatesByIU.containsKey(iu)) { + // We've already looked them up in the planner, use the cache + updates = possibleUpdatesByIU.get(iu); + } else { + // We must consult the planner + IInstallableUnit[] replacements = session.getPlanner().updatesFor(iu, context, monitor); + updates = new ArrayList(replacements.length); + for (int i = 0; i < replacements.length; i++) { + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=273967 + // In the case of patches, it's possible that a patch is returned as an available update + // even though it is already installed, because we are querying each IU for updates individually. + // For now, we ignore any proposed update that is already installed. + IQueryResult alreadyInstalled = profile.query(new InstallableUnitQuery(replacements[i]), null); + if (alreadyInstalled.isEmpty()) { + Update update = new Update(iu, replacements[i]); + updates.add(update); + } + } + possibleUpdatesByIU.put(iu, updates); + } + return updates.toArray(new Update[updates.size()]); + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.ProfileChangeOperation#computeProfileChangeRequest(org.eclipse.core.runtime.IProgressMonitor) + */ + protected void computeProfileChangeRequest(MultiStatus status, IProgressMonitor monitor) { + // Here we create a profile change request by finding the latest version available for any replacement, unless + // otherwise specified in the selections. + // We have to consider the scenario where the only updates available are patches, in which case the original + // IU should not be removed as part of the update. + Set toBeUpdated = new HashSet(); + HashSet elementsToPlan = new HashSet(); + boolean selectionSpecified = false; + IProfile profile = session.getProfileRegistry().getProfile(profileId); + if (profile == null) + return; + + SubMonitor sub = SubMonitor.convert(monitor, Messages.UpdateOperation_ProfileChangeRequestProgress, 100 * iusToUpdate.length); + for (int i = 0; i < iusToUpdate.length; i++) { + SubMonitor iuMon = sub.newChild(100); + Update[] updates = updatesFor(iusToUpdate[i], profile, iuMon); + for (int j = 0; j < updates.length; j++) { + toBeUpdated.add(iusToUpdate[i]); + if (defaultUpdates != null && defaultUpdates.contains(updates[j])) { + elementsToPlan.add(updates[j]); + selectionSpecified = true; + } + + } + if (!selectionSpecified) { + // If no selection was specified, we must figure out the latest version to apply. + // The rules are that a true update will always win over a patch, but if only + // patches are available, they should all be selected. + // We first gather the latest versions of everything proposed. + // Patches are keyed by their id because they are unique and should not be compared to + // each other. Updates are keyed by the IU they are updating so we can compare the + // versions and select the latest one + HashMap latestVersions = new HashMap(); + boolean foundUpdate = false; + boolean foundPatch = false; + for (int j = 0; j < updates.length; j++) { + String key; + if (PatchQuery.isPatch(updates[j].replacement)) { + foundPatch = true; + key = updates[j].replacement.getId(); + } else { + foundUpdate = true; + key = updates[j].toUpdate.getId(); + } + Update latestUpdate = latestVersions.get(key); + IInstallableUnit latestIU = latestUpdate == null ? null : latestUpdate.replacement; + if (latestIU == null || updates[j].replacement.getVersion().compareTo(latestIU.getVersion()) > 0) + latestVersions.put(key, updates[j]); + } + // If there is a true update available, ignore any patches found + // Patches are keyed by their own id + if (foundPatch && foundUpdate) { + Set keys = new HashSet(); + keys.addAll(latestVersions.keySet()); + for (String id : keys) { + // Get rid of things keyed by a different id. We've already made sure + // that updates with a different id are keyed under the original id + if (!id.equals(iusToUpdate[i].getId())) { + latestVersions.remove(id); + } + } + } + elementsToPlan.addAll(latestVersions.values()); + } + sub.worked(100); + } + + if (toBeUpdated.size() <= 0 || elementsToPlan.isEmpty()) { + sub.done(); + status.add(PlanAnalyzer.getStatus(IStatusCodes.NOTHING_TO_UPDATE, null)); + return; + } + + request = ProfileChangeRequest.createByProfileId(profileId); + for (Update update : elementsToPlan) { + IInstallableUnit theUpdate = update.replacement; + if (defaultUpdates == null) { + defaultUpdates = new ArrayList(); + defaultUpdates.add(update); + } else { + if (!defaultUpdates.contains(update)) + defaultUpdates.add(update); + } + request.addInstallableUnits(theUpdate); + // if (rootMarkerKey != null) + request.setInstallableUnitProfileProperty(theUpdate, IProfile.PROP_PROFILE_ROOT_IU, Boolean.toString(true)); + if (PatchQuery.isPatch(theUpdate)) { + request.setInstallableUnitInclusionRules(theUpdate, PlannerHelper.createOptionalInclusionRule(theUpdate)); + } else { + request.removeInstallableUnit(update.toUpdate); + } + + } + sub.done(); + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.ProfileChangeOperation#getProvisioningJobName() + */ + protected String getProvisioningJobName() { + return Messages.UpdateOperation_UpdateJobName; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.ProfileChangeOperation#getResolveJobName() + */ + protected String getResolveJobName() { + return Messages.UpdateOperation_ResolveJobName; + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.ProfileChangeOperation#prepareToResolve() + */ + protected void prepareToResolve() { + super.prepareToResolve(); + if (iusToUpdate == null) { + iusToUpdate = session.getInstalledIUs(profileId, false); + } + } + +} diff --git a/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/package.html b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/package.html new file mode 100644 index 000000000..c0f0a930a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.operations/src/org/eclipse/equinox/p2/operations/package.html @@ -0,0 +1,33 @@ + + + + + + + Package-level Javadoc + + +Describes high level provisioning operations that can be resolved and performed +either modally or in the background. +

    +Package Specification

    +

    +This package consists of several kinds of operations and supporting classes: +

      +
    • Profile Change Operations describe high level provisioning operations that +modify a profile. These operations generally are performed in two phases, the resolution +of the operation, followed by the provisioning of the resolved operation. Both the +resolution and the provisioning tasks can be performed either synchronously or as jobs. +
    • +
    • Provisioning Jobs describe lower level provisioning tasks that can +be performed synchronously or in the background. +
    • +
    • ProvisioningSession represents a particular instance of a p2 provisioning +system. It provides access to all of the p2 core services as well as utility methods +for commonly performed provisioning tasks. +
    • +
    +

    +@since 2.0 + + diff --git a/bundles/org.eclipse.equinox.p2.reconciler.dropins/.classpath b/bundles/org.eclipse.equinox.p2.reconciler.dropins/.classpath index 6f3b481ac..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.reconciler.dropins/.classpath +++ b/bundles/org.eclipse.equinox.p2.reconciler.dropins/.classpath @@ -1,6 +1,6 @@ - + diff --git a/bundles/org.eclipse.equinox.p2.reconciler.dropins/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.reconciler.dropins/.settings/org.eclipse.jdt.core.prefs index b8283102b..45a58927b 100644 --- a/bundles/org.eclipse.equinox.p2.reconciler.dropins/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.reconciler.dropins/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Thu Nov 20 12:56:54 PST 2008 +#Wed Dec 30 07:30:16 CET 2009 eclipse.preferences.version=1 instance/org.eclipse.core.net/org.eclipse.core.net.hasMigrated=true org.eclipse.jdt.core.builder.cleanOutputFolder=clean @@ -8,24 +8,24 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fieldHiding=warning org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning @@ -72,7 +72,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=en org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 diff --git a/bundles/org.eclipse.equinox.p2.reconciler.dropins/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.reconciler.dropins/META-INF/MANIFEST.MF index 84163bc4f..a153b4b82 100644 --- a/bundles/org.eclipse.equinox.p2.reconciler.dropins/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.reconciler.dropins/META-INF/MANIFEST.MF @@ -6,8 +6,9 @@ Bundle-Vendor: %providerName Bundle-Localization: plugin Bundle-Version: 1.0.100.qualifier Bundle-Activator: org.eclipse.equinox.internal.p2.reconciler.dropins.Activator -Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, - J2SE-1.4 +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 Import-Package: org.eclipse.equinox.app;version="1.0.0", org.eclipse.equinox.internal.p2.artifact.repository, org.eclipse.equinox.internal.p2.core.helpers, @@ -15,15 +16,19 @@ Import-Package: org.eclipse.equinox.app;version="1.0.0", org.eclipse.equinox.internal.p2.metadata.repository, org.eclipse.equinox.internal.p2.update, org.eclipse.equinox.internal.provisional.configurator, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.director, org.eclipse.equinox.internal.provisional.p2.directorywatcher, - org.eclipse.equinox.internal.provisional.p2.engine, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.p2.repository, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.engine.query, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.metadata, org.eclipse.osgi.service.datalocation;version="1.0.0", org.eclipse.osgi.service.environment;version="1.1.0", org.eclipse.osgi.util;version="1.1.0", diff --git a/bundles/org.eclipse.equinox.p2.reconciler.dropins/build.properties b/bundles/org.eclipse.equinox.p2.reconciler.dropins/build.properties index 6861747e4..3552dc9d2 100644 --- a/bundles/org.eclipse.equinox.p2.reconciler.dropins/build.properties +++ b/bundles/org.eclipse.equinox.p2.reconciler.dropins/build.properties @@ -18,3 +18,5 @@ bin.includes = META-INF/,\ Bootstrap.product,\ config.ini src.includes = about.html +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/Activator.java b/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/Activator.java index 6636bea3d..e3c1fd62d 100644 --- a/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/Activator.java +++ b/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/Activator.java @@ -9,6 +9,8 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.reconciler.dropins; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.*; import java.net.URI; import java.net.URL; @@ -20,15 +22,15 @@ import org.eclipse.equinox.internal.p2.extensionlocation.*; import org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager; import org.eclipse.equinox.internal.p2.update.Configuration; import org.eclipse.equinox.internal.p2.update.PathUtil; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.directorywatcher.DirectoryWatcher; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.service.datalocation.Location; import org.osgi.framework.*; import org.osgi.service.packageadmin.PackageAdmin; @@ -50,9 +52,9 @@ public class Activator implements BundleActivator { private static PackageAdmin packageAdmin; private static BundleContext bundleContext; private ServiceReference packageAdminRef; - private List watchers = new ArrayList(); - private final static Set repositories = new HashSet(); - private Collection filesToCheck = null; + private List watchers = new ArrayList(); + private final static Set repositories = new HashSet(); + private Collection filesToCheck = null; /** * Helper method to create an extension location metadata repository at the given URI. @@ -63,11 +65,9 @@ public class Activator implements BundleActivator { * @throws IllegalStateException * @throws ProvisionException */ - public static IMetadataRepository createExtensionLocationMetadataRepository(URI location, String name, Map properties) throws ProvisionException { - BundleContext context = getContext(); - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(context, IMetadataRepositoryManager.class.getName()); - if (manager == null) - throw new IllegalStateException("MetadataRepositoryManager not registered."); //$NON-NLS-1$ + public static IMetadataRepository createExtensionLocationMetadataRepository(URI location, String name, Map properties) throws ProvisionException { + IProvisioningAgent agent = (IProvisioningAgent) ServiceHelper.getService(getContext(), IProvisioningAgent.SERVICE_NAME); + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME); ExtensionLocationMetadataRepositoryFactory factory = new ExtensionLocationMetadataRepositoryFactory(); IMetadataRepository repository = factory.create(location, name, ExtensionLocationMetadataRepository.TYPE, properties); //we need to add the concrete repository to the repository manager, or its properties will not be correct @@ -83,8 +83,8 @@ public class Activator implements BundleActivator { * @throws ProvisionException */ public static IMetadataRepository loadMetadataRepository(URI location, IProgressMonitor monitor) throws ProvisionException { - BundleContext context = getContext(); - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(context, IMetadataRepositoryManager.class.getName()); + IProvisioningAgent agent = (IProvisioningAgent) ServiceHelper.getService(getContext(), IProvisioningAgent.SERVICE_NAME); + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME); if (manager == null) throw new IllegalStateException("MetadataRepositoryManager not registered."); //$NON-NLS-1$ IMetadataRepository repository = manager.loadRepository(location, monitor); @@ -101,9 +101,9 @@ public class Activator implements BundleActivator { * @throws IllegalStateException * @throws ProvisionException */ - public static IArtifactRepository createExtensionLocationArtifactRepository(URI location, String name, Map properties) throws ProvisionException { - BundleContext context = getContext(); - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(context, IArtifactRepositoryManager.class.getName()); + public static IArtifactRepository createExtensionLocationArtifactRepository(URI location, String name, Map properties) throws ProvisionException { + IProvisioningAgent agent = (IProvisioningAgent) ServiceHelper.getService(getContext(), IProvisioningAgent.SERVICE_NAME); + IArtifactRepositoryManager manager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME); if (manager == null) throw new IllegalStateException("ArtifactRepositoryManager not registered."); //$NON-NLS-1$ ExtensionLocationArtifactRepositoryFactory factory = new ExtensionLocationArtifactRepositoryFactory(); @@ -121,8 +121,8 @@ public class Activator implements BundleActivator { * @throws ProvisionException */ public static IArtifactRepository loadArtifactRepository(URI location, IProgressMonitor monitor) throws ProvisionException { - BundleContext context = getContext(); - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(context, IArtifactRepositoryManager.class.getName()); + IProvisioningAgent agent = (IProvisioningAgent) ServiceHelper.getService(getContext(), IProvisioningAgent.SERVICE_NAME); + IArtifactRepositoryManager manager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME); if (manager == null) throw new IllegalStateException("ArtifactRepositoryManager not registered."); //$NON-NLS-1$ IArtifactRepository repository = manager.loadRepository(location, monitor); @@ -134,7 +134,7 @@ public class Activator implements BundleActivator { * Return the set of metadata repositories known to this bundle. It is constructed from the repos * for the drop-ins as well as the ones in the configuration. */ - public static Set getRepositories() { + public static Set getRepositories() { return repositories; } @@ -156,10 +156,6 @@ public class Activator implements BundleActivator { if (!startEarly("org.eclipse.equinox.p2.exemplarysetup")) //$NON-NLS-1$ return; - if (!startEarly("org.eclipse.equinox.simpleconfigurator.manipulator")) //$NON-NLS-1$ - return; - if (!startEarly("org.eclipse.equinox.frameworkadmin.equinox")) //$NON-NLS-1$ - return; checkConfigIni(); @@ -225,9 +221,9 @@ public class Activator implements BundleActivator { return false; // gather the list of files/folders that we need to check - Collection files = getFilesToCheck(); - for (Iterator iter = files.iterator(); iter.hasNext();) { - File file = (File) iter.next(); + Collection files = getFilesToCheck(); + for (Iterator iter = files.iterator(); iter.hasNext();) { + File file = iter.next(); String key = file.getAbsolutePath(); String timestamp = timestamps.getProperty(key); if (timestamp == null) @@ -271,11 +267,11 @@ public class Activator implements BundleActivator { * Return a collection of files which are interesting to us when we want to record timestamps * to figure out if something has changed and perhaps avoid an unnecessary reconcilation. */ - private Collection getFilesToCheck() { + private Collection getFilesToCheck() { if (filesToCheck != null) return filesToCheck; - Set result = new HashSet(); + Set result = new HashSet(); // configuration/org.eclipse.update/platform.xml, configuration/../plugins, configuration/../features File configuration = getConfigurationLocation(); @@ -319,8 +315,8 @@ public class Activator implements BundleActivator { * Iterate over the given collection of files (could be dropins or links folders) and * return a collection of files that might be interesting to check the timestamps of. */ - private Collection getDropinsToCheck(File[] files) { - Collection result = new HashSet(); + private Collection getDropinsToCheck(File[] files) { + Collection result = new HashSet(); for (int outer = 0; outer < files.length; outer++) { // add top-level file/folder result.add(files[outer]); @@ -377,9 +373,9 @@ public class Activator implements BundleActivator { */ private void writeTimestamps() { Properties timestamps = new Properties(); - Collection files = getFilesToCheck(); - for (Iterator iter = files.iterator(); iter.hasNext();) { - File file = (File) iter.next(); + Collection files = getFilesToCheck(); + for (Iterator iter = files.iterator(); iter.hasNext();) { + File file = iter.next(); timestamps.put(file.getAbsolutePath(), Long.toString(file.lastModified())); } @@ -470,6 +466,7 @@ public class Activator implements BundleActivator { PlatformXmlListener listener = new PlatformXmlListener(configFile); watcher.addListener(listener); watcher.poll(); + watchers.add(watcher); repositories.addAll(listener.getMetadataRepositories()); } @@ -477,7 +474,7 @@ public class Activator implements BundleActivator { * Create a new directory watcher with a repository listener on the drop-ins folder. */ private void watchDropins() { - List directories = new ArrayList(); + List directories = new ArrayList(); File[] dropinsDirectories = getDropinsDirectories(); directories.addAll(Arrays.asList(dropinsDirectories)); File[] linksDirectories = getLinksDirectories(); @@ -486,9 +483,10 @@ public class Activator implements BundleActivator { return; DropinsRepositoryListener listener = new DropinsRepositoryListener(DROPINS); - DirectoryWatcher watcher = new DirectoryWatcher((File[]) directories.toArray(new File[directories.size()])); + DirectoryWatcher watcher = new DirectoryWatcher(directories.toArray(new File[directories.size()])); watcher.addListener(listener); watcher.poll(); + watchers.add(watcher); repositories.addAll(listener.getMetadataRepositories()); } @@ -496,10 +494,8 @@ public class Activator implements BundleActivator { * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { - for (Iterator iter = watchers.iterator(); iter.hasNext();) { - DirectoryWatcher watcher = (DirectoryWatcher) iter.next(); + for (DirectoryWatcher watcher : watchers) watcher.stop(); - } bundleContext = null; setPackageAdmin(null); context.ungetService(packageAdminRef); @@ -576,7 +572,7 @@ public class Activator implements BundleActivator { * more than one to be returned here if we are running in shared mode. */ private static File[] getLinksDirectories() { - List linksDirectories = new ArrayList(); + List linksDirectories = new ArrayList(); File root = getEclipseHome(); if (root != null) linksDirectories.add(new File(root, LINKS)); @@ -589,7 +585,7 @@ public class Activator implements BundleActivator { if (configuration != null && configuration.getParentFile() != null) linksDirectories.add(new File(configuration.getParentFile(), LINKS)); } - return (File[]) linksDirectories.toArray(new File[linksDirectories.size()]); + return linksDirectories.toArray(new File[linksDirectories.size()]); } /* @@ -599,7 +595,7 @@ public class Activator implements BundleActivator { * local dropins directory. */ private static File[] getDropinsDirectories() { - List dropinsDirectories = new ArrayList(); + List dropinsDirectories = new ArrayList(); // did the user specify one via System properties? String watchedDirectoryProperty = bundleContext.getProperty(DROPINS_DIRECTORY); if (watchedDirectoryProperty != null) @@ -618,14 +614,14 @@ public class Activator implements BundleActivator { if (configuration != null && configuration.getParentFile() != null) dropinsDirectories.add(new File(configuration.getParentFile(), DROPINS)); } - return (File[]) dropinsDirectories.toArray(new File[dropinsDirectories.size()]); + return dropinsDirectories.toArray(new File[dropinsDirectories.size()]); } /* * Return the current profile or null if it cannot be retrieved. */ public static IProfile getCurrentProfile(BundleContext context) { - ServiceReference reference = context.getServiceReference(IProfileRegistry.class.getName()); + ServiceReference reference = context.getServiceReference(IProfileRegistry.SERVICE_NAME); if (reference == null) return null; IProfileRegistry profileRegistry = (IProfileRegistry) context.getService(reference); @@ -660,12 +656,12 @@ public class Activator implements BundleActivator { // TODO Fix this up to get the services in a better way public static IArtifactRepositoryManager getArtifactRepositoryManager() { - return (IArtifactRepositoryManager) ServiceHelper.getService(bundleContext, IArtifactRepositoryManager.class.getName()); + return (IArtifactRepositoryManager) ServiceHelper.getService(bundleContext, IArtifactRepositoryManager.SERVICE_NAME); } // TODO Fix this up to get the services in a better way public static IMetadataRepositoryManager getMetadataRepositoryManager() { - return (IMetadataRepositoryManager) ServiceHelper.getService(bundleContext, IMetadataRepositoryManager.class.getName()); + return (IMetadataRepositoryManager) ServiceHelper.getService(bundleContext, IMetadataRepositoryManager.SERVICE_NAME); } } diff --git a/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/DropinsRepositoryListener.java b/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/DropinsRepositoryListener.java index 1d84ec2ea..28588cfc7 100644 --- a/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/DropinsRepositoryListener.java +++ b/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/DropinsRepositoryListener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. + * Copyright (c) 2008, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -15,22 +15,26 @@ import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.util.*; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; +import org.eclipse.equinox.internal.p2.core.helpers.Tracing; import org.eclipse.equinox.internal.p2.extensionlocation.ExtensionLocationArtifactRepository; import org.eclipse.equinox.internal.p2.extensionlocation.ExtensionLocationMetadataRepository; import org.eclipse.equinox.internal.p2.update.Site; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.directorywatcher.RepositoryListener; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.util.NLS; public class DropinsRepositoryListener extends RepositoryListener { + private static final String PREFIX = "[reconciler] [dropins] "; //$NON-NLS-1$ private static final String PLUGINS = "plugins"; //$NON-NLS-1$ private static final String FEATURES = "features"; //$NON-NLS-1$ private static final String JAR = ".jar"; //$NON-NLS-1$ @@ -40,8 +44,8 @@ public class DropinsRepositoryListener extends RepositoryListener { private static final String DROPIN_ARTIFACT_REPOSITORIES = "dropin.artifactRepositories"; //$NON-NLS-1$ private static final String DROPIN_METADATA_REPOSITORIES = "dropin.metadataRepositories"; //$NON-NLS-1$ private static final String PIPE = "|"; //$NON-NLS-1$ - private List metadataRepositories = new ArrayList(); - private List artifactRepositories = new ArrayList(); + private List metadataRepositories = new ArrayList(); + private List artifactRepositories = new ArrayList(); public DropinsRepositoryListener(String repositoryName) { super(repositoryName, true); @@ -52,22 +56,28 @@ public class DropinsRepositoryListener extends RepositoryListener { } public boolean added(File file) { - if (super.added(file)) + if (super.added(file)) { + if (Tracing.DEBUG_RECONCILER) + Tracing.debug(PREFIX + "Interesting feature or bundle added: " + file); //$NON-NLS-1$ return true; + } addRepository(file); return true; } public boolean changed(File file) { - if (super.changed(file)) + if (super.changed(file)) { + if (Tracing.DEBUG_RECONCILER) + Tracing.debug(PREFIX + "Interesting feature or bundle changed: " + file); //$NON-NLS-1$ return true; + } addRepository(file); return true; } private void addRepository(File file) { URI repoLocation = createRepositoryLocation(file); - Properties properties = new Properties(); + Map properties = new HashMap(); // if the file pointed to a link file, keep track of the attribute // so we can add it to the repo later if (file.isFile() && file.getName().endsWith(LINK)) { @@ -174,7 +184,7 @@ public class DropinsRepositoryListener extends RepositoryListener { return repo.toURI(); } - public void getMetadataRepository(URI repoURL, Properties properties) { + public void getMetadataRepository(URI repoURL, Map properties) { try { IMetadataRepository repository = null; try { @@ -184,12 +194,23 @@ public class DropinsRepositoryListener extends RepositoryListener { repository = Activator.loadMetadataRepository(repoURL, null); } metadataRepositories.add(repository); + debugRepository(repository); } catch (ProvisionException ex) { LogHelper.log(ex); } } - public void getArtifactRepository(URI repoURL, Properties properties) { + private void debugRepository(IMetadataRepository repository) { + if (!Tracing.DEBUG_RECONCILER) + return; + Tracing.debug(PREFIX + "Repository created " + repository.getLocation()); //$NON-NLS-1$ + // Print out a list of all the IUs in the repository + IQueryResult result = repository.query(InstallableUnitQuery.ANY, new NullProgressMonitor()); + for (Iterator iter = result.iterator(); iter.hasNext();) + Tracing.debug(PREFIX + "\t" + iter.next()); //$NON-NLS-1$ + } + + public void getArtifactRepository(URI repoURL, Map properties) { try { IArtifactRepository repository = null; try { @@ -212,14 +233,14 @@ public class DropinsRepositoryListener extends RepositoryListener { } private void synchronizeDropinMetadataRepositories() { - List currentRepositories = new ArrayList(); - for (Iterator it = metadataRepositories.iterator(); it.hasNext();) { - IMetadataRepository repository = (IMetadataRepository) it.next(); + List currentRepositories = new ArrayList(); + for (Iterator it = metadataRepositories.iterator(); it.hasNext();) { + IMetadataRepository repository = it.next(); currentRepositories.add(repository.getLocation().toString()); } - List previousRepositories = getListRepositoryProperty(getMetadataRepository(), DROPIN_METADATA_REPOSITORIES); - for (Iterator iterator = previousRepositories.iterator(); iterator.hasNext();) { - String repository = (String) iterator.next(); + List previousRepositories = getListRepositoryProperty(getMetadataRepository(), DROPIN_METADATA_REPOSITORIES); + for (Iterator iterator = previousRepositories.iterator(); iterator.hasNext();) { + String repository = iterator.next(); if (!currentRepositories.contains(repository)) removeMetadataRepository(repository); } @@ -238,14 +259,14 @@ public class DropinsRepositoryListener extends RepositoryListener { } private void synchronizeDropinArtifactRepositories() { - List currentRepositories = new ArrayList(); - for (Iterator it = artifactRepositories.iterator(); it.hasNext();) { - IArtifactRepository repository = (IArtifactRepository) it.next(); + List currentRepositories = new ArrayList(); + for (Iterator it = artifactRepositories.iterator(); it.hasNext();) { + IArtifactRepository repository = it.next(); currentRepositories.add(repository.getLocation().toString()); } - List previousRepositories = getListRepositoryProperty(getArtifactRepository(), DROPIN_ARTIFACT_REPOSITORIES); - for (Iterator iterator = previousRepositories.iterator(); iterator.hasNext();) { - String repository = (String) iterator.next(); + List previousRepositories = getListRepositoryProperty(getArtifactRepository(), DROPIN_ARTIFACT_REPOSITORIES); + for (Iterator iterator = previousRepositories.iterator(); iterator.hasNext();) { + String repository = iterator.next(); if (!currentRepositories.contains(repository)) removeArtifactRepository(repository); } @@ -263,9 +284,9 @@ public class DropinsRepositoryListener extends RepositoryListener { } } - private List getListRepositoryProperty(IRepository repository, String key) { - List listProperty = new ArrayList(); - String dropinRepositories = (String) repository.getProperties().get(key); + private List getListRepositoryProperty(IRepository repository, String key) { + List listProperty = new ArrayList(); + String dropinRepositories = repository.getProperties().get(key); if (dropinRepositories != null) { StringTokenizer tokenizer = new StringTokenizer(dropinRepositories, PIPE); while (tokenizer.hasMoreTokens()) { @@ -275,10 +296,10 @@ public class DropinsRepositoryListener extends RepositoryListener { return listProperty; } - private void setListRepositoryProperty(IRepository repository, String key, List listProperty) { + private void setListRepositoryProperty(IRepository repository, String key, List listProperty) { StringBuffer buffer = new StringBuffer(); - for (Iterator it = listProperty.iterator(); it.hasNext();) { - String repositoryString = (String) it.next(); + for (Iterator it = listProperty.iterator(); it.hasNext();) { + String repositoryString = it.next(); buffer.append(repositoryString); if (it.hasNext()) buffer.append(PIPE); @@ -287,8 +308,8 @@ public class DropinsRepositoryListener extends RepositoryListener { repository.setProperty(key, value); } - public Collection getMetadataRepositories() { - List result = new ArrayList(metadataRepositories); + public Collection getMetadataRepositories() { + List result = new ArrayList(metadataRepositories); result.add(getMetadataRepository()); return result; } diff --git a/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/PlatformXmlListener.java b/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/PlatformXmlListener.java index 913f7f85c..f89f24602 100644 --- a/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/PlatformXmlListener.java +++ b/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/PlatformXmlListener.java @@ -10,18 +10,21 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.reconciler.dropins; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.*; +import java.util.Map.Entry; import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.extensionlocation.*; import org.eclipse.equinox.internal.p2.update.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.directorywatcher.DirectoryChangeListener; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.osgi.util.NLS; /** @@ -38,7 +41,7 @@ public class PlatformXmlListener extends DirectoryChangeListener { private boolean changed = false; private File root; private long lastModified = -1l; - private Set configRepositories; + private Set configRepositories; private String toString(Feature[] features, String[] list) { StringBuffer buffer = new StringBuffer(); @@ -127,7 +130,7 @@ public class PlatformXmlListener extends DirectoryChangeListener { if (changed) { lastModified = root.lastModified(); try { - Configuration configuration = ConfigurationParser.parse(root, Activator.getOSGiInstallArea()); + Configuration configuration = Configuration.load(root, Activator.getOSGiInstallArea()); synchronizeConfiguration(configuration); } catch (ProvisionException e) { LogHelper.log(new Status(IStatus.ERROR, Activator.ID, Messages.errorProcessingConfg, e)); @@ -136,9 +139,9 @@ public class PlatformXmlListener extends DirectoryChangeListener { changed = false; } - public Collection getMetadataRepositories() { + public Collection getMetadataRepositories() { if (configRepositories == null) - return Collections.EMPTY_SET; + return CollectionUtils.emptySet(); return configRepositories; } @@ -147,12 +150,11 @@ public class PlatformXmlListener extends DirectoryChangeListener { * currently associated with the given url string. Return null if one could not * be found. */ - private IMetadataRepository getMatchingRepo(Collection repositoryList, String urlString) { + private IMetadataRepository getMatchingRepo(Collection repositoryList, String urlString) { if (repositoryList == null) return null; IPath urlPath = new Path(urlString).makeAbsolute(); - for (Iterator iter = repositoryList.iterator(); iter.hasNext();) { - IMetadataRepository repo = (IMetadataRepository) iter.next(); + for (IMetadataRepository repo : repositoryList) { Path repoPath = new Path(URIUtil.toFile(repo.getLocation()).getAbsolutePath()); if (repoPath.makeAbsolute().equals(urlPath)) return repo; @@ -179,11 +181,10 @@ public class PlatformXmlListener extends DirectoryChangeListener { * Ensure that we have a repository for each site in the given configuration. */ protected void synchronizeConfiguration(Configuration config) { - List sites = config.getSites(); - Set newRepos = new LinkedHashSet(); - Set toBeRemoved = new HashSet(); - for (Iterator iter = sites.iterator(); iter.hasNext();) { - Site site = (Site) iter.next(); + List sites = config.getSites(); + Set newRepos = new LinkedHashSet(); + Set toBeRemoved = new HashSet(); + for (Site site : sites) { String siteURL = site.getUrl(); IMetadataRepository match = getMatchingRepo(Activator.getRepositories(), siteURL); if (match == null) { @@ -202,7 +203,7 @@ public class PlatformXmlListener extends DirectoryChangeListener { } String eclipseExtensionURL = siteURL + Constants.EXTENSION_LOCATION; URI location = URIUtil.fromString(eclipseExtensionURL); - Map properties = new HashMap(); + Map properties = new HashMap(); properties.put(SiteListener.SITE_POLICY, site.getPolicy()); // In a "USER-INCLUDE" we add the site's features to the list @@ -232,10 +233,8 @@ public class PlatformXmlListener extends DirectoryChangeListener { throw inner; } // set the repository properties here in case they have changed since the last time we loaded - for (Iterator inner = properties.keySet().iterator(); inner.hasNext();) { - String key = (String) inner.next(); - String value = (String) properties.get(key); - metadataRepository.setProperty(key, value); + for (Entry entry : properties.entrySet()) { + metadataRepository.setProperty(entry.getKey(), entry.getValue()); } } newRepos.add(metadataRepository); @@ -246,9 +245,9 @@ public class PlatformXmlListener extends DirectoryChangeListener { } catch (ProvisionException ex) { IArtifactRepository artifactRepository = Activator.loadArtifactRepository(location, null); // set the repository properties here in case they have changed since the last time we loaded - for (Iterator inner = properties.keySet().iterator(); inner.hasNext();) { - String key = (String) inner.next(); - String value = (String) properties.get(key); + for (Iterator inner = properties.keySet().iterator(); inner.hasNext();) { + String key = inner.next(); + String value = properties.get(key); artifactRepository.setProperty(key, value); } } @@ -264,8 +263,8 @@ public class PlatformXmlListener extends DirectoryChangeListener { } } if (!toBeRemoved.isEmpty()) { - for (Iterator iter = toBeRemoved.iterator(); iter.hasNext();) - config.removeSite((Site) iter.next()); + for (Iterator iter = toBeRemoved.iterator(); iter.hasNext();) + config.removeSite(iter.next()); try { config.save(root, Activator.getOSGiInstallArea()); } catch (ProvisionException e) { diff --git a/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/ProfileSynchronizer.java b/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/ProfileSynchronizer.java index 6bd67780d..b2308c470 100644 --- a/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/ProfileSynchronizer.java +++ b/bundles/org.eclipse.equinox.p2.reconciler.dropins/src/org/eclipse/equinox/internal/p2/reconciler/dropins/ProfileSynchronizer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. All rights reserved. + * Copyright (c) 2007, 2010 IBM Corporation and others. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html @@ -15,20 +15,22 @@ import java.net.URISyntaxException; import java.util.*; import java.util.Map.Entry; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.core.helpers.Tracing; +import org.eclipse.equinox.internal.p2.core.helpers.*; import org.eclipse.equinox.internal.p2.extensionlocation.Constants; import org.eclipse.equinox.internal.provisional.configurator.Configurator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.query.IUProfilePropertyQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.GroupQuery; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.Collector; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.osgi.service.environment.EnvironmentInfo; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; @@ -48,17 +50,16 @@ public class ProfileSynchronizer { private static final String EXPLANATION = "org.eclipse.equinox.p2.director.explain"; //$NON-NLS-1$ final IProfile profile; - final Map repositoryMap; - private Properties timestamps; + final Map repositoryMap; + private Map timestamps; /* * Constructor for the class. */ - public ProfileSynchronizer(IProfile profile, Collection repositories) { + public ProfileSynchronizer(IProfile profile, Collection repositories) { this.profile = profile; - this.repositoryMap = new HashMap(); - for (Iterator it = repositories.iterator(); it.hasNext();) { - IMetadataRepository repository = (IMetadataRepository) it.next(); + this.repositoryMap = new HashMap(); + for (IMetadataRepository repository : repositories) { repositoryMap.put(repository.getLocation().toString(), repository); } } @@ -72,14 +73,13 @@ public class ProfileSynchronizer { return Status.OK_STATUS; ProvisioningContext context = getContext(); - context.setProperty(EXPLANATION, Boolean.FALSE.toString()); + context.setProperty(EXPLANATION, new Boolean(Tracing.DEBUG_RECONCILER).toString()); ProfileChangeRequest request = createProfileChangeRequest(context); String updatedCacheExtensions = synchronizeCacheExtensions(); if (request == null) { if (updatedCacheExtensions != null) { - Operand operand = new PropertyOperand(CACHE_EXTENSIONS, null, updatedCacheExtensions); - IStatus engineResult = executeOperands(new Operand[] {operand}, context, null); + IStatus engineResult = setProperty(CACHE_EXTENSIONS, updatedCacheExtensions, context, null); if (engineResult.getSeverity() != IStatus.ERROR && engineResult.getSeverity() != IStatus.CANCEL) writeTimestamps(); return engineResult; @@ -92,13 +92,13 @@ public class ProfileSynchronizer { SubMonitor sub = SubMonitor.convert(monitor, 100); try { //create the provisioning plan - ProvisioningPlan plan = createProvisioningPlan(request, context, sub.newChild(50)); + IProvisioningPlan plan = createProvisioningPlan(request, context, sub.newChild(50)); IStatus status = plan.getStatus(); if (status.getSeverity() == IStatus.ERROR || status.getSeverity() == IStatus.CANCEL) return status; + debug(request, plan); - Operand[] operands = plan.getOperands(); - if (operands.length == 0 || containsOnlyInstallableUnitPropertyOperandAdditions(operands)) { + if (plan.getAdditions().query(InstallableUnitQuery.ANY, null).isEmpty() && plan.getRemovals().query(InstallableUnitQuery.ANY, null).isEmpty()) { writeTimestamps(); return status; } @@ -116,31 +116,15 @@ public class ProfileSynchronizer { } } - // This is a special case that occurs where all IUs being installed are not compatible with the profile so - // the operands will have no affect if executed on the profile. - private boolean containsOnlyInstallableUnitPropertyOperandAdditions(Operand[] operands) { - for (int i = 0; i < operands.length; i++) { - if (!(operands[i] instanceof InstallableUnitPropertyOperand)) - return false; - - InstallableUnitPropertyOperand iuPropertyOperand = (InstallableUnitPropertyOperand) operands[i]; - //check if this is a removal or update - if (iuPropertyOperand.first() != null) - return false; - } - return true; - } - private void writeTimestamps() { timestamps.clear(); timestamps.put(PROFILE_TIMESTAMP, Long.toString(profile.getTimestamp())); - for (Iterator it = repositoryMap.entrySet().iterator(); it.hasNext();) { - Entry entry = (Entry) it.next(); - IMetadataRepository repository = (IMetadataRepository) entry.getValue(); - Map props = repository.getProperties(); + for (Entry entry : repositoryMap.entrySet()) { + IMetadataRepository repository = entry.getValue(); + Map props = repository.getProperties(); String timestamp = null; if (props != null) - timestamp = (String) props.get(IRepository.PROP_TIMESTAMP); + timestamp = props.get(IRepository.PROP_TIMESTAMP); if (timestamp == null) timestamp = NO_TIMESTAMP; @@ -152,7 +136,7 @@ public class ProfileSynchronizer { File file = Activator.getContext().getDataFile(TIMESTAMPS_FILE_PREFIX + profile.getProfileId().hashCode()); OutputStream os = new BufferedOutputStream(new FileOutputStream(file)); try { - timestamps.store(os, "Timestamps for " + profile.getProfileId()); //$NON-NLS-1$ + CollectionUtils.storeProperties(timestamps, os, "Timestamps for " + profile.getProfileId()); //$NON-NLS-1$ } finally { if (os != null) os.close(); @@ -169,26 +153,25 @@ public class ProfileSynchronizer { if ("true".equals(Activator.getContext().getProperty("osgi.checkConfiguration"))) //$NON-NLS-1$//$NON-NLS-2$ return false; - String lastKnownProfileTimeStamp = (String) timestamps.remove(PROFILE_TIMESTAMP); + String lastKnownProfileTimeStamp = timestamps.remove(PROFILE_TIMESTAMP); if (lastKnownProfileTimeStamp == null) return false; if (!lastKnownProfileTimeStamp.equals(Long.toString(profile.getTimestamp()))) return false; //When we get here the timestamps map only contains information related to repos - for (Iterator it = repositoryMap.entrySet().iterator(); it.hasNext();) { - Entry entry = (Entry) it.next(); - IMetadataRepository repository = (IMetadataRepository) entry.getValue(); + for (Entry entry : repositoryMap.entrySet()) { + IMetadataRepository repository = entry.getValue(); - Map props = repository.getProperties(); + Map props = repository.getProperties(); String currentTimestamp = null; if (props != null) - currentTimestamp = (String) props.get(IRepository.PROP_TIMESTAMP); + currentTimestamp = props.get(IRepository.PROP_TIMESTAMP); if (currentTimestamp == null) currentTimestamp = NO_TIMESTAMP; - String lastKnownTimestamp = (String) timestamps.remove(entry.getKey()); + String lastKnownTimestamp = timestamps.remove(entry.getKey()); //A repo has been added if (lastKnownTimestamp == null) return false; @@ -205,53 +188,54 @@ public class ProfileSynchronizer { private void readTimestamps() { File file = Activator.getContext().getDataFile(TIMESTAMPS_FILE_PREFIX + profile.getProfileId().hashCode()); - timestamps = new Properties(); try { InputStream is = new BufferedInputStream(new FileInputStream(file)); try { - timestamps.load(is); + timestamps = CollectionUtils.loadProperties(is); } finally { if (is != null) is.close(); } } catch (FileNotFoundException e) { + timestamps = new HashMap(); //Ignore } catch (IOException e) { //Ignore + timestamps = new HashMap(); } } private ProvisioningContext getContext() { - ArrayList repoURLs = new ArrayList(); - for (Iterator iterator = repositoryMap.keySet().iterator(); iterator.hasNext();) { + ArrayList repoURLs = new ArrayList(); + for (Iterator iterator = repositoryMap.keySet().iterator(); iterator.hasNext();) { try { - repoURLs.add(new URI((String) iterator.next())); + repoURLs.add(new URI(iterator.next())); } catch (URISyntaxException e) { //ignore } } - ProvisioningContext result = new ProvisioningContext((URI[]) repoURLs.toArray(new URI[repoURLs.size()])); + ProvisioningContext result = new ProvisioningContext(repoURLs.toArray(new URI[repoURLs.size()])); result.setArtifactRepositories(new URI[0]); return result; } private String synchronizeCacheExtensions() { - List currentExtensions = new ArrayList(); + List currentExtensions = new ArrayList(); StringBuffer buffer = new StringBuffer(); - List repositories = new ArrayList(repositoryMap.keySet()); + List repositories = new ArrayList(repositoryMap.keySet()); final String OSGiInstallArea = Activator.getOSGiInstallArea().toExternalForm() + Constants.EXTENSION_LOCATION; - Collections.sort(repositories, new Comparator() { - public int compare(Object left, Object right) { + Collections.sort(repositories, new Comparator() { + public int compare(String left, String right) { if (OSGiInstallArea.equals(left)) return -1; if (OSGiInstallArea.equals(right)) return 1; - return ((String) left).compareTo((String) right); + return left.compareTo(right); } }); - for (Iterator it = repositories.iterator(); it.hasNext();) { - String repositoryId = (String) it.next(); + for (Iterator it = repositories.iterator(); it.hasNext();) { + String repositoryId = it.next(); try { IArtifactRepository repository = Activator.loadArtifactRepository(new URI(repositoryId), null); @@ -270,7 +254,7 @@ public class ProfileSynchronizer { } String currentExtensionsProperty = (buffer.length() == 0) ? null : buffer.toString(); - List previousExtensions = new ArrayList(); + List previousExtensions = new ArrayList(); String previousExtensionsProperty = profile.getProperty(CACHE_EXTENSIONS); if (previousExtensionsProperty != null) { StringTokenizer tokenizer = new StringTokenizer(previousExtensionsProperty, PIPE); @@ -305,27 +289,27 @@ public class ProfileSynchronizer { if (resolve) request.removeProfileProperty("org.eclipse.equinox.p2.resolve"); //$NON-NLS-1$ - List toAdd = new ArrayList(); - List toRemove = new ArrayList(); + List toAdd = new ArrayList(); + List toRemove = new ArrayList(); boolean foundIUsToAdd = false; - Collection profileIUs = new HashSet(profile.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection()); + Set profileIUs = profile.query(InstallableUnitQuery.ANY, null).unmodifiableSet(); // we use IProfile.available(...) here so that we also gather any shared IUs - Collection availableProfileIUs = new HashSet(profile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection()); + Set availableProfileIUs = profile.available(InstallableUnitQuery.ANY, null).unmodifiableSet(); // get all IUs from all our repos (toAdd) - Collector allIUs = getAllIUsFromRepos(); - for (Iterator iter = allIUs.iterator(); iter.hasNext();) { - final IInstallableUnit iu = (IInstallableUnit) iter.next(); + IQueryResult allIUs = getAllIUsFromRepos(); + for (Iterator iter = allIUs.iterator(); iter.hasNext();) { + final IInstallableUnit iu = iter.next(); // if the IU is already installed in the profile then skip it if (!profileIUs.contains(iu)) { - if (Boolean.valueOf(iu.getProperty(IInstallableUnit.PROP_TYPE_GROUP)).booleanValue()) - request.setInstallableUnitProfileProperty(iu, IInstallableUnit.PROP_PROFILE_ROOT_IU, Boolean.TRUE.toString()); + if (GroupQuery.isGroup(iu)) + request.setInstallableUnitProfileProperty(iu, IProfile.PROP_PROFILE_ROOT_IU, Boolean.TRUE.toString()); // mark all IUs with special property request.setInstallableUnitProfileProperty(iu, PROP_FROM_DROPINS, Boolean.TRUE.toString()); request.setInstallableUnitInclusionRules(iu, PlannerHelper.createOptionalInclusionRule(iu)); - request.setInstallableUnitProfileProperty(iu, IInstallableUnit.PROP_PROFILE_LOCKED_IU, Integer.toString(IInstallableUnit.LOCK_UNINSTALL)); + request.setInstallableUnitProfileProperty(iu, IProfile.PROP_PROFILE_LOCKED_IU, Integer.toString(IProfile.LOCK_UNINSTALL)); toAdd.add(iu); // as soon as we find something locally that needs to be installed, then @@ -337,10 +321,10 @@ public class ProfileSynchronizer { } // get all IUs from profile with marked property (existing) - Collector dropinIUs = profile.query(new IUProfilePropertyQuery(PROP_FROM_DROPINS, Boolean.toString(true)), new Collector(), null); - Collection all = new HashSet(allIUs.toCollection()); - for (Iterator iter = dropinIUs.iterator(); iter.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iter.next(); + IQueryResult dropinIUs = profile.query(new IUProfilePropertyQuery(PROP_FROM_DROPINS, Boolean.toString(true)), null); + Set all = allIUs.unmodifiableSet(); + for (Iterator iter = dropinIUs.iterator(); iter.hasNext();) { + IInstallableUnit iu = iter.next(); // the STRICT policy is set when we install things via the UI, we use it to differentiate between IUs installed // via the dropins and the UI. (dropins are considered optional) If an IU has both properties set it means that // it was initially installed via the dropins but then upgraded via the UI. (properties are copied from the old IU @@ -348,7 +332,7 @@ public class ProfileSynchronizer { // will stick. if ("STRICT".equals(profile.getInstallableUnitProperty(iu, "org.eclipse.equinox.p2.internal.inclusion.rules"))) { //$NON-NLS-1$//$NON-NLS-2$ request.removeInstallableUnitProfileProperty(iu, PROP_FROM_DROPINS); - request.removeInstallableUnitProfileProperty(iu, IInstallableUnit.PROP_PROFILE_LOCKED_IU); + request.removeInstallableUnitProfileProperty(iu, IProfile.PROP_PROFILE_LOCKED_IU); continue; } // remove the IUs that are in the intersection between the 2 sets @@ -365,12 +349,47 @@ public class ProfileSynchronizer { } context.setExtraIUs(toAdd); - request.addInstallableUnits((IInstallableUnit[]) toAdd.toArray(new IInstallableUnit[toAdd.size()])); - request.removeInstallableUnits((IInstallableUnit[]) toRemove.toArray(new IInstallableUnit[toRemove.size()])); + request.addInstallableUnits(toAdd.toArray(new IInstallableUnit[toAdd.size()])); + request.removeInstallableUnits(toRemove.toArray(new IInstallableUnit[toRemove.size()])); debug(request); return request; } + private void debug(ProfileChangeRequest request, IProvisioningPlan plan) { + if (!Tracing.DEBUG_RECONCILER) + return; + final String PREFIX = "[reconciler] [plan] "; //$NON-NLS-1$ + // get the request + List toAdd = new ArrayList(); + toAdd.addAll(Arrays.asList(request.getAddedInstallableUnits())); + List toRemove = new ArrayList(); + toRemove.addAll(Arrays.asList(request.getRemovedInstallableUnits())); + // remove from the request everything what is in the plan + Operand[] ops = plan.getOperands(); + for (int i = 0; i < ops.length; i++) { + if (ops[i] instanceof InstallableUnitOperand) { + InstallableUnitOperand iuo = (InstallableUnitOperand) ops[i]; + if (iuo.first() == null && iuo.second() != null) + toAdd.remove(iuo.second()); + if (iuo.first() != null && iuo.second() == null) + toRemove.remove(iuo.first()); + } + } + // if anything is left in the request, then something is wrong with the plan + if (toAdd.size() == 0 && toRemove.size() == 0) + Tracing.debug(PREFIX + "Plan matches the request."); //$NON-NLS-1$ + if (toAdd.size() != 0) { + Tracing.debug(PREFIX + "Some units will not be installed, because they are already installed or there are dependency issues:"); //$NON-NLS-1$ + for (IInstallableUnit unit : toAdd) + Tracing.debug(PREFIX + unit); + } + if (toRemove.size() != 0) { + Tracing.debug(PREFIX + "Some units will not be uninstalled:"); //$NON-NLS-1$ + for (IInstallableUnit unit : toRemove) + Tracing.debug(PREFIX + unit); + } + } + /* * If debugging is turned on, then print out the details for the given profile change request. */ @@ -386,13 +405,12 @@ public class ProfileSynchronizer { Tracing.debug(PREFIX + "Adding IU: " + toAdd[i].getId() + ' ' + toAdd[i].getVersion()); //$NON-NLS-1$ } } - Map propsToAdd = request.getInstallableUnitProfilePropertiesToAdd(); + Map> propsToAdd = request.getInstallableUnitProfilePropertiesToAdd(); if (propsToAdd == null || propsToAdd.isEmpty()) { Tracing.debug(PREFIX + "No IU properties to add."); //$NON-NLS-1$ } else { - for (Iterator iter = propsToAdd.keySet().iterator(); iter.hasNext();) { - Object key = iter.next(); - Tracing.debug(PREFIX + "Adding IU property: " + key + "->" + propsToAdd.get(key)); //$NON-NLS-1$ //$NON-NLS-2$ + for (Entry> entry : propsToAdd.entrySet()) { + Tracing.debug(PREFIX + "Adding IU property: " + entry.getKey() + "->" + entry.getValue()); //$NON-NLS-1$ //$NON-NLS-2$ } } @@ -404,30 +422,28 @@ public class ProfileSynchronizer { Tracing.debug(PREFIX + "Removing IU: " + toRemove[i].getId() + ' ' + toRemove[i].getVersion()); //$NON-NLS-1$ } } - Map propsToRemove = request.getInstallableUnitProfilePropertiesToRemove(); + Map> propsToRemove = request.getInstallableUnitProfilePropertiesToRemove(); if (propsToRemove == null || propsToRemove.isEmpty()) { Tracing.debug(PREFIX + "No IU properties to remove."); //$NON-NLS-1$ } else { - for (Iterator iter = propsToRemove.keySet().iterator(); iter.hasNext();) { - Object key = iter.next(); - Tracing.debug(PREFIX + "Removing IU property: " + key + "->" + propsToRemove.get(key)); //$NON-NLS-1$ //$NON-NLS-2$ + for (Entry> entry : propsToRemove.entrySet()) { + Tracing.debug(PREFIX + "Removing IU property: " + entry.getKey() + "->" + entry.getValue()); //$NON-NLS-1$ //$NON-NLS-2$ } } } - private Collector getAllIUsFromRepos() { - Collector allRepos = new Collector(); - for (Iterator it = repositoryMap.entrySet().iterator(); it.hasNext();) { - Entry entry = (Entry) it.next(); - IMetadataRepository repository = (IMetadataRepository) entry.getValue(); - repository.query(InstallableUnitQuery.ANY, allRepos, null).iterator(); + private IQueryResult getAllIUsFromRepos() { + // TODO: Should consider using a sequenced iterator here instead of collecting + Collector allRepos = new Collector(); + for (IMetadataRepository repository : repositoryMap.values()) { + allRepos.addAll(repository.query(InstallableUnitQuery.ANY, null)); } return allRepos; } - private ProvisioningPlan createProvisioningPlan(ProfileChangeRequest request, ProvisioningContext provisioningContext, IProgressMonitor monitor) { + private IProvisioningPlan createProvisioningPlan(ProfileChangeRequest request, ProvisioningContext provisioningContext, IProgressMonitor monitor) { BundleContext context = Activator.getContext(); - ServiceReference reference = context.getServiceReference(IPlanner.class.getName()); + ServiceReference reference = context.getServiceReference(IPlanner.SERVICE_NAME); IPlanner planner = (IPlanner) context.getService(reference); try { @@ -437,33 +453,39 @@ public class ProfileSynchronizer { } } - private IStatus executeOperands(Operand[] operands, ProvisioningContext provisioningContext, IProgressMonitor monitor) { + private IStatus setProperty(String key, String value, ProvisioningContext provisioningContext, IProgressMonitor monitor) { BundleContext context = Activator.getContext(); - ServiceReference reference = context.getServiceReference(IEngine.class.getName()); + ServiceReference reference = context.getServiceReference(IEngine.SERVICE_NAME); IEngine engine = (IEngine) context.getService(reference); + ServiceReference plannerReference = context.getServiceReference(IPlanner.SERVICE_NAME); + IPlanner planner = (IPlanner) context.getService(reference); try { - PhaseSet phaseSet = DefaultPhaseSet.createDefaultPhaseSet(DefaultPhaseSet.PHASE_COLLECT | DefaultPhaseSet.PHASE_CHECK_TRUST); - return engine.perform(profile, phaseSet, operands, provisioningContext, monitor); + ProfileChangeRequest addPropertyRequest = new ProfileChangeRequest(profile); + addPropertyRequest.setProfileProperty(key, value); + IProvisioningPlan plan = planner.getProvisioningPlan(addPropertyRequest, provisioningContext, monitor); + IPhaseSet phaseSet = engine.createPhaseSetExcluding(new String[] {IPhaseSet.PHASE_COLLECT, IPhaseSet.PHASE_CHECK_TRUST}); + return engine.perform(plan, phaseSet, monitor); } finally { context.ungetService(reference); + context.ungetService(plannerReference); } } - private IStatus executePlan(ProvisioningPlan plan, ProvisioningContext provisioningContext, IProgressMonitor monitor) { + private IStatus executePlan(IProvisioningPlan plan, ProvisioningContext provisioningContext, IProgressMonitor monitor) { BundleContext context = Activator.getContext(); - ServiceReference reference = context.getServiceReference(IEngine.class.getName()); + ServiceReference reference = context.getServiceReference(IEngine.SERVICE_NAME); IEngine engine = (IEngine) context.getService(reference); try { - PhaseSet phaseSet = DefaultPhaseSet.createDefaultPhaseSet(DefaultPhaseSet.PHASE_COLLECT | DefaultPhaseSet.PHASE_CHECK_TRUST); + IPhaseSet phaseSet = engine.createPhaseSetExcluding(new String[] {IPhaseSet.PHASE_COLLECT, IPhaseSet.PHASE_CHECK_TRUST}); if (plan.getInstallerPlan() != null) { - IStatus installerPlanStatus = engine.perform(profile, phaseSet, plan.getInstallerPlan().getOperands(), provisioningContext, monitor); + IStatus installerPlanStatus = engine.perform(plan.getInstallerPlan(), phaseSet, monitor); if (!installerPlanStatus.isOK()) return installerPlanStatus; applyConfiguration(true); } - return engine.perform(profile, phaseSet, plan.getOperands(), provisioningContext, monitor); + return engine.perform(plan, phaseSet, monitor); } finally { context.ungetService(reference); } diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/.classpath b/bundles/org.eclipse.equinox.p2.repository.tools/.classpath index 75116d75c..834ea833e 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/.classpath +++ b/bundles/org.eclipse.equinox.p2.repository.tools/.classpath @@ -1,6 +1,6 @@ - + diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.repository.tools/.settings/org.eclipse.jdt.core.prefs index 323ecbcd2..b07f19588 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.repository.tools/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Fri Feb 27 09:31:49 EST 2009 +#Mon Dec 28 06:58:36 CET 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.builder.cleanOutputFolder=clean org.eclipse.jdt.core.builder.duplicateResourceTask=warning @@ -7,17 +7,17 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning org.eclipse.jdt.core.compiler.problem.deadCode=warning @@ -26,13 +26,13 @@ org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=warning org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=warning org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=error org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore @@ -50,6 +50,7 @@ org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=public org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning @@ -88,7 +89,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enab org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 @@ -160,7 +161,6 @@ org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.repository.tools/META-INF/MANIFEST.MF index 1498ff596..1fc3ed3de 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.repository.tools/META-INF/MANIFEST.MF @@ -5,30 +5,45 @@ Bundle-SymbolicName: org.eclipse.equinox.p2.repository.tools;singleton:=true Bundle-Version: 1.0.100.qualifier Bundle-Activator: org.eclipse.equinox.p2.internal.repository.tools.Activator Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, - J2SE-1.4 -Import-Package: org.eclipse.equinox.app;version="1.0.0", - org.eclipse.equinox.internal.p2.artifact.mirror, +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 +Import-Package: org.eclipse.core.runtime;version="3.4.0", + org.eclipse.equinox.app;version="1.0.0", org.eclipse.equinox.internal.p2.artifact.repository, org.eclipse.equinox.internal.p2.artifact.repository.simple, org.eclipse.equinox.internal.p2.core.helpers, org.eclipse.equinox.internal.p2.director, org.eclipse.equinox.internal.p2.engine, + org.eclipse.equinox.internal.p2.engine.phases, + org.eclipse.equinox.internal.p2.metadata, + org.eclipse.equinox.internal.p2.metadata.query, org.eclipse.equinox.internal.p2.metadata.repository, + org.eclipse.equinox.internal.p2.persistence, org.eclipse.equinox.internal.p2.repository.helpers, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, - org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing, org.eclipse.equinox.internal.provisional.p2.core, - org.eclipse.equinox.internal.provisional.p2.engine, - org.eclipse.equinox.internal.provisional.p2.engine.phases, + org.eclipse.equinox.internal.provisional.p2.director, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.p2.repository, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.engine.spi, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.expression, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.artifact.spi, + org.eclipse.equinox.p2.repository.metadata, + org.eclipse.equinox.p2.repository.metadata.spi, org.eclipse.osgi.util;version="1.1.0", org.osgi.framework;version="1.4.0", org.osgi.service.packageadmin;version="1.2.0" Require-Bundle: org.eclipse.equinox.common;bundle-version="3.5.0" -Export-Package: org.eclipse.equinox.p2.internal.repository.tools;x-internal:=true +Export-Package: org.eclipse.equinox.p2.internal.repository.comparator;x-internal:=true, + org.eclipse.equinox.p2.internal.repository.mirroring;x-internal:=true, + org.eclipse.equinox.p2.internal.repository.tools;x-internal:=true, + org.eclipse.equinox.p2.internal.repository.tools.analyzer;x-internal:=true, + org.eclipse.equinox.p2.repository.tools.analyzer;x-internal:=true Bundle-Vendor: %providerName Bundle-Localization: plugin diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/build.properties b/bundles/org.eclipse.equinox.p2.repository.tools/build.properties index a1a83243a..bea6ebab2 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/build.properties +++ b/bundles/org.eclipse.equinox.p2.repository.tools/build.properties @@ -21,6 +21,7 @@ jars.compile.order = ., lib/repository-tools-ant.jar source.lib/repository-tools-ant.jar = src_ant/ output.lib/repository-tools-ant.jar = bin_ant/ jars.extra.classpath=platform:/plugin/org.apache.ant/lib/ant.jar,\ - platform:/plugin/org.eclipse.equinox.p2.jarprocessor/lib/jarprocessor-ant.jar,\ - platform:/plugin/org.eclipse.equinox.p2.artifact.repository/ant_tasks/artifactRepository-ant.jar + platform:/plugin/org.eclipse.equinox.p2.jarprocessor/lib/jarprocessor-ant.jar src.includes = about.html +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/plugin.xml b/bundles/org.eclipse.equinox.p2.repository.tools/plugin.xml index 9cc4dc21d..db08b32e6 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/plugin.xml +++ b/bundles/org.eclipse.equinox.p2.repository.tools/plugin.xml @@ -2,38 +2,112 @@ - - - - - - + + + + + + + + + + + + + + + + + - - - - + + + + + + + + + + + + + + + + - - - + + - - + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/schema/org.eclipse.equinox.p2.repository.tools.verifier.exsd b/bundles/org.eclipse.equinox.p2.repository.tools/schema/org.eclipse.equinox.p2.repository.tools.verifier.exsd new file mode 100644 index 000000000..ba2d23b96 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/schema/org.eclipse.equinox.p2.repository.tools.verifier.exsd @@ -0,0 +1,109 @@ + + + + + + + + + [Enter description of this extension point.] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + [Enter the first release in which this extension point appears.] + + + + + + + + + [Enter extension point usage example here.] + + + + + + + + + [Enter API information here.] + + + + + + + + + [Enter information about supplied implementation of this extension point.] + + + + + diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Annotation.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Annotation.java deleted file mode 100644 index 2771ea6f1..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Annotation.java +++ /dev/null @@ -1,90 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class Annotation extends ClassFileStruct { - - private static final AnnotationComponent[] NO_ENTRIES = new AnnotationComponent[0]; - - private int typeIndex; - private char[] typeName; - private int componentsNumber; - private AnnotationComponent[] components; - private int readOffset; - - /** - * Constructor for Annotation. - * - * @param classFileBytes - * @param constantPool - * @param offset - * @throws ClassFormatException - */ - public Annotation(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - - final int index = u2At(classFileBytes, 0, offset); - this.typeIndex = index; - if (index != 0) { - ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.typeName = constantPoolEntry.getUtf8Value(); - } else { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - final int length = u2At(classFileBytes, 2, offset); - this.componentsNumber = length; - this.readOffset = 4; - if (length != 0) { - this.components = new AnnotationComponent[length]; - for (int i = 0; i < length; i++) { - AnnotationComponent component = new AnnotationComponent(classFileBytes, constantPool, offset + this.readOffset); - this.components[i] = component; - this.readOffset += component.sizeInBytes(); - } - } else { - this.components = NO_ENTRIES; - } - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotation#getTypeIndex() - */ - public int getTypeIndex() { - return this.typeIndex; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotation#getComponentsNumber() - */ - public int getComponentsNumber() { - return this.componentsNumber; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotation#getComponents() - */ - public AnnotationComponent[] getComponents() { - return this.components; - } - - int sizeInBytes() { - return this.readOffset; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotation#getTypeName() - */ - public char[] getTypeName() { - return this.typeName; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AnnotationComponent.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AnnotationComponent.java deleted file mode 100644 index ac8374398..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AnnotationComponent.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class AnnotationComponent extends ClassFileStruct { - - private int componentNameIndex; - private char[] componentName; - private AnnotationComponentValue componentValue; - private int readOffset; - - public AnnotationComponent(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - final int nameIndex = u2At(classFileBytes, 0, offset); - this.componentNameIndex = nameIndex; - if (nameIndex != 0) { - ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(nameIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.componentName = constantPoolEntry.getUtf8Value(); - } - this.readOffset = 2; - AnnotationComponentValue value = new AnnotationComponentValue(classFileBytes, constantPool, offset + this.readOffset); - this.componentValue = value; - this.readOffset += value.sizeInBytes(); - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponent#getComponentNameIndex() - */ - public int getComponentNameIndex() { - return this.componentNameIndex; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponent#getComponentName() - */ - public char[] getComponentName() { - return this.componentName; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponent#getComponentValue() - */ - public AnnotationComponentValue getComponentValue() { - return this.componentValue; - } - - int sizeInBytes() { - return this.readOffset; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AnnotationComponentValue.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AnnotationComponentValue.java deleted file mode 100644 index 386643914..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AnnotationComponentValue.java +++ /dev/null @@ -1,277 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class AnnotationComponentValue extends ClassFileStruct { - /** - * Tag value for a constant of type byte - * @since 3.1 - */ - public static final int BYTE_TAG = 'B'; - /** - * Tag value for a constant of type char - * @since 3.1 - */ - public static final int CHAR_TAG = 'C'; - /** - * Tag value for a constant of type double - * @since 3.1 - */ - public static final int DOUBLE_TAG = 'D'; - /** - * Tag value for a constant of type float - * @since 3.1 - */ - public static final int FLOAT_TAG = 'F'; - /** - * Tag value for a constant of type int - * @since 3.1 - */ - public static final int INTEGER_TAG = 'I'; - /** - * Tag value for a constant of type long - * @since 3.1 - */ - public static final int LONG_TAG = 'J'; - /** - * Tag value for a constant of type short - * @since 3.1 - */ - public static final int SHORT_TAG = 'S'; - /** - * Tag value for a constant of type boolean - * @since 3.1 - */ - public static final int BOOLEAN_TAG = 'Z'; - /** - * Tag value for a constant of type java.lang.String - * @since 3.1 - */ - public static final int STRING_TAG = 's'; - /** - * Tag value for a value that represents an enum constant - * @since 3.1 - */ - public static final int ENUM_TAG = 'e'; - /** - * Tag value for a value that represents a class - * @since 3.1 - */ - public static final int CLASS_TAG = 'c'; - /** - * Tag value for a value that represents an annotation - * @since 3.1 - */ - public static final int ANNOTATION_TAG = '@'; - /** - * Tag value for a value that represents an array - * @since 3.1 - */ - public static final int ARRAY_TAG = '['; - - private static final AnnotationComponentValue[] NO_VALUES = new AnnotationComponentValue[0]; - - private AnnotationComponentValue[] annotationComponentValues; - private Annotation annotationValue; - private ConstantPoolEntry classInfo; - private int classFileInfoIndex; - private ConstantPoolEntry constantValue; - private int constantValueIndex; - private int enumConstantTypeNameIndex; - private int enumConstantNameIndex; - private char[] enumConstantTypeName; - private char[] enumConstantName; - - private int readOffset; - private int tag; - private int valuesNumber; - - public AnnotationComponentValue(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - this.classFileInfoIndex = -1; - this.constantValueIndex = -1; - this.enumConstantTypeNameIndex = -1; - this.enumConstantNameIndex = -1; - final int t = u1At(classFileBytes, 0, offset); - this.tag = t; - this.readOffset = 1; - switch (t) { - case 'B' : - case 'C' : - case 'D' : - case 'F' : - case 'I' : - case 'J' : - case 'S' : - case 'Z' : - case 's' : - final int constantIndex = u2At(classFileBytes, this.readOffset, offset); - this.constantValueIndex = constantIndex; - if (constantIndex != 0) { - ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(constantIndex); - switch (constantPoolEntry.getKind()) { - case ConstantPoolConstant.CONSTANT_Long : - case ConstantPoolConstant.CONSTANT_Float : - case ConstantPoolConstant.CONSTANT_Double : - case ConstantPoolConstant.CONSTANT_Integer : - case ConstantPoolConstant.CONSTANT_Utf8 : - break; - default : - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.constantValue = constantPoolEntry; - } - this.readOffset += 2; - break; - case 'e' : - int index = u2At(classFileBytes, this.readOffset, offset); - this.enumConstantTypeNameIndex = index; - if (index != 0) { - ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.enumConstantTypeName = constantPoolEntry.getUtf8Value(); - } - this.readOffset += 2; - index = u2At(classFileBytes, this.readOffset, offset); - this.enumConstantNameIndex = index; - if (index != 0) { - ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.enumConstantName = constantPoolEntry.getUtf8Value(); - } - this.readOffset += 2; - break; - case 'c' : - final int classFileIndex = u2At(classFileBytes, this.readOffset, offset); - this.classFileInfoIndex = classFileIndex; - if (classFileIndex != 0) { - ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(classFileIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.classInfo = constantPoolEntry; - } - this.readOffset += 2; - break; - case '@' : - Annotation annotation = new Annotation(classFileBytes, constantPool, this.readOffset + offset); - this.annotationValue = annotation; - this.readOffset += annotation.sizeInBytes(); - break; - case '[' : - final int numberOfValues = u2At(classFileBytes, this.readOffset, offset); - this.valuesNumber = numberOfValues; - this.readOffset += 2; - if (numberOfValues != 0) { - this.annotationComponentValues = new AnnotationComponentValue[numberOfValues]; - for (int i = 0; i < numberOfValues; i++) { - AnnotationComponentValue value = new AnnotationComponentValue(classFileBytes, constantPool, offset + this.readOffset); - this.annotationComponentValues[i] = value; - this.readOffset += value.sizeInBytes(); - } - } else { - this.annotationComponentValues = NO_VALUES; - } - break; - } - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getAnnotationComponentValues() - */ - public AnnotationComponentValue[] getAnnotationComponentValues() { - return this.annotationComponentValues; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getAnnotationValue() - */ - public Annotation getAnnotationValue() { - return this.annotationValue; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getClassInfo() - */ - public ConstantPoolEntry getClassInfo() { - return this.classInfo; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getClassInfoIndex() - */ - public int getClassInfoIndex() { - return this.classFileInfoIndex; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getConstantValue() - */ - public ConstantPoolEntry getConstantValue() { - return this.constantValue; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getConstantValueIndex() - */ - public int getConstantValueIndex() { - return this.constantValueIndex; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getEnumConstantName() - */ - public char[] getEnumConstantName() { - return this.enumConstantName; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getEnumConstantNameIndex() - */ - public int getEnumConstantNameIndex() { - return this.enumConstantNameIndex; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getEnumConstantTypeName() - */ - public char[] getEnumConstantTypeName() { - return this.enumConstantTypeName; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getEnumConstantTypeNameIndex() - */ - public int getEnumConstantTypeNameIndex() { - return this.enumConstantTypeNameIndex; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getTag() - */ - public int getTag() { - return this.tag; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getValuesNumber() - */ - public int getValuesNumber() { - return this.valuesNumber; - } - - int sizeInBytes() { - return this.readOffset; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AnnotationDefaultAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AnnotationDefaultAttribute.java deleted file mode 100644 index a52692c20..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AnnotationDefaultAttribute.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class AnnotationDefaultAttribute extends ClassFileAttribute { - - private AnnotationComponentValue memberValue; - - /** - * Constructor for AnnotationDefaultAttribute. - * @param classFileBytes - * @param constantPool - * @param offset - * @throws ClassFormatException - */ - public AnnotationDefaultAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - super(classFileBytes, constantPool, offset); - this.memberValue = new AnnotationComponentValue(classFileBytes, constantPool, offset + 6); - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IAnnotationDefaultAttribute#getMemberValue() - */ - public AnnotationComponentValue getMemberValue() { - return this.memberValue; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AttributeNamesConstants.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AttributeNamesConstants.java deleted file mode 100644 index 3f55bfce0..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/AttributeNamesConstants.java +++ /dev/null @@ -1,142 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public interface AttributeNamesConstants { - /* - * "Synthetic" attribute. - *

    Note that prior to JDK 1.5, synthetic elements were always marked - * using an attribute; with 1.5, synthetic elements can also be marked - * using the {@link IModifierConstants#ACC_SYNTHETIC} flag. - *

    - * @since 2.0 - */ - char[] SYNTHETIC = "Synthetic".toCharArray(); //$NON-NLS-1$ - - /* - * "ConstantValue" attribute. - * @since 2.0 - */ - char[] CONSTANT_VALUE = "ConstantValue".toCharArray(); //$NON-NLS-1$ - - /* - * "LineNumberTable" attribute. - * @since 2.0 - */ - char[] LINE_NUMBER = "LineNumberTable".toCharArray(); //$NON-NLS-1$ - - /* - * "LocalVariableTable" attribute. - * @since 2.0 - */ - char[] LOCAL_VARIABLE = "LocalVariableTable".toCharArray(); //$NON-NLS-1$ - - /* - * "InnerClasses" attribute. - * @since 2.0 - */ - char[] INNER_CLASSES = "InnerClasses".toCharArray(); //$NON-NLS-1$ - - /* - * "Code" attribute. - * @since 2.0 - */ - char[] CODE = "Code".toCharArray(); //$NON-NLS-1$ - - /* - * "Exceptions" attribute. - * @since 2.0 - */ - char[] EXCEPTIONS = "Exceptions".toCharArray(); //$NON-NLS-1$ - - /* - * "SourceFile" attribute. - * @since 2.0 - */ - char[] SOURCE = "SourceFile".toCharArray(); //$NON-NLS-1$ - - /* - * "Deprecated" attribute. - * @since 2.0 - */ - char[] DEPRECATED = "Deprecated".toCharArray(); //$NON-NLS-1$ - - /* - * "Signature" attribute (added in J2SE 1.5). - * Class file readers which support J2SE 1.5 return - * attributes with this name represented by objects - * implementing {@link ISignatureAttribute}. - * @since 3.0 - */ - char[] SIGNATURE = "Signature".toCharArray(); //$NON-NLS-1$ - - /* - * "EnclosingMethod" attribute (added in J2SE 1.5). - * Class file readers which support J2SE 1.5 return - * attributes with this name represented by objects - * implementing {@link IEnclosingMethodAttribute}. - * @since 3.0 - */ - char[] ENCLOSING_METHOD = "EnclosingMethod".toCharArray(); //$NON-NLS-1$ - - /* - * "LocalVariableTypeTable" attribute (added in J2SE 1.5). - * @since 3.0 - */ - char[] LOCAL_VARIABLE_TYPE_TABLE = "LocalVariableTypeTable".toCharArray(); //$NON-NLS-1$ - - /* - * "RuntimeVisibleAnnotations" attribute (added in J2SE 1.5). - * @since 3.0 - */ - char[] RUNTIME_VISIBLE_ANNOTATIONS = "RuntimeVisibleAnnotations".toCharArray(); //$NON-NLS-1$ - - /* - * "RuntimeInvisibleAnnotations" attribute (added in J2SE 1.5). - * @since 3.0 - */ - char[] RUNTIME_INVISIBLE_ANNOTATIONS = "RuntimeInvisibleAnnotations".toCharArray(); //$NON-NLS-1$ - - /* - * "RuntimeVisibleParameterAnnotations" attribute (added in J2SE 1.5). - * @since 3.0 - */ - char[] RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS = "RuntimeVisibleParameterAnnotations".toCharArray(); //$NON-NLS-1$ - - /* - * "RuntimeInvisibleParameterAnnotations" attribute (added in J2SE 1.5). - * @since 3.0 - */ - char[] RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS = "RuntimeInvisibleParameterAnnotations".toCharArray(); //$NON-NLS-1$ - - /* - * "AnnotationDefault" attribute (added in J2SE 1.5). - * @since 3.0 - */ - char[] ANNOTATION_DEFAULT = "AnnotationDefault".toCharArray(); //$NON-NLS-1$ - - /* - * "StackMapTable" attribute (added in J2SE 1.6). - * @since 3.2 - */ - char[] STACK_MAP_TABLE = "StackMapTable".toCharArray(); //$NON-NLS-1$ - - /* - * "StackMap" attribute (added in cldc1.0). - * @since 3.2 - */ - char[] STACK_MAP = "StackMap".toCharArray(); //$NON-NLS-1$ - - /* - * "Varargs" attribute (unspecified). - */ - char[] VAR_ARGS = "Varargs".toCharArray(); //$NON-NLS-1$ -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/CharOperation.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/CharOperation.java deleted file mode 100644 index 2f1ae4d9b..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/CharOperation.java +++ /dev/null @@ -1,602 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public final class CharOperation { - public static final char[] This = "this".toCharArray(); //$NON-NLS-1$ - - public static final char[] JAVA_LANG_ANNOTATION_DOCUMENTED = "Ljava/lang/annotation/Documented;".toCharArray(); //$NON-NLS-1$ - public static final char[] JAVA_LANG_ANNOTATION_ELEMENTTYPE = "Ljava/lang/annotation/ElementType;".toCharArray(); //$NON-NLS-1$ - public static final char[] JAVA_LANG_ANNOTATION_RETENTION = "Ljava/lang/annotation/Retention;".toCharArray(); //$NON-NLS-1$ - public static final char[] JAVA_LANG_ANNOTATION_RETENTIONPOLICY = "Ljava/lang/annotation/RetentionPolicy;".toCharArray(); //$NON-NLS-1$ - public static final char[] JAVA_LANG_ANNOTATION_TARGET = "Ljava/lang/annotation/Target;".toCharArray(); //$NON-NLS-1$ - public static final char[] JAVA_LANG_DEPRECATED = "Ljava/lang/Deprecated;".toCharArray(); //$NON-NLS-1$ - public static final char[] JAVA_LANG_ANNOTATION_INHERITED = "Ljava/lang/annotation/Inherited;".toCharArray(); //$NON-NLS-1$ - /** - * Constant for an empty char array - */ - public static final char[] NO_CHAR = new char[0]; - - /** - * Constant for an empty char array with two dimensions. - */ - public static final char[][] NO_CHAR_CHAR = new char[0][]; - - /** - * Answers a hashcode for the array - * - * @param array the array for which a hashcode is required - * @return the hashcode - * @throws NullPointerException if array is null - */ - public static final int hashCode(char[] array) { - int length = array.length; - int hash = length == 0 ? 31 : array[0]; - if (length < 8) { - for (int i = length; --i > 0;) - hash = (hash * 31) + array[i]; - } else { - // 8 characters is enough to compute a decent hash code, don't waste time examining every character - for (int i = length - 1, last = i > 16 ? i - 16 : 0; i > last; i -= 2) - hash = (hash * 31) + array[i]; - } - return hash & 0x7FFFFFFF; - } - - /** - * Answers the last index in the array for which the corresponding character is - * equal to toBeFound starting from the end of the array. - * Answers -1 if no occurrence of this character is found. - *
    - *
    - * For example: - *
      - *
    1. -	 *    toBeFound = 'c'
      -	 *    array = { ' a', 'b', 'c', 'd' , 'c', 'e' }
      -	 *    result => 4
      -	 * 
      - *
    2. - *
    3. -	 *    toBeFound = 'e'
      -	 *    array = { ' a', 'b', 'c', 'd' }
      -	 *    result => -1
      -	 * 
      - *
    4. - *
    - * - * @param toBeFound the character to search - * @param array the array to be searched - * @return the last index in the array for which the corresponding character is - * equal to toBeFound starting from the end of the array, -1 otherwise - * @throws NullPointerException if array is null - */ - public static final int lastIndexOf(char toBeFound, char[] array) { - for (int i = array.length; --i >= 0;) - if (toBeFound == array[i]) - return i; - return -1; - } - - /** - * Return a new array which is the split of the given array using the given divider. - *
    - *
    - * For example: - *
      - *
    1. -	 *    divider = 'b'
      -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
      -	 *    result => { { 'a' }, {  }, { 'a' }, { 'a' } }
      -	 * 
      - *
    2. - *
    3. -	 *    divider = 'c'
      -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
      -	 *    result => { { 'a', 'b', 'b', 'a', 'b', 'a' } }
      -	 * 
      - *
    4. - *
    5. -	 *    divider = 'c'
      -	 *    array = { ' ', ' ', 'a' , 'b', 'b', 'a', 'b', 'a', ' ' }
      -	 *    result => { { ' ', 'a', 'b', 'b', 'a', 'b', 'a', ' ' } }
      -	 * 
      - *
    6. - *
    - * - * @param divider the given divider - * @param array the given array - * @return a new array which is the split of the given array using the given divider - */ - public static final char[][] splitOn(char divider, char[] array) { - int length = array == null ? 0 : array.length; - if (length == 0) - return NO_CHAR_CHAR; - - int wordCount = 1; - for (int i = 0; i < length; i++) - if (array[i] == divider) - wordCount++; - char[][] split = new char[wordCount][]; - int last = 0, currentWord = 0; - for (int i = 0; i < length; i++) { - if (array[i] == divider) { - split[currentWord] = new char[i - last]; - System.arraycopy(array, last, split[currentWord++], 0, i - last); - last = i + 1; - } - } - split[currentWord] = new char[length - last]; - System.arraycopy(array, last, split[currentWord], 0, length - last); - return split; - } - - /** - * Answers the first index in the array for which the corresponding character is - * equal to toBeFound starting the search at index start. - * Answers -1 if no occurrence of this character is found. - *
    - *
    - * For example: - *
      - *
    1. -	 *    toBeFound = 'c'
      -	 *    array = { ' a', 'b', 'c', 'd' }
      -	 *    start = 2
      -	 *    result => 2
      -	 * 
      - *
    2. - *
    3. -	 *    toBeFound = 'c'
      -	 *    array = { ' a', 'b', 'c', 'd' }
      -	 *    start = 3
      -	 *    result => -1
      -	 * 
      - *
    4. - *
    5. -	 *    toBeFound = 'e'
      -	 *    array = { ' a', 'b', 'c', 'd' }
      -	 *    start = 1
      -	 *    result => -1
      -	 * 
      - *
    6. - *
    - * - * @param toBeFound the character to search - * @param array the array to be searched - * @param start the starting index - * @return the first index in the array for which the corresponding character is - * equal to toBeFound, -1 otherwise - * @throws NullPointerException if array is null - * @throws ArrayIndexOutOfBoundsException if start is lower than 0 - */ - public static final int indexOf(char toBeFound, char[] array, int start) { - for (int i = start; i < array.length; i++) - if (toBeFound == array[i]) - return i; - return -1; - } - - /** - * Answers a new array with prepending the prefix character and appending the suffix - * character at the end of the array. If array is null, it answers a new array containing the - * prefix and the suffix characters. - *
    - *
    - * For example:
    - *
      - *
    1. -	 *    prefix = 'a'
      -	 *    array = { 'b' }
      -	 *    suffix = 'c'
      -	 *    => result = { 'a', 'b' , 'c' }
      -	 * 
      - *
    2. - *
    3. -	 *    prefix = 'a'
      -	 *    array = null
      -	 *    suffix = 'c'
      -	 *    => result = { 'a', 'c' }
      -	 * 
    4. - *
    - * - * @param prefix the prefix character - * @param array the array that is concatenated with the prefix and suffix characters - * @param suffix the suffix character - * @return the new array - */ - public static final char[] concat(char prefix, char[] array, char suffix) { - if (array == null) - return new char[] {prefix, suffix}; - - int length = array.length; - char[] result = new char[length + 2]; - result[0] = prefix; - System.arraycopy(array, 0, result, 1, length); - result[length + 1] = suffix; - return result; - } - - /** - * Answers the concatenation of the three arrays. It answers null if the three arrays are null. - * If first is null, it answers the concatenation of second and third. - * If second is null, it answers the concatenation of first and third. - * If third is null, it answers the concatenation of first and second. - *
    - *
    - * For example: - *
      - *
    1. -	 *    first = null
      -	 *    second = { 'a' }
      -	 *    third = { 'b' }
      -	 *    => result = { ' a', 'b' }
      -	 * 
      - *
    2. - *
    3. -	 *    first = { 'a' }
      -	 *    second = null
      -	 *    third = { 'b' }
      -	 *    => result = { ' a', 'b' }
      -	 * 
      - *
    4. - *
    5. -	 *    first = { 'a' }
      -	 *    second = { 'b' }
      -	 *    third = null
      -	 *    => result = { ' a', 'b' }
      -	 * 
      - *
    6. - *
    7. -	 *    first = null
      -	 *    second = null
      -	 *    third = null
      -	 *    => result = null
      -	 * 
      - *
    8. - *
    9. -	 *    first = { 'a' }
      -	 *    second = { 'b' }
      -	 *    third = { 'c' }
      -	 *    => result = { 'a', 'b', 'c' }
      -	 * 
      - *
    10. - *
    - * - * @param first the first array to concatenate - * @param second the second array to concatenate - * @param third the third array to concatenate - * - * @return the concatenation of the three arrays, or null if the three arrays are null. - */ - public static final char[] concat(char[] first, char[] second, char[] third) { - if (first == null) - return concat(second, third); - if (second == null) - return concat(first, third); - if (third == null) - return concat(first, second); - - int length1 = first.length; - int length2 = second.length; - int length3 = third.length; - char[] result = new char[length1 + length2 + length3]; - System.arraycopy(first, 0, result, 0, length1); - System.arraycopy(second, 0, result, length1, length2); - System.arraycopy(third, 0, result, length1 + length2, length3); - return result; - } - - /** - * Answers the concatenation of the two arrays. It answers null if the two arrays are null. - * If the first array is null, then the second array is returned. - * If the second array is null, then the first array is returned. - *
    - *
    - * For example: - *
      - *
    1. -	 *    first = null
      -	 *    second = { 'a' }
      -	 *    => result = { ' a' }
      -	 * 
      - *
    2. - *
    3. -	 *    first = { ' a' }
      -	 *    second = null
      -	 *    => result = { ' a' }
      -	 * 
      - *
    4. - *
    5. -	 *    first = { ' a' }
      -	 *    second = { ' b' }
      -	 *    => result = { ' a' , ' b' }
      -	 * 
      - *
    6. - *
    - * - * @param first the first array to concatenate - * @param second the second array to concatenate - * @return the concatenation of the two arrays, or null if the two arrays are null. - */ - public static final char[] concat(char[] first, char[] second) { - if (first == null) - return second; - if (second == null) - return first; - - int length1 = first.length; - int length2 = second.length; - char[] result = new char[length1 + length2]; - System.arraycopy(first, 0, result, 0, length1); - System.arraycopy(second, 0, result, length1, length2); - return result; - } - - /** - * Replace all occurrence of the character to be replaced with the replacement character in the - * given array. - *
    - *
    - * For example: - *
      - *
    1. -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
      -	 *    toBeReplaced = 'b'
      -	 *    replacementChar = 'a'
      -	 *    result => No returned value, but array is now equals to { 'a' , 'a', 'a', 'a', 'a', 'a' }
      -	 * 
      - *
    2. - *
    3. -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
      -	 *    toBeReplaced = 'c'
      -	 *    replacementChar = 'a'
      -	 *    result => No returned value, but array is now equals to { 'a' , 'b', 'b', 'a', 'b', 'a' }
      -	 * 
      - *
    4. - *
    - * - * @param array the given array - * @param toBeReplaced the character to be replaced - * @param replacementChar the replacement character - * @throws NullPointerException if the given array is null - */ - public static final void replace(char[] array, char toBeReplaced, char replacementChar) { - if (toBeReplaced != replacementChar) { - for (int i = 0, max = array.length; i < max; i++) { - if (array[i] == toBeReplaced) - array[i] = replacementChar; - } - } - } - - /** - * Replace all occurrence of the character to be replaced with the replacement character - * in a copy of the given array. Returns the given array if no occurrences of the character - * to be replaced are found. - *
    - *
    - * For example: - *
      - *
    1. -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
      -	 *    toBeReplaced = 'b'
      -	 *    replacementChar = 'a'
      -	 *    result => A new array that is equals to { 'a' , 'a', 'a', 'a', 'a', 'a' }
      -	 * 
      - *
    2. - *
    3. -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
      -	 *    toBeReplaced = 'c'
      -	 *    replacementChar = 'a'
      -	 *    result => The original array that remains unchanged.
      -	 * 
      - *
    4. - *
    - * - * @param array the given array - * @param toBeReplaced the character to be replaced - * @param replacementChar the replacement character - * @throws NullPointerException if the given array is null - * @since 3.1 - */ - public static final char[] replaceOnCopy(char[] array, char toBeReplaced, char replacementChar) { - - char[] result = null; - for (int i = 0, length = array.length; i < length; i++) { - char c = array[i]; - if (c == toBeReplaced) { - if (result == null) { - result = new char[length]; - System.arraycopy(array, 0, result, 0, i); - } - result[i] = replacementChar; - } else if (result != null) { - result[i] = c; - } - } - if (result == null) - return array; - return result; - } - - /** - * Answers the first index in the array for which the corresponding character is - * equal to toBeFound. Answers -1 if no occurrence of this character is found. - *
    - *
    - * For example: - *
      - *
    1. -	 *    toBeFound = 'c'
      -	 *    array = { ' a', 'b', 'c', 'd' }
      -	 *    result => 2
      -	 * 
      - *
    2. - *
    3. -	 *    toBeFound = 'e'
      -	 *    array = { ' a', 'b', 'c', 'd' }
      -	 *    result => -1
      -	 * 
      - *
    4. - *
    - * - * @param toBeFound the character to search - * @param array the array to be searched - * @return the first index in the array for which the corresponding character is - * equal to toBeFound, -1 otherwise - * @throws NullPointerException if array is null - */ - public static final int indexOf(char toBeFound, char[] array) { - return indexOf(toBeFound, array, 0); - } - - /** - * Answers a new array which is a copy of the given array starting at the given start and - * ending at the given end. The given start is inclusive and the given end is exclusive. - * Answers null if start is greater than end, if start is lower than 0 or if end is greater - * than the length of the given array. If end equals -1, it is converted to the array length. - *
    - *
    - * For example: - *
      - *
    1. -	 *    array = { 'a' , 'b' }
      -	 *    start = 0
      -	 *    end = 1
      -	 *    result => { 'a' }
      -	 * 
      - *
    2. - *
    3. -	 *    array = { 'a', 'b' }
      -	 *    start = 0
      -	 *    end = -1
      -	 *    result => { 'a' , 'b' }
      -	 * 
      - *
    4. - *
    - * - * @param array the given array - * @param start the given starting index - * @param end the given ending index - * @return a new array which is a copy of the given array starting at the given start and - * ending at the given end - * @throws NullPointerException if the given array is null - */ - public static final char[] subarray(char[] array, int start, int end) { - if (end == -1) - end = array.length; - if (start > end) - return null; - if (start < 0) - return null; - if (end > array.length) - return null; - - char[] result = new char[end - start]; - System.arraycopy(array, start, result, 0, end - start); - return result; - } - - /** - * Answers a new array which is a copy of the given array starting at the given start and - * ending at the given end. The given start is inclusive and the given end is exclusive. - * Answers null if start is greater than end, if start is lower than 0 or if end is greater - * than the length of the given array. If end equals -1, it is converted to the array length. - *
    - *
    - * For example: - *
      - *
    1. -	 *    array = { { 'a' } , { 'b' } }
      -	 *    start = 0
      -	 *    end = 1
      -	 *    result => { { 'a' } }
      -	 * 
      - *
    2. - *
    3. -	 *    array = { { 'a' } , { 'b' } }
      -	 *    start = 0
      -	 *    end = -1
      -	 *    result => { { 'a' }, { 'b' } }
      -	 * 
      - *
    4. - *
    - * - * @param array the given array - * @param start the given starting index - * @param end the given ending index - * @return a new array which is a copy of the given array starting at the given start and - * ending at the given end - * @throws NullPointerException if the given array is null - */ - public static final char[][] subarray(char[][] array, int start, int end) { - if (end == -1) - end = array.length; - if (start > end) - return null; - if (start < 0) - return null; - if (end > array.length) - return null; - - char[][] result = new char[end - start][]; - System.arraycopy(array, start, result, 0, end - start); - return result; - } - - /** - * Return a new array which is the split of the given array using the given divider. The given end - * is exclusive and the given start is inclusive. - *
    - *
    - * For example: - *
      - *
    1. -	 *    divider = 'b'
      -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
      -	 *    start = 2
      -	 *    end = 5
      -	 *    result => { {  }, { 'a' }, {  } }
      -	 * 
      - *
    2. - *
    - * - * @param divider the given divider - * @param array the given array - * @param start the given starting index - * @param end the given ending index - * @return a new array which is the split of the given array using the given divider - * @throws ArrayIndexOutOfBoundsException if start is lower than 0 or end is greater than the array length - */ - public static final char[][] splitOn(char divider, char[] array, int start, int end) { - int length = array == null ? 0 : array.length; - if (length == 0 || start > end) - return NO_CHAR_CHAR; - - int wordCount = 1; - for (int i = start; i < end; i++) - if (array[i] == divider) - wordCount++; - char[][] split = new char[wordCount][]; - int last = start, currentWord = 0; - for (int i = start; i < end; i++) { - if (array[i] == divider) { - split[currentWord] = new char[i - last]; - System.arraycopy(array, last, split[currentWord++], 0, i - last); - last = i + 1; - } - } - split[currentWord] = new char[end - last]; - System.arraycopy(array, last, split[currentWord], 0, end - last); - return split; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFileAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFileAttribute.java deleted file mode 100644 index 05225801f..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFileAttribute.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class ClassFileAttribute extends ClassFileStruct { - public static final ClassFileAttribute[] NO_ATTRIBUTES = new ClassFileAttribute[0]; - private long attributeLength; - private int attributeNameIndex; - private char[] attributeName; - - public ClassFileAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - this.attributeNameIndex = u2At(classFileBytes, 0, offset); - this.attributeLength = u4At(classFileBytes, 2, offset); - ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(this.attributeNameIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.attributeName = constantPoolEntry.getUtf8Value(); - } - - public int getAttributeNameIndex() { - return this.attributeNameIndex; - } - - /* - * @see IClassFileAttribute#getAttributeName() - */ - public char[] getAttributeName() { - return this.attributeName; - } - - /* - * @see IClassFileAttribute#getAttributeLength() - */ - public long getAttributeLength() { - return this.attributeLength; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFileReader.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFileReader.java deleted file mode 100644 index 61765ef09..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFileReader.java +++ /dev/null @@ -1,468 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -import java.util.Arrays; - -public class ClassFileReader extends ClassFileStruct { - /* - * This value should be used to read completely each part of a .class file. - */ - public static final int ALL = 0xFFFF; - - /* - * This value should be used to read only the constant pool entries of a .class file. - */ - public static final int CONSTANT_POOL = 0x0001; - - /* - * This value should be used to read the constant pool entries and - * the method infos of a .class file. - */ - public static final int METHOD_INFOS = 0x0002 + CONSTANT_POOL; - - /* - * This value should be used to read the constant pool entries and - * the field infos of a .class file. - */ - public static final int FIELD_INFOS = 0x0004 + CONSTANT_POOL; - - /* - * This value should be used to read the constant pool entries and - * the super interface names of a .class file. - */ - public static final int SUPER_INTERFACES = 0x0008 + CONSTANT_POOL; - - /* - * This value should be used to read the constant pool entries and - * the attributes of a .class file. - */ - public static final int CLASSFILE_ATTRIBUTES = 0x0010 + CONSTANT_POOL; - - /* - * This value should be used to read the method bodies. - * It has to be used with METHOD_INFOS. - */ - public static final int METHOD_BODIES = 0x0020; - - /* - * This value should be used to read the whole contents of the .class file except the - * method bodies. - */ - public static final int ALL_BUT_METHOD_BODIES = ALL & ~METHOD_BODIES; - - private static final FieldInfo[] NO_FIELD_INFOS = new FieldInfo[0]; - private static final char[][] NO_INTERFACES_NAMES = CharOperation.NO_CHAR_CHAR; - private static final MethodInfo[] NO_METHOD_INFOS = new MethodInfo[0]; - private int accessFlags; - private ClassFileAttribute[] attributes; - private int attributesCount; - private char[] className; - private int classNameIndex; - - private ConstantPool constantPool; - private FieldInfo[] fields; - private int fieldsCount; - private InnerClassesAttribute innerClassesAttribute; - private int[] interfaceIndexes; - private char[][] interfaceNames; - private int interfacesCount; - private int magicNumber; - private int majorVersion; - private MethodInfo[] methods; - private int methodsCount; - private int minorVersion; - private SourceFileAttribute sourceFileAttribute; - private char[] superclassName; - private int superclassNameIndex; - - /* - * Constructor for ClassFileReader. - * - * @param classFileBytes the raw bytes of the .class file - * @param decodingFlags the decoding flags - * - * @see IClassFileReader#ALL - * @see IClassFileReader#CLASSFILE_ATTRIBUTES - * @see IClassFileReader#CONSTANT_POOL - * @see IClassFileReader#FIELD_INFOS - */ - public ClassFileReader(byte[] classFileBytes, int decodingFlags) throws ClassFormatException { - - // This method looks ugly but is actually quite simple, the constantPool is constructed - // in 3 passes. All non-primitive constant pool members that usually refer to other members - // by index are tweaked to have their value in inst vars, this minor cost at read-time makes - // all subsequent uses of the constant pool element faster. - int constantPoolCount; - int[] constantPoolOffsets; - try { - this.magicNumber = (int) u4At(classFileBytes, 0, 0); - if (this.magicNumber != 0xCAFEBABE) { - throw new ClassFormatException(ClassFormatException.INVALID_MAGIC_NUMBER); - } - - int readOffset = 10; - this.minorVersion = u2At(classFileBytes, 4, 0); - this.majorVersion = u2At(classFileBytes, 6, 0); - - if ((decodingFlags & CONSTANT_POOL) == 0) { - // no need to go further - return; - } - - constantPoolCount = u2At(classFileBytes, 8, 0); - // Pass #1 - Fill in all primitive constants - constantPoolOffsets = new int[constantPoolCount]; - for (int i = 1; i < constantPoolCount; i++) { - int tag = u1At(classFileBytes, readOffset, 0); - switch (tag) { - case ConstantPoolConstant.CONSTANT_Utf8 : - constantPoolOffsets[i] = readOffset; - readOffset += u2At(classFileBytes, readOffset + 1, 0); - readOffset += ConstantPoolConstant.CONSTANT_Utf8_SIZE; - break; - case ConstantPoolConstant.CONSTANT_Integer : - constantPoolOffsets[i] = readOffset; - readOffset += ConstantPoolConstant.CONSTANT_Integer_SIZE; - break; - case ConstantPoolConstant.CONSTANT_Float : - constantPoolOffsets[i] = readOffset; - readOffset += ConstantPoolConstant.CONSTANT_Float_SIZE; - break; - case ConstantPoolConstant.CONSTANT_Long : - constantPoolOffsets[i] = readOffset; - readOffset += ConstantPoolConstant.CONSTANT_Long_SIZE; - i++; - break; - case ConstantPoolConstant.CONSTANT_Double : - constantPoolOffsets[i] = readOffset; - readOffset += ConstantPoolConstant.CONSTANT_Double_SIZE; - i++; - break; - case ConstantPoolConstant.CONSTANT_Class : - constantPoolOffsets[i] = readOffset; - readOffset += ConstantPoolConstant.CONSTANT_Class_SIZE; - break; - case ConstantPoolConstant.CONSTANT_String : - constantPoolOffsets[i] = readOffset; - readOffset += ConstantPoolConstant.CONSTANT_String_SIZE; - break; - case ConstantPoolConstant.CONSTANT_Fieldref : - constantPoolOffsets[i] = readOffset; - readOffset += ConstantPoolConstant.CONSTANT_Fieldref_SIZE; - break; - case ConstantPoolConstant.CONSTANT_Methodref : - constantPoolOffsets[i] = readOffset; - readOffset += ConstantPoolConstant.CONSTANT_Methodref_SIZE; - break; - case ConstantPoolConstant.CONSTANT_InterfaceMethodref : - constantPoolOffsets[i] = readOffset; - readOffset += ConstantPoolConstant.CONSTANT_InterfaceMethodref_SIZE; - break; - case ConstantPoolConstant.CONSTANT_NameAndType : - constantPoolOffsets[i] = readOffset; - readOffset += ConstantPoolConstant.CONSTANT_NameAndType_SIZE; - break; - default : - throw new ClassFormatException(ClassFormatException.INVALID_TAG_CONSTANT); - } - } - - this.constantPool = new ConstantPool(classFileBytes, constantPoolOffsets); - // Read and validate access flags - this.accessFlags = u2At(classFileBytes, readOffset, 0); - readOffset += 2; - - // Read the classname, use exception handlers to catch bad format - this.classNameIndex = u2At(classFileBytes, readOffset, 0); - this.className = getConstantClassNameAt(classFileBytes, constantPoolOffsets, this.classNameIndex); - readOffset += 2; - - // Read the superclass name, can be zero for java.lang.Object - this.superclassNameIndex = u2At(classFileBytes, readOffset, 0); - readOffset += 2; - // if superclassNameIndex is equals to 0 there is no need to set a value for the - // field this.superclassName. null is fine. - if (this.superclassNameIndex != 0) { - this.superclassName = getConstantClassNameAt(classFileBytes, constantPoolOffsets, this.superclassNameIndex); - } - - // Read the interfaces, use exception handlers to catch bad format - this.interfacesCount = u2At(classFileBytes, readOffset, 0); - readOffset += 2; - this.interfaceNames = NO_INTERFACES_NAMES; - this.interfaceIndexes = Utility.EMPTY_INT_ARRAY; - if (this.interfacesCount != 0) { - if ((decodingFlags & SUPER_INTERFACES) != CONSTANT_POOL) { - this.interfaceNames = new char[this.interfacesCount][]; - this.interfaceIndexes = new int[this.interfacesCount]; - for (int i = 0; i < this.interfacesCount; i++) { - this.interfaceIndexes[i] = u2At(classFileBytes, readOffset, 0); - this.interfaceNames[i] = getConstantClassNameAt(classFileBytes, constantPoolOffsets, this.interfaceIndexes[i]); - readOffset += 2; - } - } else { - readOffset += (2 * this.interfacesCount); - } - } - // Read the this.fields, use exception handlers to catch bad format - this.fieldsCount = u2At(classFileBytes, readOffset, 0); - readOffset += 2; - this.fields = NO_FIELD_INFOS; - if (this.fieldsCount != 0) { - if ((decodingFlags & FIELD_INFOS) != CONSTANT_POOL) { - FieldInfo field; - this.fields = new FieldInfo[this.fieldsCount]; - for (int i = 0; i < this.fieldsCount; i++) { - field = new FieldInfo(classFileBytes, this.constantPool, readOffset); - this.fields[i] = field; - readOffset += field.sizeInBytes(); - } - } else { - for (int i = 0; i < this.fieldsCount; i++) { - int attributeCountForField = u2At(classFileBytes, 6, readOffset); - readOffset += 8; - if (attributeCountForField != 0) { - for (int j = 0; j < attributeCountForField; j++) { - int attributeLength = (int) u4At(classFileBytes, 2, readOffset); - readOffset += (6 + attributeLength); - } - } - } - } - } - // Read the this.methods - this.methodsCount = u2At(classFileBytes, readOffset, 0); - readOffset += 2; - this.methods = NO_METHOD_INFOS; - if (this.methodsCount != 0) { - if ((decodingFlags & METHOD_INFOS) != CONSTANT_POOL) { - this.methods = new MethodInfo[this.methodsCount]; - MethodInfo method; - for (int i = 0; i < this.methodsCount; i++) { - method = new MethodInfo(classFileBytes, this.constantPool, readOffset, decodingFlags); - this.methods[i] = method; - readOffset += method.sizeInBytes(); - } - } else { - for (int i = 0; i < this.methodsCount; i++) { - int attributeCountForMethod = u2At(classFileBytes, 6, readOffset); - readOffset += 8; - if (attributeCountForMethod != 0) { - for (int j = 0; j < attributeCountForMethod; j++) { - int attributeLength = (int) u4At(classFileBytes, 2, readOffset); - readOffset += (6 + attributeLength); - } - } - } - } - } - - // Read the attributes - this.attributesCount = u2At(classFileBytes, readOffset, 0); - readOffset += 2; - - int attributesIndex = 0; - this.attributes = ClassFileAttribute.NO_ATTRIBUTES; - if (this.attributesCount != 0) { - if ((decodingFlags & CLASSFILE_ATTRIBUTES) != CONSTANT_POOL) { - this.attributes = new ClassFileAttribute[this.attributesCount]; - for (int i = 0; i < this.attributesCount; i++) { - int utf8Offset = constantPoolOffsets[u2At(classFileBytes, readOffset, 0)]; - char[] attributeName = utf8At(classFileBytes, utf8Offset + 3, 0, u2At(classFileBytes, utf8Offset + 1, 0)); - if (Arrays.equals(attributeName, AttributeNamesConstants.INNER_CLASSES)) { - this.innerClassesAttribute = new InnerClassesAttribute(classFileBytes, this.constantPool, readOffset); - this.attributes[attributesIndex++] = this.innerClassesAttribute; - } else if (Arrays.equals(attributeName, AttributeNamesConstants.SOURCE)) { - this.sourceFileAttribute = new SourceFileAttribute(classFileBytes, this.constantPool, readOffset); - this.attributes[attributesIndex++] = this.sourceFileAttribute; - } else if (Arrays.equals(attributeName, AttributeNamesConstants.ENCLOSING_METHOD)) { - this.attributes[attributesIndex++] = new EnclosingMethodAttribute(classFileBytes, this.constantPool, readOffset); - } else if (Arrays.equals(attributeName, AttributeNamesConstants.SIGNATURE)) { - this.attributes[attributesIndex++] = new SignatureAttribute(classFileBytes, this.constantPool, readOffset); - } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_VISIBLE_ANNOTATIONS)) { - this.attributes[attributesIndex++] = new RuntimeVisibleAnnotationsAttribute(classFileBytes, this.constantPool, readOffset); - } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS)) { - this.attributes[attributesIndex++] = new RuntimeInvisibleAnnotationsAttribute(classFileBytes, this.constantPool, readOffset); - } else { - this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, this.constantPool, readOffset); - } - readOffset += (6 + u4At(classFileBytes, readOffset + 2, 0)); - } - } else { - for (int i = 0; i < this.attributesCount; i++) { - readOffset += (6 + u4At(classFileBytes, readOffset + 2, 0)); - } - } - } - if (readOffset != classFileBytes.length) { - throw new ClassFormatException(ClassFormatException.TOO_MANY_BYTES); - } - } catch (ClassFormatException e) { - throw e; - } catch (Exception e) { - e.printStackTrace(); - throw new ClassFormatException(ClassFormatException.ERROR_TRUNCATED_INPUT); - } - } - - /* - * @see IClassFileReader#getAccessFlags() - */ - public int getAccessFlags() { - return this.accessFlags; - } - - /* - * @see IClassFileReader#getAttributeCount() - */ - public int getAttributeCount() { - return this.attributesCount; - } - - /* - * @see IClassFileReader#getAttributes() - */ - public ClassFileAttribute[] getAttributes() { - return this.attributes; - } - - /* - * @see IClassFileReader#getClassIndex() - */ - public int getClassIndex() { - return this.classNameIndex; - } - - /* - * @see IClassFileReader#getClassName() - */ - public char[] getClassName() { - return this.className; - } - - private char[] getConstantClassNameAt(byte[] classFileBytes, int[] constantPoolOffsets, int constantPoolIndex) { - int utf8Offset = constantPoolOffsets[u2At(classFileBytes, constantPoolOffsets[constantPoolIndex] + 1, 0)]; - return utf8At(classFileBytes, utf8Offset + 3, 0, u2At(classFileBytes, utf8Offset + 1, 0)); - } - - /* - * @see IClassFileReader#getConstantPool() - */ - public ConstantPool getConstantPool() { - return this.constantPool; - } - - /* - * @see IClassFileReader#getFieldInfos() - */ - public FieldInfo[] getFieldInfos() { - return this.fields; - } - - /* - * @see IClassFileReader#getFieldsCount() - */ - public int getFieldsCount() { - return this.fieldsCount; - } - - /* - * @see IClassFileReader#getInnerClassesAttribute() - */ - public InnerClassesAttribute getInnerClassesAttribute() { - return this.innerClassesAttribute; - } - - /* - * @see IClassFileReader#getInterfaceIndexes() - */ - public int[] getInterfaceIndexes() { - return this.interfaceIndexes; - } - - /* - * @see IClassFileReader#getInterfaceNames() - */ - public char[][] getInterfaceNames() { - return this.interfaceNames; - } - - /* - * @see IClassFileReader#getMagic() - */ - public int getMagic() { - return this.magicNumber; - } - - /* - * @see IClassFileReader#getMajorVersion() - */ - public int getMajorVersion() { - return this.majorVersion; - } - - /* - * @see IClassFileReader#getMethodInfos() - */ - public MethodInfo[] getMethodInfos() { - return this.methods; - } - - /* - * @see IClassFileReader#getMethodsCount() - */ - public int getMethodsCount() { - return this.methodsCount; - } - - /* - * @see IClassFileReader#getMinorVersion() - */ - public int getMinorVersion() { - return this.minorVersion; - } - - /* - * @see IClassFileReader#getSourceFileAttribute() - */ - public SourceFileAttribute getSourceFileAttribute() { - return this.sourceFileAttribute; - } - - /* - * @see IClassFileReader#getSuperclassIndex() - */ - public int getSuperclassIndex() { - return this.superclassNameIndex; - } - - /* - * @see IClassFileReader#getSuperclassName() - */ - public char[] getSuperclassName() { - return this.superclassName; - } - - /* - * @see IClassFileReader#isClass() - */ - public boolean isClass() { - return !isInterface(); - } - - /* - * @see IClassFileReader#isInterface() - */ - public boolean isInterface() { - return (getAccessFlags() & IModifierConstants.ACC_INTERFACE) != 0; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFileStruct.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFileStruct.java deleted file mode 100644 index a8c6038e3..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFileStruct.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public abstract class ClassFileStruct { - - protected double doubleAt(byte[] reference, int relativeOffset, int structOffset) { - return (Double.longBitsToDouble(i8At(reference, relativeOffset, structOffset))); - } - - protected float floatAt(byte[] reference, int relativeOffset, int structOffset) { - return (Float.intBitsToFloat(i4At(reference, relativeOffset, structOffset))); - } - - protected int i1At(byte[] reference, int relativeOffset, int structOffset) { - return reference[relativeOffset + structOffset]; - } - - protected int i2At(byte[] reference, int relativeOffset, int structOffset) { - int position = relativeOffset + structOffset; - return (reference[position++] << 8) + (reference[position] & 0xFF); - } - - protected int i4At(byte[] reference, int relativeOffset, int structOffset) { - int position = relativeOffset + structOffset; - return ((reference[position++] & 0xFF) << 24) + ((reference[position++] & 0xFF) << 16) + ((reference[position++] & 0xFF) << 8) + (reference[position] & 0xFF); - } - - protected long i8At(byte[] reference, int relativeOffset, int structOffset) { - int position = relativeOffset + structOffset; - return (((long) (reference[position++] & 0xFF)) << 56) + (((long) (reference[position++] & 0xFF)) << 48) + (((long) (reference[position++] & 0xFF)) << 40) + (((long) (reference[position++] & 0xFF)) << 32) + (((long) (reference[position++] & 0xFF)) << 24) + (((long) (reference[position++] & 0xFF)) << 16) + (((long) (reference[position++] & 0xFF)) << 8) + (reference[position++] & 0xFF); - } - - protected int u1At(byte[] reference, int relativeOffset, int structOffset) { - return (reference[relativeOffset + structOffset] & 0xFF); - } - - protected int u2At(byte[] reference, int relativeOffset, int structOffset) { - int position = relativeOffset + structOffset; - return ((reference[position++] & 0xFF) << 8) + (reference[position] & 0xFF); - } - - protected long u4At(byte[] reference, int relativeOffset, int structOffset) { - int position = relativeOffset + structOffset; - return (((reference[position++] & 0xFFL) << 24) + ((reference[position++] & 0xFF) << 16) + ((reference[position++] & 0xFF) << 8) + (reference[position] & 0xFF)); - } - - protected char[] utf8At(byte[] reference, int relativeOffset, int structOffset, int bytesAvailable) { - int length = bytesAvailable; - char outputBuf[] = new char[bytesAvailable]; - int outputPos = 0; - int readOffset = structOffset + relativeOffset; - - while (length != 0) { - int x = reference[readOffset++] & 0xFF; - length--; - if ((0x80 & x) != 0) { - if ((x & 0x20) != 0) { - length -= 2; - x = ((x & 0xF) << 12) + ((reference[readOffset++] & 0x3F) << 6) + (reference[readOffset++] & 0x3F); - } else { - length--; - x = ((x & 0x1F) << 6) + (reference[readOffset++] & 0x3F); - } - } - outputBuf[outputPos++] = (char) x; - } - - if (outputPos != bytesAvailable) { - System.arraycopy(outputBuf, 0, (outputBuf = new char[outputPos]), 0, outputPos); - } - return outputBuf; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFormatException.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFormatException.java deleted file mode 100644 index acff39c2c..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ClassFormatException.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class ClassFormatException extends Exception { - - public static final int ERROR_MALFORMED_UTF8 = 1; - public static final int ERROR_TRUNCATED_INPUT = 2; - public static final int INVALID_CONSTANT_POOL_ENTRY = 3; - public static final int TOO_MANY_BYTES = 4; - public static final int INVALID_ARGUMENTS_FOR_INVOKEINTERFACE = 5; - public static final int INVALID_BYTECODE = 6; - - /** - * @since 3.0 - */ - public static final int INVALID_TAG_CONSTANT = 7; - - /** - * @since 3.0 - */ - public static final int INVALID_MAGIC_NUMBER = 8; - - private static final long serialVersionUID = 6582900558320612988L; // backward compatible - - /** - * Constructor for ClassFormatException. - * @param errorID the given error ID - */ - public ClassFormatException(int errorID) { - // TODO (olivier) what is the errorID? - } - - /** - * Constructor for ClassFormatException. - * @param message the message for the exception - */ - public ClassFormatException(String message) { - super(message); - } - - /** - * Constructor for ClassFormatException. - * @param message the message for the exception - * @param cause the cause of the exception - * @since 3.5 - */ - public ClassFormatException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/CodeAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/CodeAttribute.java deleted file mode 100644 index 97884685a..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/CodeAttribute.java +++ /dev/null @@ -1,1114 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class CodeAttribute extends ClassFileAttribute { - private static final ExceptionTableEntry[] NO_EXCEPTION_TABLE = new ExceptionTableEntry[0]; - private ClassFileAttribute[] attributes; - private int attributesCount; - private byte[] bytecodes; - private byte[] classFileBytes; - private long codeLength; - private int codeOffset; - private ConstantPool constantPool; - private ExceptionTableEntry[] exceptionTableEntries; - private int exceptionTableLength; - private int maxLocals; - private int maxStack; - - CodeAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - super(classFileBytes, constantPool, offset); - this.classFileBytes = classFileBytes; - this.constantPool = constantPool; - this.maxStack = u2At(classFileBytes, 6, offset); - this.maxLocals = u2At(classFileBytes, 8, offset); - this.codeLength = u4At(classFileBytes, 10, offset); - this.codeOffset = offset + 14; - int readOffset = (int) (14 + this.codeLength); - this.exceptionTableLength = u2At(classFileBytes, readOffset, offset); - readOffset += 2; - this.exceptionTableEntries = NO_EXCEPTION_TABLE; - if (this.exceptionTableLength != 0) { - this.exceptionTableEntries = new ExceptionTableEntry[this.exceptionTableLength]; - for (int i = 0; i < this.exceptionTableLength; i++) { - this.exceptionTableEntries[i] = new ExceptionTableEntry(classFileBytes, constantPool, offset + readOffset); - readOffset += 8; - } - } - this.attributesCount = u2At(classFileBytes, readOffset, offset); - this.attributes = ClassFileAttribute.NO_ATTRIBUTES; - if (this.attributesCount != 0) { - this.attributes = new ClassFileAttribute[this.attributesCount]; - } - readOffset += 2; - for (int i = 0; i < this.attributesCount; i++) { - ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(u2At(classFileBytes, readOffset, offset)); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - readOffset += (6 + u4At(classFileBytes, readOffset + 2, offset)); - } - } - - /* - * @see ICodeAttribute#getAttributes() - */ - public ClassFileAttribute[] getAttributes() { - return this.attributes; - } - - /* - * @see ICodeAttribute#getAttributesCount() - */ - public int getAttributesCount() { - return this.attributesCount; - } - - /* - * @see ICodeAttribute#getBytecodes() - */ - public byte[] getBytecodes() { - if (this.bytecodes == null) { - System.arraycopy(this.classFileBytes, this.codeOffset, (this.bytecodes = new byte[(int) this.codeLength]), 0, (int) this.codeLength); - } - return this.bytecodes; - } - - /* - * @see ICodeAttribute#getCodeLength() - */ - public long getCodeLength() { - return this.codeLength; - } - - /* - * @see ICodeAttribute#getExceptionTable() - */ - public ExceptionTableEntry[] getExceptionTable() { - return this.exceptionTableEntries; - } - - /* - * @see ICodeAttribute#getExceptionTableLength() - */ - public int getExceptionTableLength() { - return this.exceptionTableLength; - } - - /* - * @see ICodeAttribute#getMaxLocals() - */ - public int getMaxLocals() { - return this.maxLocals; - } - - /* - * @see ICodeAttribute#getMaxStack() - */ - public int getMaxStack() { - return this.maxStack; - } - - /* - * @see ICodeAttribute#traverse(IBytecodeVisitor visitor) - */ - public void traverse(DefaultBytecodeVisitor visitor) throws ClassFormatException { - int pc = this.codeOffset; - int opcode, index, _const, branchOffset; - ConstantPoolEntry constantPoolEntry; - while (true) { - opcode = u1At(this.classFileBytes, 0, pc); - switch (opcode) { - case IOpcodeMnemonics.NOP : - visitor._nop(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ACONST_NULL : - visitor._aconst_null(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ICONST_M1 : - visitor._iconst_m1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ICONST_0 : - visitor._iconst_0(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ICONST_1 : - visitor._iconst_1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ICONST_2 : - visitor._iconst_2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ICONST_3 : - visitor._iconst_3(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ICONST_4 : - visitor._iconst_4(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ICONST_5 : - visitor._iconst_5(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LCONST_0 : - visitor._lconst_0(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LCONST_1 : - visitor._lconst_1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FCONST_0 : - visitor._fconst_0(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FCONST_1 : - visitor._fconst_1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FCONST_2 : - visitor._fconst_2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DCONST_0 : - visitor._dconst_0(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DCONST_1 : - visitor._dconst_1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.BIPUSH : - visitor._bipush(pc - this.codeOffset, (byte) i1At(this.classFileBytes, 1, pc)); - pc += 2; - break; - case IOpcodeMnemonics.SIPUSH : - visitor._sipush(pc - this.codeOffset, (short) i2At(this.classFileBytes, 1, pc)); - pc += 3; - break; - case IOpcodeMnemonics.LDC : - index = u1At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Float && constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Integer && constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_String && constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - visitor._ldc(pc - this.codeOffset, index, constantPoolEntry); - pc += 2; - break; - case IOpcodeMnemonics.LDC_W : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Float && constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Integer && constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_String && constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - visitor._ldc_w(pc - this.codeOffset, index, constantPoolEntry); - pc += 3; - break; - case IOpcodeMnemonics.LDC2_W : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Double && constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Long) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - visitor._ldc2_w(pc - this.codeOffset, index, constantPoolEntry); - pc += 3; - break; - case IOpcodeMnemonics.ILOAD : - index = u1At(this.classFileBytes, 1, pc); - visitor._iload(pc - this.codeOffset, index); - pc += 2; - break; - case IOpcodeMnemonics.LLOAD : - index = u1At(this.classFileBytes, 1, pc); - visitor._lload(pc - this.codeOffset, index); - pc += 2; - break; - case IOpcodeMnemonics.FLOAD : - index = u1At(this.classFileBytes, 1, pc); - visitor._fload(pc - this.codeOffset, index); - pc += 2; - break; - case IOpcodeMnemonics.DLOAD : - index = u1At(this.classFileBytes, 1, pc); - visitor._dload(pc - this.codeOffset, index); - pc += 2; - break; - case IOpcodeMnemonics.ALOAD : - index = u1At(this.classFileBytes, 1, pc); - visitor._aload(pc - this.codeOffset, index); - pc += 2; - break; - case IOpcodeMnemonics.ILOAD_0 : - visitor._iload_0(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ILOAD_1 : - visitor._iload_1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ILOAD_2 : - visitor._iload_2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ILOAD_3 : - visitor._iload_3(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LLOAD_0 : - visitor._lload_0(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LLOAD_1 : - visitor._lload_1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LLOAD_2 : - visitor._lload_2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LLOAD_3 : - visitor._lload_3(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FLOAD_0 : - visitor._fload_0(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FLOAD_1 : - visitor._fload_1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FLOAD_2 : - visitor._fload_2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FLOAD_3 : - visitor._fload_3(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DLOAD_0 : - visitor._dload_0(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DLOAD_1 : - visitor._dload_1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DLOAD_2 : - visitor._dload_2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DLOAD_3 : - visitor._dload_3(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ALOAD_0 : - visitor._aload_0(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ALOAD_1 : - visitor._aload_1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ALOAD_2 : - visitor._aload_2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ALOAD_3 : - visitor._aload_3(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.IALOAD : - visitor._iaload(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LALOAD : - visitor._laload(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FALOAD : - visitor._faload(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DALOAD : - visitor._daload(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.AALOAD : - visitor._aaload(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.BALOAD : - visitor._baload(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.CALOAD : - visitor._caload(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.SALOAD : - visitor._saload(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ISTORE : - index = u1At(this.classFileBytes, 1, pc); - visitor._istore(pc - this.codeOffset, index); - pc += 2; - break; - case IOpcodeMnemonics.LSTORE : - index = u1At(this.classFileBytes, 1, pc); - visitor._lstore(pc - this.codeOffset, index); - pc += 2; - break; - case IOpcodeMnemonics.FSTORE : - index = u1At(this.classFileBytes, 1, pc); - visitor._fstore(pc - this.codeOffset, index); - pc += 2; - break; - case IOpcodeMnemonics.DSTORE : - index = u1At(this.classFileBytes, 1, pc); - visitor._dstore(pc - this.codeOffset, index); - pc += 2; - break; - case IOpcodeMnemonics.ASTORE : - index = u1At(this.classFileBytes, 1, pc); - visitor._astore(pc - this.codeOffset, index); - pc += 2; - break; - case IOpcodeMnemonics.ISTORE_0 : - visitor._istore_0(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ISTORE_1 : - visitor._istore_1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ISTORE_2 : - visitor._istore_2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ISTORE_3 : - visitor._istore_3(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LSTORE_0 : - visitor._lstore_0(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LSTORE_1 : - visitor._lstore_1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LSTORE_2 : - visitor._lstore_2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LSTORE_3 : - visitor._lstore_3(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FSTORE_0 : - visitor._fstore_0(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FSTORE_1 : - visitor._fstore_1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FSTORE_2 : - visitor._fstore_2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FSTORE_3 : - visitor._fstore_3(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DSTORE_0 : - visitor._dstore_0(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DSTORE_1 : - visitor._dstore_1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DSTORE_2 : - visitor._dstore_2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DSTORE_3 : - visitor._dstore_3(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ASTORE_0 : - visitor._astore_0(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ASTORE_1 : - visitor._astore_1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ASTORE_2 : - visitor._astore_2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ASTORE_3 : - visitor._astore_3(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.IASTORE : - visitor._iastore(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LASTORE : - visitor._lastore(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FASTORE : - visitor._fastore(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DASTORE : - visitor._dastore(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.AASTORE : - visitor._aastore(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.BASTORE : - visitor._bastore(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.CASTORE : - visitor._castore(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.SASTORE : - visitor._sastore(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.POP : - visitor._pop(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.POP2 : - visitor._pop2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DUP : - visitor._dup(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DUP_X1 : - visitor._dup_x1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DUP_X2 : - visitor._dup_x2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DUP2 : - visitor._dup2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DUP2_X1 : - visitor._dup2_x1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DUP2_X2 : - visitor._dup2_x2(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.SWAP : - visitor._swap(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.IADD : - visitor._iadd(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LADD : - visitor._ladd(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FADD : - visitor._fadd(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DADD : - visitor._dadd(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ISUB : - visitor._isub(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LSUB : - visitor._lsub(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FSUB : - visitor._fsub(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DSUB : - visitor._dsub(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.IMUL : - visitor._imul(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LMUL : - visitor._lmul(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FMUL : - visitor._fmul(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DMUL : - visitor._dmul(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.IDIV : - visitor._idiv(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LDIV : - visitor._ldiv(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FDIV : - visitor._fdiv(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DDIV : - visitor._ddiv(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.IREM : - visitor._irem(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LREM : - visitor._lrem(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FREM : - visitor._frem(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DREM : - visitor._drem(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.INEG : - visitor._ineg(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LNEG : - visitor._lneg(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FNEG : - visitor._fneg(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DNEG : - visitor._dneg(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ISHL : - visitor._ishl(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LSHL : - visitor._lshl(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ISHR : - visitor._ishr(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LSHR : - visitor._lshr(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.IUSHR : - visitor._iushr(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LUSHR : - visitor._lushr(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.IAND : - visitor._iand(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LAND : - visitor._land(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.IOR : - visitor._ior(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LOR : - visitor._lor(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.IXOR : - visitor._ixor(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LXOR : - visitor._lxor(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.IINC : - index = u1At(this.classFileBytes, 1, pc); - _const = i1At(this.classFileBytes, 2, pc); - visitor._iinc(pc - this.codeOffset, index, _const); - pc += 3; - break; - case IOpcodeMnemonics.I2L : - visitor._i2l(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.I2F : - visitor._i2f(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.I2D : - visitor._i2d(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.L2I : - visitor._l2i(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.L2F : - visitor._l2f(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.L2D : - visitor._l2d(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.F2I : - visitor._f2i(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.F2L : - visitor._f2l(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.F2D : - visitor._f2d(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.D2I : - visitor._d2i(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.D2L : - visitor._d2l(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.D2F : - visitor._d2f(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.I2B : - visitor._i2b(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.I2C : - visitor._i2c(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.I2S : - visitor._i2s(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LCMP : - visitor._lcmp(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FCMPL : - visitor._fcmpl(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FCMPG : - visitor._fcmpg(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DCMPL : - visitor._dcmpl(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DCMPG : - visitor._dcmpg(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.IFEQ : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._ifeq(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.IFNE : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._ifne(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.IFLT : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._iflt(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.IFGE : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._ifge(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.IFGT : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._ifgt(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.IFLE : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._ifle(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.IF_ICMPEQ : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._if_icmpeq(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.IF_ICMPNE : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._if_icmpne(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.IF_ICMPLT : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._if_icmplt(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.IF_ICMPGE : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._if_icmpge(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.IF_ICMPGT : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._if_icmpgt(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.IF_ICMPLE : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._if_icmple(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.IF_ACMPEQ : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._if_acmpeq(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.IF_ACMPNE : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._if_acmpne(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.GOTO : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._goto(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.JSR : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._jsr(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.RET : - index = u1At(this.classFileBytes, 1, pc); - visitor._ret(pc - this.codeOffset, index); - pc += 2; - break; - case IOpcodeMnemonics.TABLESWITCH : - int startpc = pc; - pc++; - while (((pc - this.codeOffset) & 0x03) != 0) { // faster than % 4 - pc++; - } - int defaultOffset = i4At(this.classFileBytes, 0, pc); - pc += 4; - int low = i4At(this.classFileBytes, 0, pc); - pc += 4; - int high = i4At(this.classFileBytes, 0, pc); - pc += 4; - int length = high - low + 1; - int[] jumpOffsets = new int[length]; - for (int i = 0; i < length; i++) { - jumpOffsets[i] = i4At(this.classFileBytes, 0, pc); - pc += 4; - } - visitor._tableswitch(startpc - this.codeOffset, defaultOffset, low, high, jumpOffsets); - break; - case IOpcodeMnemonics.LOOKUPSWITCH : - startpc = pc; - pc++; - while (((pc - this.codeOffset) & 0x03) != 0) { - pc++; - } - defaultOffset = i4At(this.classFileBytes, 0, pc); - pc += 4; - int npairs = (int) u4At(this.classFileBytes, 0, pc); - int[][] offset_pairs = new int[npairs][2]; - pc += 4; - for (int i = 0; i < npairs; i++) { - offset_pairs[i][0] = i4At(this.classFileBytes, 0, pc); - pc += 4; - offset_pairs[i][1] = i4At(this.classFileBytes, 0, pc); - pc += 4; - } - visitor._lookupswitch(startpc - this.codeOffset, defaultOffset, npairs, offset_pairs); - break; - case IOpcodeMnemonics.IRETURN : - visitor._ireturn(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.LRETURN : - visitor._lreturn(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.FRETURN : - visitor._freturn(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.DRETURN : - visitor._dreturn(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ARETURN : - visitor._areturn(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.RETURN : - visitor._return(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.GETSTATIC : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Fieldref) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - visitor._getstatic(pc - this.codeOffset, index, constantPoolEntry); - pc += 3; - break; - case IOpcodeMnemonics.PUTSTATIC : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Fieldref) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - visitor._putstatic(pc - this.codeOffset, index, constantPoolEntry); - pc += 3; - break; - case IOpcodeMnemonics.GETFIELD : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Fieldref) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - visitor._getfield(pc - this.codeOffset, index, constantPoolEntry); - pc += 3; - break; - case IOpcodeMnemonics.PUTFIELD : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Fieldref) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - visitor._putfield(pc - this.codeOffset, index, constantPoolEntry); - pc += 3; - break; - case IOpcodeMnemonics.INVOKEVIRTUAL : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Methodref) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - visitor._invokevirtual(pc - this.codeOffset, index, constantPoolEntry); - pc += 3; - break; - case IOpcodeMnemonics.INVOKESPECIAL : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Methodref) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - visitor._invokespecial(pc - this.codeOffset, index, constantPoolEntry); - pc += 3; - break; - case IOpcodeMnemonics.INVOKESTATIC : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Methodref) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - visitor._invokestatic(pc - this.codeOffset, index, constantPoolEntry); - pc += 3; - break; - case IOpcodeMnemonics.INVOKEINTERFACE : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_InterfaceMethodref) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - byte count = (byte) u1At(this.classFileBytes, 3, pc); - int extraArgs = u1At(this.classFileBytes, 4, pc); - if (extraArgs != 0) { - throw new ClassFormatException(ClassFormatException.INVALID_ARGUMENTS_FOR_INVOKEINTERFACE); - } - visitor._invokeinterface(pc - this.codeOffset, index, count, constantPoolEntry); - pc += 5; - break; - case IOpcodeMnemonics.NEW : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - visitor._new(pc - this.codeOffset, index, constantPoolEntry); - pc += 3; - break; - case IOpcodeMnemonics.NEWARRAY : - int atype = u1At(this.classFileBytes, 1, pc); - visitor._newarray(pc - this.codeOffset, atype); - pc += 2; - break; - case IOpcodeMnemonics.ANEWARRAY : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - visitor._anewarray(pc - this.codeOffset, index, constantPoolEntry); - pc += 3; - break; - case IOpcodeMnemonics.ARRAYLENGTH : - visitor._arraylength(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.ATHROW : - visitor._athrow(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.CHECKCAST : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - visitor._checkcast(pc - this.codeOffset, index, constantPoolEntry); - pc += 3; - break; - case IOpcodeMnemonics.INSTANCEOF : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - visitor._instanceof(pc - this.codeOffset, index, constantPoolEntry); - pc += 3; - break; - case IOpcodeMnemonics.MONITORENTER : - visitor._monitorenter(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.MONITOREXIT : - visitor._monitorexit(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.WIDE : - opcode = u1At(this.classFileBytes, 1, pc); - if (opcode == IOpcodeMnemonics.IINC) { - index = u2At(this.classFileBytes, 2, pc); - _const = i2At(this.classFileBytes, 4, pc); - visitor._wide(pc - this.codeOffset, opcode, index, _const); - pc += 6; - } else { - index = u2At(this.classFileBytes, 2, pc); - visitor._wide(pc - this.codeOffset, opcode, index); - pc += 4; - } - break; - case IOpcodeMnemonics.MULTIANEWARRAY : - index = u2At(this.classFileBytes, 1, pc); - constantPoolEntry = this.constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - int dimensions = u1At(this.classFileBytes, 3, pc); - visitor._multianewarray(pc - this.codeOffset, index, dimensions, constantPoolEntry); - pc += 4; - break; - case IOpcodeMnemonics.IFNULL : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._ifnull(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.IFNONNULL : - branchOffset = i2At(this.classFileBytes, 1, pc); - visitor._ifnonnull(pc - this.codeOffset, branchOffset); - pc += 3; - break; - case IOpcodeMnemonics.GOTO_W : - branchOffset = i4At(this.classFileBytes, 1, pc); - visitor._goto_w(pc - this.codeOffset, branchOffset); - pc += 5; - break; - case IOpcodeMnemonics.JSR_W : - branchOffset = i4At(this.classFileBytes, 1, pc); - visitor._jsr_w(pc - this.codeOffset, branchOffset); - pc += 5; - break; - case IOpcodeMnemonics.BREAKPOINT : - visitor._breakpoint(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.IMPDEP1 : - visitor._impdep1(pc - this.codeOffset); - pc++; - break; - case IOpcodeMnemonics.IMPDEP2 : - visitor._impdep2(pc - this.codeOffset); - pc++; - break; - default : - throw new ClassFormatException(ClassFormatException.INVALID_BYTECODE); - } - if (pc >= (this.codeLength + this.codeOffset)) { - break; - } - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantPool.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantPool.java deleted file mode 100644 index 380108600..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantPool.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class ConstantPool extends ClassFileStruct { - - private int constantPoolCount; - private int[] constantPoolOffset; - private byte[] classFileBytes; - - ConstantPool(byte[] reference, int[] constantPoolOffset) { - this.constantPoolCount = constantPoolOffset.length; - this.constantPoolOffset = constantPoolOffset; - this.classFileBytes = reference; - } - - /* - * @see IConstantPool#decodeEntry(int) - */ - public ConstantPoolEntry decodeEntry(int index) { - ConstantPoolEntry constantPoolEntry = new ConstantPoolEntry(); - constantPoolEntry.reset(); - int kind = getEntryKind(index); - constantPoolEntry.setKind(kind); - switch (kind) { - case ConstantPoolConstant.CONSTANT_Class : - constantPoolEntry.setClassInfoNameIndex(u2At(this.classFileBytes, 1, this.constantPoolOffset[index])); - constantPoolEntry.setClassInfoName(getUtf8ValueAt(constantPoolEntry.getClassInfoNameIndex())); - break; - case ConstantPoolConstant.CONSTANT_Double : - constantPoolEntry.setDoubleValue(doubleAt(this.classFileBytes, 1, this.constantPoolOffset[index])); - break; - case ConstantPoolConstant.CONSTANT_Fieldref : - constantPoolEntry.setClassIndex(u2At(this.classFileBytes, 1, this.constantPoolOffset[index])); - int declaringClassIndex = u2At(this.classFileBytes, 1, this.constantPoolOffset[constantPoolEntry.getClassIndex()]); - constantPoolEntry.setClassName(getUtf8ValueAt(declaringClassIndex)); - constantPoolEntry.setNameAndTypeIndex(u2At(this.classFileBytes, 3, this.constantPoolOffset[index])); - int fieldNameIndex = u2At(this.classFileBytes, 1, this.constantPoolOffset[constantPoolEntry.getNameAndTypeIndex()]); - int fieldDescriptorIndex = u2At(this.classFileBytes, 3, this.constantPoolOffset[constantPoolEntry.getNameAndTypeIndex()]); - constantPoolEntry.setFieldName(getUtf8ValueAt(fieldNameIndex)); - constantPoolEntry.setFieldDescriptor(getUtf8ValueAt(fieldDescriptorIndex)); - break; - case ConstantPoolConstant.CONSTANT_Methodref : - case ConstantPoolConstant.CONSTANT_InterfaceMethodref : - constantPoolEntry.setClassIndex(u2At(this.classFileBytes, 1, this.constantPoolOffset[index])); - declaringClassIndex = u2At(this.classFileBytes, 1, this.constantPoolOffset[constantPoolEntry.getClassIndex()]); - constantPoolEntry.setClassName(getUtf8ValueAt(declaringClassIndex)); - constantPoolEntry.setNameAndTypeIndex(u2At(this.classFileBytes, 3, this.constantPoolOffset[index])); - int methodNameIndex = u2At(this.classFileBytes, 1, this.constantPoolOffset[constantPoolEntry.getNameAndTypeIndex()]); - int methodDescriptorIndex = u2At(this.classFileBytes, 3, this.constantPoolOffset[constantPoolEntry.getNameAndTypeIndex()]); - constantPoolEntry.setMethodName(getUtf8ValueAt(methodNameIndex)); - constantPoolEntry.setMethodDescriptor(getUtf8ValueAt(methodDescriptorIndex)); - break; - case ConstantPoolConstant.CONSTANT_Float : - constantPoolEntry.setFloatValue(floatAt(this.classFileBytes, 1, this.constantPoolOffset[index])); - break; - case ConstantPoolConstant.CONSTANT_Integer : - constantPoolEntry.setIntegerValue(i4At(this.classFileBytes, 1, this.constantPoolOffset[index])); - break; - case ConstantPoolConstant.CONSTANT_Long : - constantPoolEntry.setLongValue(i8At(this.classFileBytes, 1, this.constantPoolOffset[index])); - break; - case ConstantPoolConstant.CONSTANT_NameAndType : - constantPoolEntry.setNameAndTypeNameIndex(u2At(this.classFileBytes, 1, this.constantPoolOffset[index])); - constantPoolEntry.setNameAndTypeDescriptorIndex(u2At(this.classFileBytes, 3, this.constantPoolOffset[index])); - break; - case ConstantPoolConstant.CONSTANT_String : - constantPoolEntry.setStringIndex(u2At(this.classFileBytes, 1, this.constantPoolOffset[index])); - constantPoolEntry.setStringValue(getUtf8ValueAt(constantPoolEntry.getStringIndex())); - break; - case ConstantPoolConstant.CONSTANT_Utf8 : - constantPoolEntry.setUtf8Length(u2At(this.classFileBytes, 1, this.constantPoolOffset[index])); - constantPoolEntry.setUtf8Value(getUtf8ValueAt(index)); - } - return constantPoolEntry; - } - - /* - * @see IConstantPool#getConstantPoolCount() - */ - public int getConstantPoolCount() { - return this.constantPoolCount; - } - - /* - * @see IConstantPool#getEntryKind(int) - */ - public int getEntryKind(int index) { - return u1At(this.classFileBytes, 0, this.constantPoolOffset[index]); - } - - private char[] getUtf8ValueAt(int utf8Index) { - int utf8Offset = this.constantPoolOffset[utf8Index]; - return utf8At(this.classFileBytes, 0, utf8Offset + 3, u2At(this.classFileBytes, 0, utf8Offset + 1)); - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantPoolConstant.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantPoolConstant.java deleted file mode 100644 index 7cebf66e1..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantPoolConstant.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public interface ConstantPoolConstant { - - int CONSTANT_Class = 7; - int CONSTANT_Fieldref = 9; - int CONSTANT_Methodref = 10; - int CONSTANT_InterfaceMethodref = 11; - int CONSTANT_String = 8; - int CONSTANT_Integer = 3; - int CONSTANT_Float = 4; - int CONSTANT_Long = 5; - int CONSTANT_Double = 6; - int CONSTANT_NameAndType = 12; - int CONSTANT_Utf8 = 1; - - int CONSTANT_Methodref_SIZE = 5; - int CONSTANT_Class_SIZE = 3; - int CONSTANT_Double_SIZE = 9; - int CONSTANT_Fieldref_SIZE = 5; - int CONSTANT_Float_SIZE = 5; - int CONSTANT_Integer_SIZE = 5; - int CONSTANT_InterfaceMethodref_SIZE = 5; - int CONSTANT_Long_SIZE = 9; - int CONSTANT_String_SIZE = 3; - int CONSTANT_Utf8_SIZE = 3; - int CONSTANT_NameAndType_SIZE = 5; - -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantPoolEntry.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantPoolEntry.java deleted file mode 100644 index cdee2fd49..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantPoolEntry.java +++ /dev/null @@ -1,396 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class ConstantPoolEntry { - - private int kind; - private int classInfoNameIndex; - private int classIndex; - private int nameAndTypeIndex; - private int stringIndex; - private char[] stringValue; - private int integerValue; - private float floatValue; - private double doubleValue; - private long longValue; - private int nameAndTypeDescriptorIndex; - private int nameAndTypeNameIndex; - private char[] className; - private char[] fieldName; - private char[] methodName; - private char[] fieldDescriptor; - private char[] methodDescriptor; - private char[] utf8Value; - private int utf8Length; - private char[] classInfoName; - - public ConstantPoolEntry() { - this.classInfoNameIndex = -1; - this.classIndex = -1; - this.nameAndTypeIndex = -1; - this.stringIndex = -1; - this.stringValue = null; - this.integerValue = -1; - this.floatValue = -0.0f; - this.doubleValue = -0 - 0; - this.longValue = -1; - this.nameAndTypeDescriptorIndex = -1; - this.nameAndTypeNameIndex = -1; - this.className = null; - this.fieldName = null; - this.methodName = null; - this.fieldDescriptor = null; - this.methodDescriptor = null; - this.utf8Value = null; - this.utf8Length = -1; - this.classInfoName = null; - } - - /* - * @see IConstantPoolEntry#getKind() - */ - public int getKind() { - return this.kind; - } - - /* - * Sets the kind. - * @param kind The kind to set - */ - public void setKind(int kind) { - this.kind = kind; - } - - /* - * @see IConstantPoolEntry#getClassInfoNameIndex() - */ - public int getClassInfoNameIndex() { - return this.classInfoNameIndex; - } - - /* - * @see IConstantPoolEntry#getClassIndex() - */ - public int getClassIndex() { - return this.classIndex; - } - - /* - * @see IConstantPoolEntry#getNameAndTypeIndex() - */ - public int getNameAndTypeIndex() { - return this.nameAndTypeIndex; - } - - /* - * @see IConstantPoolEntry#getStringIndex() - */ - public int getStringIndex() { - return this.stringIndex; - } - - /* - * @see IConstantPoolEntry#getStringValue() - */ - public String getStringValue() { - return new String(this.stringValue); - } - - /* - * @see IConstantPoolEntry#getIntegerValue() - */ - public int getIntegerValue() { - return this.integerValue; - } - - /* - * @see IConstantPoolEntry#getFloatValue() - */ - public float getFloatValue() { - return this.floatValue; - } - - /* - * @see IConstantPoolEntry#getDoubleValue() - */ - public double getDoubleValue() { - return this.doubleValue; - } - - /* - * @see IConstantPoolEntry#getLongValue() - */ - public long getLongValue() { - return this.longValue; - } - - /* - * @see IConstantPoolEntry#getNameAndTypeInfoDescriptorIndex() - */ - public int getNameAndTypeInfoDescriptorIndex() { - return this.nameAndTypeDescriptorIndex; - } - - /* - * @see IConstantPoolEntry#getNameAndTypeInfoNameIndex() - */ - public int getNameAndTypeInfoNameIndex() { - return this.nameAndTypeNameIndex; - } - - /* - * @see IConstantPoolEntry#getClassName() - */ - public char[] getClassName() { - return this.className; - } - - /* - * @see IConstantPoolEntry#getFieldName() - */ - public char[] getFieldName() { - return this.fieldName; - } - - /* - * @see IConstantPoolEntry#getMethodName() - */ - public char[] getMethodName() { - return this.methodName; - } - - /* - * @see IConstantPoolEntry#getFieldDescriptor() - */ - public char[] getFieldDescriptor() { - return this.fieldDescriptor; - } - - /* - * @see IConstantPoolEntry#getMethodDescriptor() - */ - public char[] getMethodDescriptor() { - return this.methodDescriptor; - } - - /* - * @see IConstantPoolEntry#getUtf8Value() - */ - public char[] getUtf8Value() { - return this.utf8Value; - } - - /* - * @see IConstantPoolEntry#getClassInfoName() - */ - public char[] getClassInfoName() { - return this.classInfoName; - } - - /* - * Sets the classInfoNameIndex. - * @param classInfoNameIndex The classInfoNameIndex to set - */ - public void setClassInfoNameIndex(int classInfoNameIndex) { - this.classInfoNameIndex = classInfoNameIndex; - } - - /* - * Sets the classIndex. - * @param classIndex The classIndex to set - */ - public void setClassIndex(int classIndex) { - this.classIndex = classIndex; - } - - /* - * Sets the nameAndTypeIndex. - * @param nameAndTypeIndex The nameAndTypeIndex to set - */ - public void setNameAndTypeIndex(int nameAndTypeIndex) { - this.nameAndTypeIndex = nameAndTypeIndex; - } - - /* - * Sets the stringIndex. - * @param stringIndex The stringIndex to set - */ - public void setStringIndex(int stringIndex) { - this.stringIndex = stringIndex; - } - - /* - * Sets the stringValue. - * @param stringValue The stringValue to set - */ - public void setStringValue(char[] stringValue) { - this.stringValue = stringValue; - } - - /* - * Sets the integerValue. - * @param integerValue The integerValue to set - */ - public void setIntegerValue(int integerValue) { - this.integerValue = integerValue; - } - - /* - * Sets the floatValue. - * @param floatValue The floatValue to set - */ - public void setFloatValue(float floatValue) { - this.floatValue = floatValue; - } - - /* - * Sets the doubleValue. - * @param doubleValue The doubleValue to set - */ - public void setDoubleValue(double doubleValue) { - this.doubleValue = doubleValue; - } - - /* - * Sets the longValue. - * @param longValue The longValue to set - */ - public void setLongValue(long longValue) { - this.longValue = longValue; - } - - /* - * Gets the nameAndTypeDescriptorIndex. - * @return Returns a int - */ - public int getNameAndTypeDescriptorIndex() { - return this.nameAndTypeDescriptorIndex; - } - - /* - * Sets the nameAndTypeDescriptorIndex. - * @param nameAndTypeDescriptorIndex The nameAndTypeDescriptorIndex to set - */ - public void setNameAndTypeDescriptorIndex(int nameAndTypeDescriptorIndex) { - this.nameAndTypeDescriptorIndex = nameAndTypeDescriptorIndex; - } - - /* - * Gets the nameAndTypeNameIndex. - * @return Returns a int - */ - public int getNameAndTypeNameIndex() { - return this.nameAndTypeNameIndex; - } - - /* - * Sets the nameAndTypeNameIndex. - * @param nameAndTypeNameIndex The nameAndTypeNameIndex to set - */ - public void setNameAndTypeNameIndex(int nameAndTypeNameIndex) { - this.nameAndTypeNameIndex = nameAndTypeNameIndex; - } - - /* - * Sets the className. - * @param className The className to set - */ - public void setClassName(char[] className) { - this.className = className; - } - - /* - * Sets the fieldName. - * @param fieldName The fieldName to set - */ - public void setFieldName(char[] fieldName) { - this.fieldName = fieldName; - } - - /* - * Sets the methodName. - * @param methodName The methodName to set - */ - public void setMethodName(char[] methodName) { - this.methodName = methodName; - } - - /* - * Sets the fieldDescriptor. - * @param fieldDescriptor The fieldDescriptor to set - */ - public void setFieldDescriptor(char[] fieldDescriptor) { - this.fieldDescriptor = fieldDescriptor; - } - - /* - * Sets the methodDescriptor. - * @param methodDescriptor The methodDescriptor to set - */ - public void setMethodDescriptor(char[] methodDescriptor) { - this.methodDescriptor = methodDescriptor; - } - - /* - * Sets the utf8Value. - * @param utf8Value The utf8Value to set - */ - public void setUtf8Value(char[] utf8Value) { - this.utf8Value = utf8Value; - } - - /* - * Sets the classInfoName. - * @param classInfoName The classInfoName to set - */ - public void setClassInfoName(char[] classInfoName) { - this.classInfoName = classInfoName; - } - - /* - * @see IConstantPoolEntry#getUtf8Length() - */ - public int getUtf8Length() { - return this.utf8Length; - } - - /* - * Sets the utf8Length. - * @param utf8Length The utf8Length to set - */ - public void setUtf8Length(int utf8Length) { - this.utf8Length = utf8Length; - } - - public void reset() { - this.kind = 0; - this.classInfoNameIndex = 0; - this.classIndex = 0; - this.nameAndTypeIndex = 0; - this.stringIndex = 0; - this.stringValue = null; - this.integerValue = 0; - this.floatValue = 0.0f; - this.doubleValue = 0.0; - this.longValue = 0L; - this.nameAndTypeDescriptorIndex = 0; - this.nameAndTypeNameIndex = 0; - this.className = null; - this.fieldName = null; - this.methodName = null; - this.fieldDescriptor = null; - this.methodDescriptor = null; - this.utf8Value = null; - this.utf8Length = 0; - this.classInfoName = null; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantValueAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantValueAttribute.java deleted file mode 100644 index 75e961e77..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ConstantValueAttribute.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class ConstantValueAttribute extends ClassFileAttribute { - - private int constantValueIndex; - private ConstantPoolEntry constantPoolEntry; - - ConstantValueAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - super(classFileBytes, constantPool, offset); - this.constantValueIndex = u2At(classFileBytes, 6, offset); - this.constantPoolEntry = constantPool.decodeEntry(this.constantValueIndex); - } - - /* - * @see IConstantValueAttribute#getConstantValue() - */ - public ConstantPoolEntry getConstantValue() { - return this.constantPoolEntry; - } - - /* - * @see IConstantValueAttribute#getConstantValueIndex() - */ - public int getConstantValueIndex() { - return this.constantValueIndex; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/DefaultBytecodeVisitor.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/DefaultBytecodeVisitor.java deleted file mode 100644 index aaeaf264b..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/DefaultBytecodeVisitor.java +++ /dev/null @@ -1,2071 +0,0 @@ -/****************************************************************************** - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -import org.eclipse.osgi.util.NLS; - -public class DefaultBytecodeVisitor { - private static final String EMPTY_CLASS_NAME = "\"\""; //$NON-NLS-1$ - private static final String EMPTY_LOCAL_NAME = ""; //$NON-NLS-1$ - private static final int T_BOOLEAN = 4; - private static final int T_CHAR = 5; - private static final int T_FLOAT = 6; - private static final int T_DOUBLE = 7; - private static final int T_BYTE = 8; - private static final int T_SHORT = 9; - private static final int T_INT = 10; - private static final int T_LONG = 11; - - private StringBuffer buffer; - private String lineSeparator; - private int tabNumber; - private int digitNumberForPC; - private int mode; - - public DefaultBytecodeVisitor(CodeAttribute codeAttribute, char[] methodDescriptor, boolean isStatic, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - this.buffer = buffer; - this.lineSeparator = lineSeparator; - this.tabNumber = tabNumber + 1; - long codeLength = codeAttribute.getCodeLength(); - this.digitNumberForPC = Long.toString(codeLength).length(); - this.mode = mode; - } - - /* - * @see IBytecodeVisitor#_aaload(int) - */ - public void _aaload(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.AALOAD]); - writeNewLine(); - } - - private void dumpPcNumber(int pc) { - writeTabs(); - int digitForPC = 1; - if (pc != 0) { - digitForPC = Integer.toString(pc).length(); - } - for (int i = 0, max = this.digitNumberForPC - digitForPC; i < max; i++) { - this.buffer.append(' '); - } - this.buffer.append(pc); - this.buffer.append(Messages.disassembler_indentation); - } - - /* - * @see IBytecodeVisitor#_aastore(int) - */ - public void _aastore(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.AASTORE]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_aconst_null(int) - */ - public void _aconst_null(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ACONST_NULL]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_aload_0(int) - */ - public void _aload_0(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ALOAD_0], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_aload_1(int) - */ - public void _aload_1(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ALOAD_1], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_aload_2(int) - */ - public void _aload_2(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ALOAD_2], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_aload_3(int) - */ - public void _aload_3(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ALOAD_3], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_aload(int, int) - */ - public void _aload(int pc, int index) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ALOAD], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_anewarray(int, int, ConstantPoolEntry) - */ - public void _anewarray(int pc, int index, ConstantPoolEntry constantClass) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_anewarray, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ANEWARRAY], returnConstantClassName(constantClass)})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_areturn(int) - */ - public void _areturn(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ARETURN]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_arraylength(int) - */ - public void _arraylength(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ARRAYLENGTH]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_astore_0(int) - */ - public void _astore_0(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ASTORE_0], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_astore_1(int) - */ - public void _astore_1(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ASTORE_1], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_astore_2(int) - */ - public void _astore_2(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ASTORE_2], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_astore_3(int) - */ - public void _astore_3(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ASTORE_3], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_astore(int, int) - */ - public void _astore(int pc, int index) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ASTORE], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_athrow(int) - */ - public void _athrow(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ATHROW]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_baload(int) - */ - public void _baload(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.BALOAD]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_bastore(int) - */ - public void _bastore(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.BASTORE]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_bipush(int, byte) - */ - public void _bipush(int pc, byte _byte) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.BIPUSH]).append(Messages.disassembler_space).append(_byte); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_caload(int) - */ - public void _caload(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.CALOAD]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_castore(int) - */ - public void _castore(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.CASTORE]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_checkcast(int, int, ConstantPoolEntry) - */ - public void _checkcast(int pc, int index, ConstantPoolEntry constantClass) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_checkcast, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.CHECKCAST], returnConstantClassName(constantClass)})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_d2f(int) - */ - public void _d2f(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.D2F]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_d2i(int) - */ - public void _d2i(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.D2I]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_d2l(int) - */ - public void _d2l(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.D2L]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dadd(int) - */ - public void _dadd(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DADD]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_daload(int) - */ - public void _daload(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DALOAD]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dastore(int) - */ - public void _dastore(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DASTORE]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dcmpg(int) - */ - public void _dcmpg(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DCMPG]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dcmpl(int) - */ - public void _dcmpl(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DCMPL]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dconst_0(int) - */ - public void _dconst_0(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DCONST_0]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dconst_1(int) - */ - public void _dconst_1(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DCONST_1]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ddiv(int) - */ - public void _ddiv(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DDIV]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dload_0(int) - */ - public void _dload_0(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DLOAD_0], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dload_1(int) - */ - public void _dload_1(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DLOAD_1], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dload_2(int) - */ - public void _dload_2(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DLOAD_2], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dload_3(int) - */ - public void _dload_3(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DLOAD_3], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dload(int, int) - */ - public void _dload(int pc, int index) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DLOAD], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dmul(int) - */ - public void _dmul(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DMUL]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dneg(int) - */ - public void _dneg(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DNEG]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_drem(int) - */ - public void _drem(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DREM]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dreturn(int) - */ - public void _dreturn(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DRETURN]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dstore_0(int) - */ - public void _dstore_0(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DSTORE_0], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dstore_1(int) - */ - public void _dstore_1(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DSTORE_1], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dstore_2(int) - */ - public void _dstore_2(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DSTORE_2], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dstore_3(int) - */ - public void _dstore_3(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DSTORE_3], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dstore(int,int) - */ - public void _dstore(int pc, int index) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DSTORE], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dsub(int) - */ - public void _dsub(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DSUB]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dup_x1(int) - */ - public void _dup_x1(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DUP_X1]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dup_x2(int) - */ - public void _dup_x2(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DUP_X2]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dup(int) - */ - public void _dup(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DUP]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dup2_x1(int) - */ - public void _dup2_x1(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DUP2_X1]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dup2_x2(int) - */ - public void _dup2_x2(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DUP2_X2]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_dup2(int) - */ - public void _dup2(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DUP2]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_f2d(int) - */ - public void _f2d(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.F2D]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_f2i(int) - */ - public void _f2i(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.F2I]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_f2l(int) - */ - public void _f2l(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.F2L]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fadd(int) - */ - public void _fadd(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FADD]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_faload(int) - */ - public void _faload(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FALOAD]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fastore(int) - */ - public void _fastore(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FASTORE]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fcmpg(int) - */ - public void _fcmpg(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FCMPG]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fcmpl(int) - */ - public void _fcmpl(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FCMPL]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fconst_0(int) - */ - public void _fconst_0(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FCONST_0]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fconst_1(int) - */ - public void _fconst_1(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FCONST_1]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fconst_2(int) - */ - public void _fconst_2(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FCONST_2]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fdiv(int) - */ - public void _fdiv(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FDIV]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fload_0(int) - */ - public void _fload_0(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FLOAD_0], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fload_1(int) - */ - public void _fload_1(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FLOAD_1], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fload_2(int) - */ - public void _fload_2(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FLOAD_2], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fload_3(int) - */ - public void _fload_3(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FLOAD_3], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fload(int, int) - */ - public void _fload(int pc, int index) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FLOAD], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fmul(int) - */ - public void _fmul(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FMUL]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fneg(int) - */ - public void _fneg(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FNEG]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_frem(int) - */ - public void _frem(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FREM]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_freturn(int) - */ - public void _freturn(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FRETURN]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fstore_0(int) - */ - public void _fstore_0(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FSTORE_0], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fstore_1(int) - */ - public void _fstore_1(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FSTORE_1], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fstore_2(int) - */ - public void _fstore_2(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FSTORE_2], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fstore_3(int) - */ - public void _fstore_3(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FSTORE_3], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fstore(int, int) - */ - public void _fstore(int pc, int index) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FSTORE], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_fsub(int) - */ - public void _fsub(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FSUB]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_getfield(int, int, ConstantPoolEntry) - */ - public void _getfield(int pc, int index, ConstantPoolEntry constantFieldref) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_getfield, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.GETFIELD], returnDeclaringClassName(constantFieldref), new String(constantFieldref.getFieldName()), returnClassName(Signature.toCharArray(constantFieldref.getFieldDescriptor()))})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_getstatic(int, int, ConstantPoolEntry) - */ - public void _getstatic(int pc, int index, ConstantPoolEntry constantFieldref) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_getstatic, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.GETSTATIC], returnDeclaringClassName(constantFieldref), new String(constantFieldref.getFieldName()), returnClassName(Signature.toCharArray(constantFieldref.getFieldDescriptor()))})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_goto_w(int, int) - */ - public void _goto_w(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.GOTO_W]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_goto(int, int) - */ - public void _goto(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.GOTO]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_i2b(int) - */ - public void _i2b(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.I2B]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_i2c(int) - */ - public void _i2c(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.I2C]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_i2d(int) - */ - public void _i2d(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.I2D]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_i2f(int) - */ - public void _i2f(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.I2F]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_i2l(int) - */ - public void _i2l(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.I2L]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_i2s(int) - */ - public void _i2s(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.I2S]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iadd(int) - */ - public void _iadd(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IADD]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iaload(int) - */ - public void _iaload(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IALOAD]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iand(int) - */ - public void _iand(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IAND]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iastore(int) - */ - public void _iastore(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IASTORE]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_if_acmpeq(int, int) - */ - public void _if_acmpeq(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ACMPEQ]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_if_acmpne(int, int) - */ - public void _if_acmpne(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ACMPNE]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_if_icmpeq(int, int) - */ - public void _if_icmpeq(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ICMPEQ]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_if_icmpge(int, int) - */ - public void _if_icmpge(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ICMPGE]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_if_icmpgt(int, int) - */ - public void _if_icmpgt(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ICMPGT]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_if_icmple(int, int) - */ - public void _if_icmple(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ICMPLE]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_if_icmplt(int, int) - */ - public void _if_icmplt(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ICMPLT]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_if_icmpne(int, int) - */ - public void _if_icmpne(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ICMPNE]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iconst_0(int) - */ - public void _iconst_0(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ICONST_0]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iconst_1(int) - */ - public void _iconst_1(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ICONST_1]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iconst_2(int) - */ - public void _iconst_2(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ICONST_2]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iconst_3(int) - */ - public void _iconst_3(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ICONST_3]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iconst_4(int) - */ - public void _iconst_4(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ICONST_4]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iconst_5(int) - */ - public void _iconst_5(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ICONST_5]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iconst_m1(int) - */ - public void _iconst_m1(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ICONST_M1]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_idiv(int) - */ - public void _idiv(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IDIV]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ifeq(int, int) - */ - public void _ifeq(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFEQ]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ifge(int, int) - */ - public void _ifge(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFGE]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ifgt(int, int) - */ - public void _ifgt(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFGT]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ifle(int, int) - */ - public void _ifle(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFLE]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iflt(int, int) - */ - public void _iflt(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFLT]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ifne(int, int) - */ - public void _ifne(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFNE]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ifnonnull(int, int) - */ - public void _ifnonnull(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFNONNULL]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ifnull(int, int) - */ - public void _ifnull(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFNULL]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iinc(int, int, int) - */ - public void _iinc(int pc, int index, int _const) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_iinc, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IINC], Integer.toString(index), Integer.toString(_const), EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iload_0(int) - */ - public void _iload_0(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ILOAD_0], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iload_1(int) - */ - public void _iload_1(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ILOAD_1], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iload_2(int) - */ - public void _iload_2(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ILOAD_2], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iload_3(int) - */ - public void _iload_3(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ILOAD_3], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iload(int, int) - */ - public void _iload(int pc, int index) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ILOAD], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_imul(int) - */ - public void _imul(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IMUL]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ineg(int) - */ - public void _ineg(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.INEG]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_instanceof(int, int, ConstantPoolEntry) - */ - public void _instanceof(int pc, int index, ConstantPoolEntry constantClass) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_instanceof, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.INSTANCEOF], returnConstantClassName(constantClass)})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_invokeinterface(int, int, byte, ConstantPoolEntry) - */ - public void _invokeinterface(int pc, int index, byte nargs, ConstantPoolEntry constantInterfaceMethodref) { - - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_invokeinterface, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.INVOKEINTERFACE], Integer.toString(nargs), Utility.toString(constantInterfaceMethodref.getClassName(), constantInterfaceMethodref.getMethodName(), constantInterfaceMethodref.getMethodDescriptor(), true, isCompact())})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_invokespecial(int, int, ConstantPoolEntry) - */ - public void _invokespecial(int pc, int index, ConstantPoolEntry constantMethodref) { - dumpPcNumber(pc); - final String signature = returnMethodSignature(constantMethodref); - this.buffer.append(NLS.bind(Messages.classformat_invokespecial, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.INVOKESPECIAL], signature})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_invokestatic(int, int, ConstantPoolEntry) - */ - public void _invokestatic(int pc, int index, ConstantPoolEntry constantMethodref) { - dumpPcNumber(pc); - final String signature = returnMethodSignature(constantMethodref); - this.buffer.append(NLS.bind(Messages.classformat_invokestatic, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.INVOKESTATIC], signature})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_invokevirtual(int, int, ConstantPoolEntry) - */ - public void _invokevirtual(int pc, int index, ConstantPoolEntry constantMethodref) { - dumpPcNumber(pc); - final String signature = returnMethodSignature(constantMethodref); - this.buffer.append(NLS.bind(Messages.classformat_invokevirtual, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.INVOKEVIRTUAL], signature})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ior(int) - */ - public void _ior(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IOR]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_irem(int) - */ - public void _irem(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IREM]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ireturn(int) - */ - public void _ireturn(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IRETURN]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ishl(int) - */ - public void _ishl(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISHL]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ishr(int) - */ - public void _ishr(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISHR]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_istore_0(int) - */ - public void _istore_0(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISTORE_0], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_istore_1(int) - */ - public void _istore_1(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISTORE_1], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_istore_2(int) - */ - public void _istore_2(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISTORE_2], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_istore_3(int) - */ - public void _istore_3(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISTORE_3], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_istore(int, int) - */ - public void _istore(int pc, int index) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISTORE], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_isub(int) - */ - public void _isub(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISUB]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_iushr(int) - */ - public void _iushr(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IUSHR]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ixor(int) - */ - public void _ixor(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IXOR]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_jsr_w(int, int) - */ - public void _jsr_w(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.JSR_W]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_jsr(int, int) - */ - public void _jsr(int pc, int branchOffset) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.JSR]).append(Messages.disassembler_space).append(branchOffset + pc); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_l2d(int) - */ - public void _l2d(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.L2D]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_l2f(int) - */ - public void _l2f(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.L2F]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_l2i(int) - */ - public void _l2i(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.L2I]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ladd(int) - */ - public void _ladd(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LADD]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_laload(int) - */ - public void _laload(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LALOAD]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_land(int) - */ - public void _land(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LAND]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lastore(int) - */ - public void _lastore(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LASTORE]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lcmp(int) - */ - public void _lcmp(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LCMP]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lconst_0(int) - */ - public void _lconst_0(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LCONST_0]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lconst_1(int) - */ - public void _lconst_1(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LCONST_1]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ldc_w(int, int, ConstantPoolEntry) - */ - public void _ldc_w(int pc, int index, ConstantPoolEntry constantPoolEntry) { - dumpPcNumber(pc); - switch (constantPoolEntry.getKind()) { - case ConstantPoolConstant.CONSTANT_Float : - this.buffer.append(NLS.bind(Messages.classformat_ldc_w_float, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC_W], Float.toString(constantPoolEntry.getFloatValue())})); - break; - case ConstantPoolConstant.CONSTANT_Integer : - this.buffer.append(NLS.bind(Messages.classformat_ldc_w_integer, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC_W], Integer.toString(constantPoolEntry.getIntegerValue())})); - break; - case ConstantPoolConstant.CONSTANT_String : - this.buffer.append(NLS.bind(Messages.classformat_ldc_w_string, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC_W], Disassembler.escapeString(constantPoolEntry.getStringValue())})); - break; - case ConstantPoolConstant.CONSTANT_Class : - this.buffer.append(NLS.bind(Messages.classformat_ldc_w_class, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC_W], returnConstantClassName(constantPoolEntry)})); - } - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ldc(int, int, ConstantPoolEntry) - */ - public void _ldc(int pc, int index, ConstantPoolEntry constantPoolEntry) { - dumpPcNumber(pc); - switch (constantPoolEntry.getKind()) { - case ConstantPoolConstant.CONSTANT_Float : - this.buffer.append(NLS.bind(Messages.classformat_ldc_w_float, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC], Float.toString(constantPoolEntry.getFloatValue())})); - break; - case ConstantPoolConstant.CONSTANT_Integer : - this.buffer.append(NLS.bind(Messages.classformat_ldc_w_integer, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC], Integer.toString(constantPoolEntry.getIntegerValue())})); - break; - case ConstantPoolConstant.CONSTANT_String : - this.buffer.append(NLS.bind(Messages.classformat_ldc_w_string, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC], Disassembler.escapeString(constantPoolEntry.getStringValue())})); - break; - case ConstantPoolConstant.CONSTANT_Class : - this.buffer.append(NLS.bind(Messages.classformat_ldc_w_class, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC], returnConstantClassName(constantPoolEntry)})); - } - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ldc2_w(int, int, ConstantPoolEntry) - */ - public void _ldc2_w(int pc, int index, ConstantPoolEntry constantPoolEntry) { - dumpPcNumber(pc); - switch (constantPoolEntry.getKind()) { - case ConstantPoolConstant.CONSTANT_Long : - this.buffer.append(NLS.bind(Messages.classformat_ldc2_w_long, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC2_W], Long.toString(constantPoolEntry.getLongValue())})); - break; - case ConstantPoolConstant.CONSTANT_Double : - this.buffer.append(NLS.bind(Messages.classformat_ldc2_w_double, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC2_W], Double.toString(constantPoolEntry.getDoubleValue())})); - } - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ldiv(int) - */ - public void _ldiv(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDIV]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lload_0(int) - */ - public void _lload_0(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LLOAD_0], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lload_1(int) - */ - public void _lload_1(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LLOAD_1], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lload_2(int) - */ - public void _lload_2(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LLOAD_2], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lload_3(int) - */ - public void _lload_3(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LLOAD_3], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lload(int, int) - */ - public void _lload(int pc, int index) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LLOAD], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lmul(int) - */ - public void _lmul(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LMUL]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lneg(int) - */ - public void _lneg(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LNEG]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lookupswitch(int, int, int, int[][]) - */ - public void _lookupswitch(int pc, int defaultoffset, int npairs, int[][] offset_pairs) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LOOKUPSWITCH]).append(" default: ") //$NON-NLS-1$ - .append(defaultoffset + pc); - writeNewLine(); - for (int i = 0; i < npairs; i++) { - writeExtraTabs(3); - this.buffer.append("case ") //$NON-NLS-1$ - .append(offset_pairs[i][0]).append(": ") //$NON-NLS-1$ - .append(offset_pairs[i][1] + pc); - writeNewLine(); - } - } - - /* - * @see IBytecodeVisitor#_lor(int) - */ - public void _lor(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LOR]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lrem(int) - */ - public void _lrem(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LREM]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lreturn(int) - */ - public void _lreturn(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LRETURN]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lshl(int) - */ - public void _lshl(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSHL]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lshr(int) - */ - public void _lshr(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSHR]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lstore_0(int) - */ - public void _lstore_0(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSTORE_0], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lstore_1(int) - */ - public void _lstore_1(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSTORE_1], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lstore_2(int) - */ - public void _lstore_2(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSTORE_2], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lstore_3(int) - */ - public void _lstore_3(int pc) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSTORE_3], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lstore(int, int) - */ - public void _lstore(int pc, int index) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSTORE], EMPTY_LOCAL_NAME})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lsub(int) - */ - public void _lsub(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSUB]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lushr(int) - */ - public void _lushr(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LUSHR]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_lxor(int) - */ - public void _lxor(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LXOR]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_monitorenter(int) - */ - public void _monitorenter(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.MONITORENTER]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_monitorexit(int) - */ - public void _monitorexit(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.MONITOREXIT]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_multianewarray(int, int, int, ConstantPoolEntry) - */ - public void _multianewarray(int pc, int index, int dimensions, ConstantPoolEntry constantClass) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_multianewarray, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.MULTIANEWARRAY], returnConstantClassName(constantClass)})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_new(int, int, ConstantPoolEntry) - */ - public void _new(int pc, int index, ConstantPoolEntry constantClass) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_new, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEW], returnConstantClassName(constantClass)})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_newarray(int, int) - */ - public void _newarray(int pc, int atype) { - dumpPcNumber(pc); - switch (atype) { - case T_BOOLEAN : - this.buffer.append(NLS.bind(Messages.classformat_newarray_boolean, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); - break; - case T_CHAR : - this.buffer.append(NLS.bind(Messages.classformat_newarray_char, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); - break; - case T_FLOAT : - this.buffer.append(NLS.bind(Messages.classformat_newarray_float, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); - break; - case T_DOUBLE : - this.buffer.append(NLS.bind(Messages.classformat_newarray_double, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); - break; - case T_BYTE : - this.buffer.append(NLS.bind(Messages.classformat_newarray_byte, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); - break; - case T_SHORT : - this.buffer.append(NLS.bind(Messages.classformat_newarray_short, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); - break; - case T_INT : - this.buffer.append(NLS.bind(Messages.classformat_newarray_int, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); - break; - case T_LONG : - this.buffer.append(NLS.bind(Messages.classformat_newarray_long, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); - } - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_nop(int) - */ - public void _nop(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NOP]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_pop(int) - */ - public void _pop(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.POP]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_pop2(int) - */ - public void _pop2(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.POP2]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_putfield(int, int, ConstantPoolEntry) - */ - public void _putfield(int pc, int index, ConstantPoolEntry constantFieldref) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_putfield, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.PUTFIELD], returnDeclaringClassName(constantFieldref), new String(constantFieldref.getFieldName()), returnClassName(Signature.toCharArray(constantFieldref.getFieldDescriptor()))})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_putstatic(int, int, ConstantPoolEntry) - */ - public void _putstatic(int pc, int index, ConstantPoolEntry constantFieldref) { - dumpPcNumber(pc); - this.buffer.append(NLS.bind(Messages.classformat_putstatic, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.PUTSTATIC], returnDeclaringClassName(constantFieldref), new String(constantFieldref.getFieldName()), returnClassName(Signature.toCharArray(constantFieldref.getFieldDescriptor()))})); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_ret(int, int) - */ - public void _ret(int pc, int index) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.RET]).append(Messages.disassembler_space).append(index); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_return(int) - */ - public void _return(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.RETURN]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_saload(int) - */ - public void _saload(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.SALOAD]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_sastore(int) - */ - public void _sastore(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.SASTORE]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_sipush(int, short) - */ - public void _sipush(int pc, short value) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.SIPUSH]).append(Messages.disassembler_space).append(value); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_swap(int) - */ - public void _swap(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.SWAP]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_tableswitch(int, int, int, int, int[]) - */ - public void _tableswitch(int pc, int defaultoffset, int low, int high, int[] jump_offsets) { - - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.TABLESWITCH]).append(" default: ") //$NON-NLS-1$ - .append(defaultoffset + pc); - writeNewLine(); - for (int i = low; i < high + 1; i++) { - writeExtraTabs(3); - this.buffer.append("case ") //$NON-NLS-1$ - .append(i).append(": ") //$NON-NLS-1$ - .append(jump_offsets[i - low] + pc); - writeNewLine(); - } - } - - /* - * @see IBytecodeVisitor#_wide(int, int, int) - */ - public void _wide(int pc, int iincopcode, int index, int _const) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.WIDE]); - writeNewLine(); - _iinc(pc + 1, index, _const); - } - - /* - * @see IBytecodeVisitor#_wide(int, int, int) - */ - public void _wide(int pc, int opcode, int index) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.WIDE]); - writeNewLine(); - switch (opcode) { - case IOpcodeMnemonics.ILOAD : - _iload(pc + 1, index); - break; - case IOpcodeMnemonics.FLOAD : - _fload(pc + 1, index); - break; - case IOpcodeMnemonics.ALOAD : - _aload(pc + 1, index); - break; - case IOpcodeMnemonics.LLOAD : - _lload(pc + 1, index); - break; - case IOpcodeMnemonics.DLOAD : - _dload(pc + 1, index); - break; - case IOpcodeMnemonics.ISTORE : - _istore(pc + 1, index); - break; - case IOpcodeMnemonics.FSTORE : - _fstore(pc + 1, index); - break; - case IOpcodeMnemonics.ASTORE : - _astore(pc + 1, index); - break; - case IOpcodeMnemonics.LSTORE : - _lstore(pc + 1, index); - break; - case IOpcodeMnemonics.DSTORE : - _dstore(pc + 1, index); - break; - case IOpcodeMnemonics.RET : - _ret(pc + 1, index); - } - } - - /* - * @see IBytecodeVisitor#_breakpoint(int) - */ - public void _breakpoint(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.BREAKPOINT]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_impdep1(int) - */ - public void _impdep1(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IMPDEP1]); - writeNewLine(); - } - - /* - * @see IBytecodeVisitor#_impdep2(int) - */ - public void _impdep2(int pc) { - dumpPcNumber(pc); - this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IMPDEP2]); - writeNewLine(); - } - - private boolean isCompact() { - return (this.mode & Disassembler.COMPACT) != 0; - } - - private String returnConstantClassName(ConstantPoolEntry constantClass) { - char[] className = constantClass.getClassInfoName(); - if (className.length == 0) { - return EMPTY_CLASS_NAME; - } - switch (className[0]) { - case '[' : - StringBuffer classNameBuffer = new StringBuffer(); - Utility.appendTypeSignature(className, 0, classNameBuffer, isCompact()); - return classNameBuffer.toString(); - default : - return returnClassName(className); - } - } - - private String returnClassName(char[] classInfoName) { - if (classInfoName.length == 0) { - return EMPTY_CLASS_NAME; - } else if (isCompact()) { - int lastIndexOfSlash = CharOperation.lastIndexOf('/', classInfoName); - if (lastIndexOfSlash != -1) { - return new String(classInfoName, lastIndexOfSlash + 1, classInfoName.length - lastIndexOfSlash - 1); - } - } - CharOperation.replace(classInfoName, '/', '.'); - return new String(classInfoName); - } - - private String returnDeclaringClassName(ConstantPoolEntry constantRef) { - final char[] className = constantRef.getClassName(); - return returnClassName(className); - } - - private String returnMethodSignature(ConstantPoolEntry constantMethodref) { - final char[] methodDescriptor = constantMethodref.getMethodDescriptor(); - CharOperation.replace(methodDescriptor, '$', '#'); - final char[] signature = Utility.toString(constantMethodref.getClassName(), constantMethodref.getMethodName(), methodDescriptor, true, isCompact()).toCharArray(); - CharOperation.replace(signature, '#', '$'); - return String.valueOf(signature); - } - - private void writeNewLine() { - this.buffer.append(this.lineSeparator); - } - - private void writeTabs() { - for (int i = 0, max = this.tabNumber; i < max; i++) { - this.buffer.append(Messages.disassembler_indentation); - } - } - - private void writeExtraTabs(int extraTabs) { - for (int i = 0, max = this.tabNumber + extraTabs; i < max; i++) { - this.buffer.append(Messages.disassembler_indentation); - } - } - -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Disassembler.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Disassembler.java deleted file mode 100644 index f96d48823..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Disassembler.java +++ /dev/null @@ -1,1149 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -import java.util.Arrays; -import java.util.Comparator; -import org.eclipse.osgi.util.NLS; - -/** - * Disassembler of .class files. It generates an output in the Writer that looks close to - * the javap output. - */ -public class Disassembler { - /** - * The mode is the detailed mode to disassemble ClassFileReader. It returns the magic - * numbers, the version numbers and field and method descriptors. - */ - public final static int DETAILED = 1; - - /** - * This mode is used to compact the class name to a simple name instead of a qualified name. - * @since 3.1 - */ - public final static int COMPACT = 8; - - private static final char[] ANY_EXCEPTION = Messages.classfileformat_anyexceptionhandler.toCharArray(); - private static final String VERSION_UNKNOWN = Messages.classfileformat_versionUnknown; - - private boolean appendModifier(StringBuffer buffer, int accessFlags, int modifierConstant, String modifier, boolean firstModifier) { - if ((accessFlags & modifierConstant) != 0) { - if (!firstModifier) { - buffer.append(Messages.disassembler_space); - } - if (firstModifier) { - firstModifier = false; - } - buffer.append(modifier); - } - return firstModifier; - } - - private void decodeModifiers(StringBuffer buffer, int accessFlags, int[] checkBits) { - decodeModifiers(buffer, accessFlags, false, false, checkBits); - } - - private void decodeModifiers(StringBuffer buffer, int accessFlags, boolean printDefault, boolean asBridge, int[] checkBits) { - if (checkBits == null) - return; - boolean firstModifier = true; - for (int i = 0, max = checkBits.length; i < max; i++) { - switch (checkBits[i]) { - case IModifierConstants.ACC_PUBLIC : - firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_PUBLIC, "public", firstModifier); //$NON-NLS-1$ - break; - case IModifierConstants.ACC_PROTECTED : - firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_PROTECTED, "protected", firstModifier); //$NON-NLS-1$ - break; - case IModifierConstants.ACC_PRIVATE : - firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_PRIVATE, "private", firstModifier); //$NON-NLS-1$ - break; - case IModifierConstants.ACC_ABSTRACT : - firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_ABSTRACT, "abstract", firstModifier); //$NON-NLS-1$ - break; - case IModifierConstants.ACC_STATIC : - firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_STATIC, "static", firstModifier); //$NON-NLS-1$ - break; - case IModifierConstants.ACC_FINAL : - firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_FINAL, "final", firstModifier); //$NON-NLS-1$ - break; - case IModifierConstants.ACC_SYNCHRONIZED : - firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_SYNCHRONIZED, "synchronized", firstModifier); //$NON-NLS-1$ - break; - case IModifierConstants.ACC_NATIVE : - firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_NATIVE, "native", firstModifier); //$NON-NLS-1$ - break; - case IModifierConstants.ACC_STRICT : - firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_STRICT, "strictfp", firstModifier); //$NON-NLS-1$ - break; - case IModifierConstants.ACC_TRANSIENT : - firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_TRANSIENT, "transient", firstModifier); //$NON-NLS-1$ - break; - case IModifierConstants.ACC_VOLATILE : - // case IModifierConstants.ACC_BRIDGE : - if (asBridge) { - firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_BRIDGE, "bridge", firstModifier); //$NON-NLS-1$ - } else { - firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_VOLATILE, "volatile", firstModifier); //$NON-NLS-1$ - } - break; - case IModifierConstants.ACC_ENUM : - firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_ENUM, "enum", firstModifier); //$NON-NLS-1$ - break; - } - } - if (!firstModifier) { - if (!printDefault) - buffer.append(Messages.disassembler_space); - } else if (printDefault) { - // no modifier: package default visibility - buffer.append("default"); //$NON-NLS-1$ - } - } - - private void decodeModifiersForField(StringBuffer buffer, int accessFlags) { - decodeModifiers(buffer, accessFlags, new int[] {IModifierConstants.ACC_PUBLIC, IModifierConstants.ACC_PROTECTED, IModifierConstants.ACC_PRIVATE, IModifierConstants.ACC_STATIC, IModifierConstants.ACC_FINAL, IModifierConstants.ACC_TRANSIENT, IModifierConstants.ACC_VOLATILE, IModifierConstants.ACC_ENUM}); - } - - private final void decodeModifiersForInnerClasses(StringBuffer buffer, int accessFlags, boolean printDefault) { - decodeModifiers(buffer, accessFlags, printDefault, false, new int[] {IModifierConstants.ACC_PUBLIC, IModifierConstants.ACC_PROTECTED, IModifierConstants.ACC_PRIVATE, IModifierConstants.ACC_ABSTRACT, IModifierConstants.ACC_STATIC, IModifierConstants.ACC_FINAL,}); - } - - private final void decodeModifiersForMethod(StringBuffer buffer, int accessFlags) { - decodeModifiers(buffer, accessFlags, false, true, new int[] {IModifierConstants.ACC_PUBLIC, IModifierConstants.ACC_PROTECTED, IModifierConstants.ACC_PRIVATE, IModifierConstants.ACC_ABSTRACT, IModifierConstants.ACC_STATIC, IModifierConstants.ACC_FINAL, IModifierConstants.ACC_SYNCHRONIZED, IModifierConstants.ACC_NATIVE, IModifierConstants.ACC_STRICT, IModifierConstants.ACC_BRIDGE,}); - } - - private final void decodeModifiersForType(StringBuffer buffer, int accessFlags) { - decodeModifiers(buffer, accessFlags, new int[] {IModifierConstants.ACC_PUBLIC, IModifierConstants.ACC_ABSTRACT, IModifierConstants.ACC_FINAL,}); - } - - public static String escapeString(String s) { - StringBuffer buffer = new StringBuffer(); - for (int i = 0, max = s.length(); i < max; i++) { - char c = s.charAt(i); - switch (c) { - case '\b' : - buffer.append("\\b"); //$NON-NLS-1$ - break; - case '\t' : - buffer.append("\\t"); //$NON-NLS-1$ - break; - case '\n' : - buffer.append("\\n"); //$NON-NLS-1$ - break; - case '\f' : - buffer.append("\\f"); //$NON-NLS-1$ - break; - case '\r' : - buffer.append("\\r"); //$NON-NLS-1$ - break; - case '\0' : - buffer.append("\\0"); //$NON-NLS-1$ - break; - case '\1' : - buffer.append("\\1"); //$NON-NLS-1$ - break; - case '\2' : - buffer.append("\\2"); //$NON-NLS-1$ - break; - case '\3' : - buffer.append("\\3"); //$NON-NLS-1$ - break; - case '\4' : - buffer.append("\\4"); //$NON-NLS-1$ - break; - case '\5' : - buffer.append("\\5"); //$NON-NLS-1$ - break; - case '\6' : - buffer.append("\\6"); //$NON-NLS-1$ - break; - case '\7' : - buffer.append("\\7"); //$NON-NLS-1$ - break; - default : - buffer.append(c); - } - } - return buffer.toString(); - } - - static String decodeStringValue(char[] chars) { - StringBuffer buffer = new StringBuffer(); - for (int i = 0, max = chars.length; i < max; i++) { - char c = chars[i]; - switch (c) { - case '\b' : - buffer.append("\\b"); //$NON-NLS-1$ - break; - case '\t' : - buffer.append("\\t"); //$NON-NLS-1$ - break; - case '\n' : - buffer.append("\\n"); //$NON-NLS-1$ - break; - case '\f' : - buffer.append("\\f"); //$NON-NLS-1$ - break; - case '\r' : - buffer.append("\\r"); //$NON-NLS-1$ - break; - case '\0' : - buffer.append("\\0"); //$NON-NLS-1$ - break; - case '\1' : - buffer.append("\\1"); //$NON-NLS-1$ - break; - case '\2' : - buffer.append("\\2"); //$NON-NLS-1$ - break; - case '\3' : - buffer.append("\\3"); //$NON-NLS-1$ - break; - case '\4' : - buffer.append("\\4"); //$NON-NLS-1$ - break; - case '\5' : - buffer.append("\\5"); //$NON-NLS-1$ - break; - case '\6' : - buffer.append("\\6"); //$NON-NLS-1$ - break; - case '\7' : - buffer.append("\\7"); //$NON-NLS-1$ - break; - default : - buffer.append(c); - } - } - return buffer.toString(); - } - - static String decodeStringValue(String s) { - return decodeStringValue(s.toCharArray()); - } - - /* - * @see org.eclipse.jdt.core.util.ClassFileBytesDisassembler#disassemble(byte[], java.lang.String, int) - */ - public String disassemble(byte[] classFileBytes, String lineSeparator, int mode) throws ClassFormatException { - try { - return disassemble(new ClassFileReader(classFileBytes, ClassFileReader.ALL), lineSeparator, mode); - } catch (ArrayIndexOutOfBoundsException e) { - throw new ClassFormatException(e.getMessage(), e); - } - } - - private void disassemble(Annotation annotation, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - writeNewLine(buffer, lineSeparator, tabNumber + 1); - final char[] typeName = CharOperation.replaceOnCopy(annotation.getTypeName(), '/', '.'); - buffer.append(NLS.bind(Messages.disassembler_annotationentrystart, new String[] {new String(returnClassName(Signature.toCharArray(typeName), '.', mode))})); - final AnnotationComponent[] components = annotation.getComponents(); - for (int i = 0, max = components.length; i < max; i++) { - disassemble(components[i], buffer, lineSeparator, tabNumber + 1, mode); - } - writeNewLine(buffer, lineSeparator, tabNumber + 1); - buffer.append(Messages.disassembler_annotationentryend); - } - - private void disassemble(AnnotationComponent annotationComponent, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - writeNewLine(buffer, lineSeparator, tabNumber + 1); - buffer.append(NLS.bind(Messages.disassembler_annotationcomponent, new String[] {new String(annotationComponent.getComponentName())})); - disassemble(annotationComponent.getComponentValue(), buffer, lineSeparator, tabNumber + 1, mode); - } - - private void disassemble(AnnotationComponentValue annotationComponentValue, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - switch (annotationComponentValue.getTag()) { - case AnnotationComponentValue.BYTE_TAG : - case AnnotationComponentValue.CHAR_TAG : - case AnnotationComponentValue.DOUBLE_TAG : - case AnnotationComponentValue.FLOAT_TAG : - case AnnotationComponentValue.INTEGER_TAG : - case AnnotationComponentValue.LONG_TAG : - case AnnotationComponentValue.SHORT_TAG : - case AnnotationComponentValue.BOOLEAN_TAG : - case AnnotationComponentValue.STRING_TAG : - ConstantPoolEntry constantPoolEntry = annotationComponentValue.getConstantValue(); - String value = null; - switch (constantPoolEntry.getKind()) { - case ConstantPoolConstant.CONSTANT_Long : - value = constantPoolEntry.getLongValue() + "L"; //$NON-NLS-1$ - break; - case ConstantPoolConstant.CONSTANT_Float : - value = constantPoolEntry.getFloatValue() + "f"; //$NON-NLS-1$ - break; - case ConstantPoolConstant.CONSTANT_Double : - value = Double.toString(constantPoolEntry.getDoubleValue()); - break; - case ConstantPoolConstant.CONSTANT_Integer : - switch (annotationComponentValue.getTag()) { - case AnnotationComponentValue.CHAR_TAG : - value = "'" + (char) constantPoolEntry.getIntegerValue() + "'"; //$NON-NLS-1$//$NON-NLS-2$ - break; - case AnnotationComponentValue.BOOLEAN_TAG : - value = constantPoolEntry.getIntegerValue() == 1 ? "true" : "false";//$NON-NLS-1$//$NON-NLS-2$ - break; - case AnnotationComponentValue.BYTE_TAG : - value = "(byte) " + constantPoolEntry.getIntegerValue(); //$NON-NLS-1$ - break; - case AnnotationComponentValue.SHORT_TAG : - value = "(short) " + constantPoolEntry.getIntegerValue(); //$NON-NLS-1$ - break; - case AnnotationComponentValue.INTEGER_TAG : - value = "(int) " + constantPoolEntry.getIntegerValue(); //$NON-NLS-1$ - } - break; - case ConstantPoolConstant.CONSTANT_Utf8 : - value = "\"" + decodeStringValue(constantPoolEntry.getUtf8Value()) + "\"";//$NON-NLS-1$//$NON-NLS-2$ - } - buffer.append(NLS.bind(Messages.disassembler_annotationdefaultvalue, value)); - break; - case AnnotationComponentValue.ENUM_TAG : - final char[] typeName = CharOperation.replaceOnCopy(annotationComponentValue.getEnumConstantTypeName(), '/', '.'); - final char[] constantName = annotationComponentValue.getEnumConstantName(); - buffer.append(NLS.bind(Messages.disassembler_annotationenumvalue, new String[] {new String(returnClassName(Signature.toCharArray(typeName), '.', mode)), new String(constantName)})); - break; - case AnnotationComponentValue.CLASS_TAG : - constantPoolEntry = annotationComponentValue.getClassInfo(); - final char[] className = CharOperation.replaceOnCopy(constantPoolEntry.getUtf8Value(), '/', '.'); - buffer.append(NLS.bind(Messages.disassembler_annotationclassvalue, new String[] {new String(returnClassName(Signature.toCharArray(className), '.', mode))})); - break; - case AnnotationComponentValue.ANNOTATION_TAG : - buffer.append(Messages.disassembler_annotationannotationvalue); - Annotation annotation = annotationComponentValue.getAnnotationValue(); - disassemble(annotation, buffer, lineSeparator, tabNumber + 1, mode); - break; - case AnnotationComponentValue.ARRAY_TAG : - buffer.append(Messages.disassembler_annotationarrayvaluestart); - final AnnotationComponentValue[] annotationComponentValues = annotationComponentValue.getAnnotationComponentValues(); - for (int i = 0, max = annotationComponentValues.length; i < max; i++) { - writeNewLine(buffer, lineSeparator, tabNumber + 1); - disassemble(annotationComponentValues[i], buffer, lineSeparator, tabNumber + 1, mode); - } - writeNewLine(buffer, lineSeparator, tabNumber + 1); - buffer.append(Messages.disassembler_annotationarrayvalueend); - } - } - - private void disassemble(AnnotationDefaultAttribute annotationDefaultAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - writeNewLine(buffer, lineSeparator, tabNumber + 1); - buffer.append(Messages.disassembler_annotationdefaultheader); - AnnotationComponentValue componentValue = annotationDefaultAttribute.getMemberValue(); - writeNewLine(buffer, lineSeparator, tabNumber + 2); - disassemble(componentValue, buffer, lineSeparator, tabNumber + 1, mode); - } - - /** - * Disassemble a method info header - */ - private void disassemble(ClassFileReader classFileReader, char[] className, MethodInfo methodInfo, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - writeNewLine(buffer, lineSeparator, tabNumber); - final CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); - final char[] methodDescriptor = methodInfo.getDescriptor(); - final SignatureAttribute signatureAttribute = (SignatureAttribute) Utility.getAttribute(methodInfo, AttributeNamesConstants.SIGNATURE); - final ClassFileAttribute runtimeVisibleAnnotationsAttribute = Utility.getAttribute(methodInfo, AttributeNamesConstants.RUNTIME_VISIBLE_ANNOTATIONS); - final ClassFileAttribute runtimeInvisibleAnnotationsAttribute = Utility.getAttribute(methodInfo, AttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS); - final ClassFileAttribute runtimeVisibleParameterAnnotationsAttribute = Utility.getAttribute(methodInfo, AttributeNamesConstants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS); - final ClassFileAttribute runtimeInvisibleParameterAnnotationsAttribute = Utility.getAttribute(methodInfo, AttributeNamesConstants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS); - final ClassFileAttribute annotationDefaultAttribute = Utility.getAttribute(methodInfo, AttributeNamesConstants.ANNOTATION_DEFAULT); - if (checkMode(mode, DETAILED)) { - buffer.append(NLS.bind(Messages.classfileformat_methoddescriptor, new String[] {new String(methodDescriptor)})); - if (methodInfo.isDeprecated()) { - buffer.append(Messages.disassembler_deprecated); - } - writeNewLine(buffer, lineSeparator, tabNumber); - if (signatureAttribute != null) { - buffer.append(NLS.bind(Messages.disassembler_signatureattributeheader, new String(signatureAttribute.getSignature()))); - writeNewLine(buffer, lineSeparator, tabNumber); - } - if (codeAttribute != null) { - buffer.append(NLS.bind(Messages.classfileformat_stacksAndLocals, new String[] {Integer.toString(codeAttribute.getMaxStack()), Integer.toString(codeAttribute.getMaxLocals())})); - writeNewLine(buffer, lineSeparator, tabNumber); - } - // disassemble compact version of annotations - if (runtimeInvisibleAnnotationsAttribute != null) { - disassembleAsModifier((RuntimeInvisibleAnnotationsAttribute) runtimeInvisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); - writeNewLine(buffer, lineSeparator, tabNumber); - } - if (runtimeVisibleAnnotationsAttribute != null) { - disassembleAsModifier((RuntimeVisibleAnnotationsAttribute) runtimeVisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); - writeNewLine(buffer, lineSeparator, tabNumber); - } - } - final int accessFlags = methodInfo.getAccessFlags(); - decodeModifiersForMethod(buffer, accessFlags); - if (methodInfo.isSynthetic()) { - buffer.append("synthetic"); //$NON-NLS-1$ - buffer.append(Messages.disassembler_space); - } - CharOperation.replace(methodDescriptor, '/', '.'); - final boolean isVarArgs = isVarArgs(methodInfo); - char[] methodHeader = null; - if (methodInfo.isConstructor()) { - methodHeader = Signature.toCharArray(methodDescriptor, returnClassName(className, '.', COMPACT), null, !checkMode(mode, COMPACT), false, isVarArgs); - } else if (methodInfo.isClinit()) { - methodHeader = Messages.classfileformat_clinitname.toCharArray(); - } else { - methodHeader = Signature.toCharArray(methodDescriptor, methodInfo.getName(), null, !checkMode(mode, COMPACT), true, isVarArgs); - } - if (checkMode(mode, DETAILED) && (runtimeInvisibleParameterAnnotationsAttribute != null || runtimeVisibleParameterAnnotationsAttribute != null)) { - ParameterAnnotation[] invisibleParameterAnnotations = null; - ParameterAnnotation[] visibleParameterAnnotations = null; - int length = -1; - if (runtimeInvisibleParameterAnnotationsAttribute != null) { - RuntimeInvisibleParameterAnnotationsAttribute attribute = (RuntimeInvisibleParameterAnnotationsAttribute) runtimeInvisibleParameterAnnotationsAttribute; - invisibleParameterAnnotations = attribute.getParameterAnnotations(); - length = invisibleParameterAnnotations.length; - } - if (runtimeVisibleParameterAnnotationsAttribute != null) { - RuntimeVisibleParameterAnnotationsAttribute attribute = (RuntimeVisibleParameterAnnotationsAttribute) runtimeVisibleParameterAnnotationsAttribute; - visibleParameterAnnotations = attribute.getParameterAnnotations(); - length = visibleParameterAnnotations.length; - } - int insertionPosition = CharOperation.indexOf('(', methodHeader) + 1; - int start = 0; - StringBuffer stringBuffer = new StringBuffer(); - stringBuffer.append(methodHeader, 0, insertionPosition); - for (int i = 0; i < length; i++) { - if (i > 0) { - stringBuffer.append(' '); - } - int stringBufferSize = stringBuffer.length(); - if (runtimeVisibleParameterAnnotationsAttribute != null) { - disassembleAsModifier((RuntimeVisibleParameterAnnotationsAttribute) runtimeVisibleParameterAnnotationsAttribute, stringBuffer, i, lineSeparator, tabNumber, mode); - } - if (runtimeInvisibleParameterAnnotationsAttribute != null) { - if (stringBuffer.length() != stringBufferSize) { - stringBuffer.append(' '); - stringBufferSize = stringBuffer.length(); - } - disassembleAsModifier((RuntimeInvisibleParameterAnnotationsAttribute) runtimeInvisibleParameterAnnotationsAttribute, stringBuffer, i, lineSeparator, tabNumber, mode); - } - if (i == 0 && stringBuffer.length() != stringBufferSize) { - stringBuffer.append(' '); - } - start = insertionPosition; - insertionPosition = CharOperation.indexOf(',', methodHeader, start + 1) + 1; - if (insertionPosition == 0) { - stringBuffer.append(methodHeader, start, methodHeader.length - start); - } else { - stringBuffer.append(methodHeader, start, insertionPosition - start); - } - } - buffer.append(stringBuffer); - } else { - buffer.append(methodHeader); - } - ExceptionAttribute exceptionAttribute = methodInfo.getExceptionAttribute(); - if (exceptionAttribute != null) { - buffer.append(" throws "); //$NON-NLS-1$ - char[][] exceptionNames = exceptionAttribute.getExceptionNames(); - int length = exceptionNames.length; - for (int i = 0; i < length; i++) { - if (i != 0) { - buffer.append(Messages.disassembler_comma).append(Messages.disassembler_space); - } - char[] exceptionName = exceptionNames[i]; - CharOperation.replace(exceptionName, '/', '.'); - buffer.append(returnClassName(exceptionName, '.', mode)); - } - } - if (checkMode(mode, DETAILED)) { - if (annotationDefaultAttribute != null) { - buffer.append(" default "); //$NON-NLS-1$ - disassembleAsModifier((AnnotationDefaultAttribute) annotationDefaultAttribute, buffer, lineSeparator, tabNumber, mode); - } - } - buffer.append(Messages.disassembler_endofmethodheader); - - if (checkMode(mode, DETAILED)) { - if (codeAttribute != null) { - disassemble(codeAttribute, methodDescriptor, (accessFlags & IModifierConstants.ACC_STATIC) != 0, buffer, lineSeparator, tabNumber, mode); - } - if (annotationDefaultAttribute != null) { - disassemble((AnnotationDefaultAttribute) annotationDefaultAttribute, buffer, lineSeparator, tabNumber, mode); - } - if (runtimeVisibleAnnotationsAttribute != null) { - disassemble((RuntimeVisibleAnnotationsAttribute) runtimeVisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); - } - if (runtimeInvisibleAnnotationsAttribute != null) { - disassemble((RuntimeInvisibleAnnotationsAttribute) runtimeInvisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); - } - if (runtimeVisibleParameterAnnotationsAttribute != null) { - disassemble((RuntimeVisibleParameterAnnotationsAttribute) runtimeVisibleParameterAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); - } - if (runtimeInvisibleParameterAnnotationsAttribute != null) { - disassemble((RuntimeInvisibleParameterAnnotationsAttribute) runtimeInvisibleParameterAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); - } - } - } - - /** - * Answers back the disassembled string of the ClassFileReader according to the - * mode. - * This is an output quite similar to the javap tool. - * - * @param classFileReader The classFileReader to be disassembled - * @param lineSeparator the line separator to use. - * @param mode the mode used to disassemble the ClassFileReader - * - * @return the disassembled string of the ClassFileReader according to the mode - */ - private String disassemble(ClassFileReader classFileReader, String lineSeparator, int mode) { - if (classFileReader == null) - return Utility.EMPTY_STRING; - char[] className = classFileReader.getClassName(); - if (className == null) { - // incomplete initialization. We cannot go further. - return Utility.EMPTY_STRING; - } - className = CharOperation.replaceOnCopy(className, '/', '.'); - final int accessFlags = classFileReader.getAccessFlags(); - final boolean isEnum = (accessFlags & IModifierConstants.ACC_ENUM) != 0; - - StringBuffer buffer = new StringBuffer(); - SourceFileAttribute sourceAttribute = classFileReader.getSourceFileAttribute(); - ClassFileAttribute classFileAttribute = Utility.getAttribute(classFileReader, AttributeNamesConstants.SIGNATURE); - SignatureAttribute signatureAttribute = (SignatureAttribute) classFileAttribute; - if (checkMode(mode, DETAILED)) { - int minorVersion = classFileReader.getMinorVersion(); - int majorVersion = classFileReader.getMajorVersion(); - buffer.append(Messages.disassembler_begincommentline); - if (sourceAttribute != null) { - buffer.append(Messages.disassembler_sourceattributeheader); - buffer.append(sourceAttribute.getSourceFileName()); - } - String versionNumber = VERSION_UNKNOWN; - if (minorVersion == 3 && majorVersion == 45) { - versionNumber = IModifierConstants.VERSION_1_1; - } else if (minorVersion == 0 && majorVersion == 46) { - versionNumber = IModifierConstants.VERSION_1_2; - } else if (minorVersion == 0 && majorVersion == 47) { - versionNumber = IModifierConstants.VERSION_1_3; - } else if (minorVersion == 0 && majorVersion == 48) { - versionNumber = IModifierConstants.VERSION_1_4; - } else if (minorVersion == 0 && majorVersion == 49) { - versionNumber = IModifierConstants.VERSION_1_5; - } else if (minorVersion == 0 && majorVersion == 50) { - versionNumber = IModifierConstants.VERSION_1_6; - } else if (minorVersion == 0 && majorVersion == 51) { - versionNumber = IModifierConstants.VERSION_1_7; - } - buffer.append(NLS.bind(Messages.classfileformat_versiondetails, new String[] {versionNumber, Integer.toString(majorVersion), Integer.toString(minorVersion), ((accessFlags & IModifierConstants.ACC_SUPER) != 0 ? Messages.classfileformat_superflagisset : Messages.classfileformat_superflagisnotset) + (isDeprecated(classFileReader) ? ", deprecated" : Utility.EMPTY_STRING)//$NON-NLS-1$ - })); - writeNewLine(buffer, lineSeparator, 0); - if (signatureAttribute != null) { - buffer.append(NLS.bind(Messages.disassembler_signatureattributeheader, new String(signatureAttribute.getSignature()))); - writeNewLine(buffer, lineSeparator, 0); - } - } - - InnerClassesAttribute innerClassesAttribute = classFileReader.getInnerClassesAttribute(); - ClassFileAttribute runtimeVisibleAnnotationsAttribute = Utility.getAttribute(classFileReader, AttributeNamesConstants.RUNTIME_VISIBLE_ANNOTATIONS); - ClassFileAttribute runtimeInvisibleAnnotationsAttribute = Utility.getAttribute(classFileReader, AttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS); - - if (checkMode(mode, DETAILED)) { - // disassemble compact version of annotations - if (runtimeInvisibleAnnotationsAttribute != null) { - disassembleAsModifier((RuntimeInvisibleAnnotationsAttribute) runtimeInvisibleAnnotationsAttribute, buffer, lineSeparator, 0, mode); - writeNewLine(buffer, lineSeparator, 0); - } - if (runtimeVisibleAnnotationsAttribute != null) { - disassembleAsModifier((RuntimeVisibleAnnotationsAttribute) runtimeVisibleAnnotationsAttribute, buffer, lineSeparator, 0, mode); - writeNewLine(buffer, lineSeparator, 0); - } - } - boolean decoded = false; - if (innerClassesAttribute != null) { - // search the right entry - InnerClassesAttributeEntry[] entries = innerClassesAttribute.getInnerClassAttributesEntries(); - for (int i = 0, max = entries.length; i < max; i++) { - InnerClassesAttributeEntry entry = entries[i]; - char[] innerClassName = entry.getInnerClassName(); - if (innerClassName != null) { - if (Arrays.equals(classFileReader.getClassName(), innerClassName)) { - decodeModifiersForInnerClasses(buffer, entry.getAccessFlags(), false); - decoded = true; - } - } - } - } - if (!decoded) { - decodeModifiersForType(buffer, accessFlags); - if (isSynthetic(classFileReader)) { - buffer.append("synthetic"); //$NON-NLS-1$ - buffer.append(Messages.disassembler_space); - } - } - - final boolean isAnnotation = (accessFlags & IModifierConstants.ACC_ANNOTATION) != 0; - boolean isInterface = false; - if (isEnum) { - buffer.append("enum "); //$NON-NLS-1$ - } else if (classFileReader.isClass()) { - buffer.append("class "); //$NON-NLS-1$ - } else { - if (isAnnotation) { - buffer.append("@"); //$NON-NLS-1$ - } - buffer.append("interface "); //$NON-NLS-1$ - isInterface = true; - } - - buffer.append(className); - - char[] superclassName = classFileReader.getSuperclassName(); - if (superclassName != null) { - CharOperation.replace(superclassName, '/', '.'); - if (!isJavaLangObject(superclassName) && !isEnum) { - buffer.append(" extends "); //$NON-NLS-1$ - buffer.append(returnClassName(superclassName, '.', mode)); - } - } - if (!isAnnotation) { - char[][] superclassInterfaces = classFileReader.getInterfaceNames(); - int length = superclassInterfaces.length; - if (length != 0) { - if (isInterface) { - buffer.append(" extends "); //$NON-NLS-1$ - } else { - buffer.append(" implements "); //$NON-NLS-1$ - } - for (int i = 0; i < length; i++) { - if (i != 0) { - buffer.append(Messages.disassembler_comma).append(Messages.disassembler_space); - } - char[] superinterface = superclassInterfaces[i]; - CharOperation.replace(superinterface, '/', '.'); - buffer.append(returnClassName(superinterface, '.', mode)); - } - } - } - buffer.append(Messages.disassembler_opentypedeclaration); - disassembleTypeMembers(classFileReader, className, buffer, lineSeparator, 1, mode, isEnum); - if (checkMode(mode, DETAILED)) { - ClassFileAttribute[] attributes = classFileReader.getAttributes(); - int length = attributes.length; - EnclosingMethodAttribute enclosingMethodAttribute = getEnclosingMethodAttribute(classFileReader); - int remainingAttributesLength = length; - if (innerClassesAttribute != null) { - remainingAttributesLength--; - } - if (enclosingMethodAttribute != null) { - remainingAttributesLength--; - } - if (sourceAttribute != null) { - remainingAttributesLength--; - } - if (signatureAttribute != null) { - remainingAttributesLength--; - } - if (innerClassesAttribute != null || enclosingMethodAttribute != null || remainingAttributesLength != 0) { - writeNewLine(buffer, lineSeparator, 0); - } - if (innerClassesAttribute != null) { - disassemble(innerClassesAttribute, buffer, lineSeparator, 1); - } - if (enclosingMethodAttribute != null) { - disassemble(enclosingMethodAttribute, buffer, lineSeparator, 0); - } - if (runtimeVisibleAnnotationsAttribute != null) { - disassemble((RuntimeVisibleAnnotationsAttribute) runtimeVisibleAnnotationsAttribute, buffer, lineSeparator, 0, mode); - } - if (runtimeInvisibleAnnotationsAttribute != null) { - disassemble((RuntimeInvisibleAnnotationsAttribute) runtimeInvisibleAnnotationsAttribute, buffer, lineSeparator, 0, mode); - } - } - writeNewLine(buffer, lineSeparator, 0); - buffer.append(Messages.disassembler_closetypedeclaration); - return buffer.toString(); - } - - private boolean isJavaLangObject(final char[] className) { - return Arrays.equals(TypeConstants.JAVA_LANG_OBJECT, CharOperation.splitOn('.', className)); - } - - private boolean isVarArgs(MethodInfo methodInfo) { - int accessFlags = methodInfo.getAccessFlags(); - if ((accessFlags & IModifierConstants.ACC_VARARGS) != 0) - return true; - // check the presence of the unspecified Varargs attribute - return Utility.getAttribute(methodInfo, AttributeNamesConstants.VAR_ARGS) != null; - } - - private void disassemble(CodeAttribute codeAttribute, char[] methodDescriptor, boolean isStatic, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - writeNewLine(buffer, lineSeparator, tabNumber - 1); - DefaultBytecodeVisitor visitor = new DefaultBytecodeVisitor(codeAttribute, methodDescriptor, isStatic, buffer, lineSeparator, tabNumber, mode); - try { - codeAttribute.traverse(visitor); - } catch (ClassFormatException e) { - dumpTab(tabNumber + 2, buffer); - buffer.append(Messages.classformat_classformatexception); - writeNewLine(buffer, lineSeparator, tabNumber + 1); - } - final int exceptionTableLength = codeAttribute.getExceptionTableLength(); - if (exceptionTableLength != 0) { - final int tabNumberForExceptionAttribute = tabNumber + 2; - dumpTab(tabNumberForExceptionAttribute, buffer); - final ExceptionTableEntry[] exceptionTableEntries = codeAttribute.getExceptionTable(); - buffer.append(Messages.disassembler_exceptiontableheader); - writeNewLine(buffer, lineSeparator, tabNumberForExceptionAttribute + 1); - for (int i = 0; i < exceptionTableLength; i++) { - if (i != 0) { - writeNewLine(buffer, lineSeparator, tabNumberForExceptionAttribute + 1); - } - ExceptionTableEntry exceptionTableEntry = exceptionTableEntries[i]; - char[] catchType; - if (exceptionTableEntry.getCatchTypeIndex() != 0) { - catchType = exceptionTableEntry.getCatchType(); - CharOperation.replace(catchType, '/', '.'); - catchType = returnClassName(catchType, '.', mode); - } else { - catchType = ANY_EXCEPTION; - } - buffer.append(NLS.bind(Messages.classfileformat_exceptiontableentry, new String[] {Integer.toString(exceptionTableEntry.getStartPC()), Integer.toString(exceptionTableEntry.getEndPC()), Integer.toString(exceptionTableEntry.getHandlerPC()), new String(catchType),})); - } - } - } - - private void disassemble(EnclosingMethodAttribute enclosingMethodAttribute, StringBuffer buffer, String lineSeparator, int tabNumber) { - writeNewLine(buffer, lineSeparator, tabNumber + 1); - buffer.append(Messages.disassembler_enclosingmethodheader); - buffer.append(" ")//$NON-NLS-1$ - .append(enclosingMethodAttribute.getEnclosingClass()); - if (enclosingMethodAttribute.getMethodNameAndTypeIndex() != 0) { - buffer.append(".")//$NON-NLS-1$ - .append(enclosingMethodAttribute.getMethodName()).append(enclosingMethodAttribute.getMethodDescriptor()); - } - } - - /** - * Disassemble a field info - */ - private void disassemble(FieldInfo fieldInfo, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - writeNewLine(buffer, lineSeparator, tabNumber); - final char[] fieldDescriptor = fieldInfo.getDescriptor(); - final SignatureAttribute signatureAttribute = (SignatureAttribute) Utility.getAttribute(fieldInfo, AttributeNamesConstants.SIGNATURE); - if (checkMode(mode, DETAILED)) { - buffer.append(NLS.bind(Messages.classfileformat_fieldddescriptor, new String[] {new String(fieldDescriptor)})); - if (fieldInfo.isDeprecated()) { - buffer.append(Messages.disassembler_deprecated); - } - writeNewLine(buffer, lineSeparator, tabNumber); - if (signatureAttribute != null) { - buffer.append(NLS.bind(Messages.disassembler_signatureattributeheader, new String(signatureAttribute.getSignature()))); - writeNewLine(buffer, lineSeparator, tabNumber); - } - } - final ClassFileAttribute runtimeVisibleAnnotationsAttribute = Utility.getAttribute(fieldInfo, AttributeNamesConstants.RUNTIME_VISIBLE_ANNOTATIONS); - final ClassFileAttribute runtimeInvisibleAnnotationsAttribute = Utility.getAttribute(fieldInfo, AttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS); - if (checkMode(mode, DETAILED)) { - // disassemble compact version of annotations - if (runtimeInvisibleAnnotationsAttribute != null) { - disassembleAsModifier((RuntimeInvisibleAnnotationsAttribute) runtimeInvisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); - writeNewLine(buffer, lineSeparator, tabNumber); - } - if (runtimeVisibleAnnotationsAttribute != null) { - disassembleAsModifier((RuntimeVisibleAnnotationsAttribute) runtimeVisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); - writeNewLine(buffer, lineSeparator, tabNumber); - } - } - decodeModifiersForField(buffer, fieldInfo.getAccessFlags()); - if (fieldInfo.isSynthetic()) { - buffer.append("synthetic"); //$NON-NLS-1$ - buffer.append(Messages.disassembler_space); - } - buffer.append(returnClassName(getSignatureForField(fieldDescriptor), '.', mode)); - buffer.append(' '); - buffer.append(new String(fieldInfo.getName())); - ConstantValueAttribute constantValueAttribute = fieldInfo.getConstantValueAttribute(); - if (constantValueAttribute != null) { - buffer.append(Messages.disassembler_fieldhasconstant); - ConstantPoolEntry constantPoolEntry = constantValueAttribute.getConstantValue(); - switch (constantPoolEntry.getKind()) { - case ConstantPoolConstant.CONSTANT_Long : - buffer.append(constantPoolEntry.getLongValue() + "L"); //$NON-NLS-1$ - break; - case ConstantPoolConstant.CONSTANT_Float : - buffer.append(constantPoolEntry.getFloatValue() + "f"); //$NON-NLS-1$ - break; - case ConstantPoolConstant.CONSTANT_Double : - buffer.append(constantPoolEntry.getDoubleValue()); - break; - case ConstantPoolConstant.CONSTANT_Integer : - switch (fieldDescriptor[0]) { - case 'C' : - buffer.append("'" + (char) constantPoolEntry.getIntegerValue() + "'"); //$NON-NLS-1$//$NON-NLS-2$ - break; - case 'Z' : - buffer.append(constantPoolEntry.getIntegerValue() == 1 ? "true" : "false");//$NON-NLS-1$//$NON-NLS-2$ - break; - case 'B' : - buffer.append(constantPoolEntry.getIntegerValue()); - break; - case 'S' : - buffer.append(constantPoolEntry.getIntegerValue()); - break; - case 'I' : - buffer.append(constantPoolEntry.getIntegerValue()); - } - break; - case ConstantPoolConstant.CONSTANT_String : - buffer.append("\"" + decodeStringValue(constantPoolEntry.getStringValue()) + "\"");//$NON-NLS-1$//$NON-NLS-2$ - } - } - buffer.append(Messages.disassembler_endoffieldheader); - if (checkMode(mode, DETAILED)) { - if (runtimeVisibleAnnotationsAttribute != null) { - disassemble((RuntimeVisibleAnnotationsAttribute) runtimeVisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); - } - if (runtimeInvisibleAnnotationsAttribute != null) { - disassemble((RuntimeInvisibleAnnotationsAttribute) runtimeInvisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); - } - } - } - - private void disassemble(InnerClassesAttribute innerClassesAttribute, StringBuffer buffer, String lineSeparator, int tabNumber) { - writeNewLine(buffer, lineSeparator, tabNumber); - buffer.append(Messages.disassembler_innerattributesheader); - writeNewLine(buffer, lineSeparator, tabNumber + 1); - InnerClassesAttributeEntry[] innerClassesAttributeEntries = innerClassesAttribute.getInnerClassAttributesEntries(); - int length = innerClassesAttributeEntries.length; - int innerClassNameIndex, outerClassNameIndex, innerNameIndex, accessFlags; - InnerClassesAttributeEntry innerClassesAttributeEntry; - for (int i = 0; i < length; i++) { - if (i != 0) { - buffer.append(Messages.disassembler_comma); - writeNewLine(buffer, lineSeparator, tabNumber + 1); - } - innerClassesAttributeEntry = innerClassesAttributeEntries[i]; - innerClassNameIndex = innerClassesAttributeEntry.getInnerClassNameIndex(); - outerClassNameIndex = innerClassesAttributeEntry.getOuterClassNameIndex(); - innerNameIndex = innerClassesAttributeEntry.getInnerNameIndex(); - accessFlags = innerClassesAttributeEntry.getAccessFlags(); - buffer.append(Messages.disassembler_openinnerclassentry).append(Messages.disassembler_inner_class_info_name); - if (innerClassNameIndex != 0) { - buffer.append(Messages.disassembler_space).append(innerClassesAttributeEntry.getInnerClassName()); - } - buffer.append(Messages.disassembler_comma).append(Messages.disassembler_space).append(Messages.disassembler_outer_class_info_name); - if (outerClassNameIndex != 0) { - buffer.append(Messages.disassembler_space).append(innerClassesAttributeEntry.getOuterClassName()); - } - writeNewLine(buffer, lineSeparator, tabNumber); - dumpTab(tabNumber, buffer); - buffer.append(Messages.disassembler_space); - buffer.append(Messages.disassembler_inner_name); - if (innerNameIndex != 0) { - buffer.append(Messages.disassembler_space).append(innerClassesAttributeEntry.getInnerName()); - } - buffer.append(Messages.disassembler_comma).append(Messages.disassembler_space).append(Messages.disassembler_inner_accessflags).append(accessFlags).append(Messages.disassembler_space); - decodeModifiersForInnerClasses(buffer, accessFlags, true); - buffer.append(Messages.disassembler_closeinnerclassentry); - } - } - - private void disassemble(int index, ParameterAnnotation parameterAnnotation, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - Annotation[] annotations = parameterAnnotation.getAnnotations(); - writeNewLine(buffer, lineSeparator, tabNumber + 1); - buffer.append(NLS.bind(Messages.disassembler_parameterannotationentrystart, new String[] {Integer.toString(index), Integer.toString(annotations.length)})); - for (int i = 0, max = annotations.length; i < max; i++) { - disassemble(annotations[i], buffer, lineSeparator, tabNumber + 1, mode); - } - } - - private void disassemble(RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - writeNewLine(buffer, lineSeparator, tabNumber + 1); - buffer.append(Messages.disassembler_runtimeinvisibleannotationsattributeheader); - Annotation[] annotations = runtimeInvisibleAnnotationsAttribute.getAnnotations(); - for (int i = 0, max = annotations.length; i < max; i++) { - disassemble(annotations[i], buffer, lineSeparator, tabNumber + 1, mode); - } - } - - private void disassemble(RuntimeInvisibleParameterAnnotationsAttribute runtimeInvisibleParameterAnnotationsAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - writeNewLine(buffer, lineSeparator, tabNumber + 1); - buffer.append(Messages.disassembler_runtimeinvisibleparameterannotationsattributeheader); - ParameterAnnotation[] parameterAnnotations = runtimeInvisibleParameterAnnotationsAttribute.getParameterAnnotations(); - for (int i = 0, max = parameterAnnotations.length; i < max; i++) { - disassemble(i, parameterAnnotations[i], buffer, lineSeparator, tabNumber + 1, mode); - } - } - - private void disassemble(RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - writeNewLine(buffer, lineSeparator, tabNumber + 1); - buffer.append(Messages.disassembler_runtimevisibleannotationsattributeheader); - Annotation[] annotations = runtimeVisibleAnnotationsAttribute.getAnnotations(); - for (int i = 0, max = annotations.length; i < max; i++) { - disassemble(annotations[i], buffer, lineSeparator, tabNumber + 1, mode); - } - } - - private void disassemble(RuntimeVisibleParameterAnnotationsAttribute runtimeVisibleParameterAnnotationsAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - writeNewLine(buffer, lineSeparator, tabNumber + 1); - buffer.append(Messages.disassembler_runtimevisibleparameterannotationsattributeheader); - ParameterAnnotation[] parameterAnnotations = runtimeVisibleParameterAnnotationsAttribute.getParameterAnnotations(); - for (int i = 0, max = parameterAnnotations.length; i < max; i++) { - disassemble(i, parameterAnnotations[i], buffer, lineSeparator, tabNumber + 1, mode); - } - } - - private void disassembleAsModifier(Annotation annotation, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - final char[] typeName = CharOperation.replaceOnCopy(annotation.getTypeName(), '/', '.'); - buffer.append('@').append(returnClassName(Signature.toCharArray(typeName), '.', mode)); - final AnnotationComponent[] components = annotation.getComponents(); - final int length = components.length; - if (length != 0) { - buffer.append('('); - for (int i = 0; i < length; i++) { - if (i > 0) { - buffer.append(','); - writeNewLine(buffer, lineSeparator, tabNumber); - } - disassembleAsModifier(components[i], buffer, lineSeparator, tabNumber + 1, mode); - } - buffer.append(')'); - } - } - - private void disassembleAsModifier(AnnotationComponent annotationComponent, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - buffer.append(annotationComponent.getComponentName()).append('='); - disassembleAsModifier(annotationComponent.getComponentValue(), buffer, lineSeparator, tabNumber + 1, mode); - } - - private void disassembleAsModifier(AnnotationComponentValue annotationComponentValue, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - switch (annotationComponentValue.getTag()) { - case AnnotationComponentValue.BYTE_TAG : - case AnnotationComponentValue.CHAR_TAG : - case AnnotationComponentValue.DOUBLE_TAG : - case AnnotationComponentValue.FLOAT_TAG : - case AnnotationComponentValue.INTEGER_TAG : - case AnnotationComponentValue.LONG_TAG : - case AnnotationComponentValue.SHORT_TAG : - case AnnotationComponentValue.BOOLEAN_TAG : - case AnnotationComponentValue.STRING_TAG : - ConstantPoolEntry constantPoolEntry = annotationComponentValue.getConstantValue(); - String value = null; - switch (constantPoolEntry.getKind()) { - case ConstantPoolConstant.CONSTANT_Long : - value = constantPoolEntry.getLongValue() + "L"; //$NON-NLS-1$ - break; - case ConstantPoolConstant.CONSTANT_Float : - value = constantPoolEntry.getFloatValue() + "f"; //$NON-NLS-1$ - break; - case ConstantPoolConstant.CONSTANT_Double : - value = Double.toString(constantPoolEntry.getDoubleValue()); - break; - case ConstantPoolConstant.CONSTANT_Integer : - switch (annotationComponentValue.getTag()) { - case AnnotationComponentValue.CHAR_TAG : - value = "'" + (char) constantPoolEntry.getIntegerValue() + "'"; //$NON-NLS-1$//$NON-NLS-2$ - break; - case AnnotationComponentValue.BOOLEAN_TAG : - value = constantPoolEntry.getIntegerValue() == 1 ? "true" : "false";//$NON-NLS-1$//$NON-NLS-2$ - break; - case AnnotationComponentValue.BYTE_TAG : - value = "(byte) " + constantPoolEntry.getIntegerValue(); //$NON-NLS-1$ - break; - case AnnotationComponentValue.SHORT_TAG : - value = "(short) " + constantPoolEntry.getIntegerValue(); //$NON-NLS-1$ - break; - case AnnotationComponentValue.INTEGER_TAG : - value = "(int) " + constantPoolEntry.getIntegerValue(); //$NON-NLS-1$ - } - break; - case ConstantPoolConstant.CONSTANT_Utf8 : - value = "\"" + decodeStringValue(constantPoolEntry.getUtf8Value()) + "\"";//$NON-NLS-1$//$NON-NLS-2$ - } - buffer.append(value); - break; - case AnnotationComponentValue.ENUM_TAG : - final char[] typeName = CharOperation.replaceOnCopy(annotationComponentValue.getEnumConstantTypeName(), '/', '.'); - final char[] constantName = annotationComponentValue.getEnumConstantName(); - buffer.append(returnClassName(Signature.toCharArray(typeName), '.', mode)).append('.').append(constantName); - break; - case AnnotationComponentValue.CLASS_TAG : - constantPoolEntry = annotationComponentValue.getClassInfo(); - final char[] className = CharOperation.replaceOnCopy(constantPoolEntry.getUtf8Value(), '/', '.'); - buffer.append(returnClassName(Signature.toCharArray(className), '.', mode)); - break; - case AnnotationComponentValue.ANNOTATION_TAG : - Annotation annotation = annotationComponentValue.getAnnotationValue(); - disassembleAsModifier(annotation, buffer, lineSeparator, tabNumber + 1, mode); - break; - case AnnotationComponentValue.ARRAY_TAG : - final AnnotationComponentValue[] annotationComponentValues = annotationComponentValue.getAnnotationComponentValues(); - buffer.append('{'); - for (int i = 0, max = annotationComponentValues.length; i < max; i++) { - if (i > 0) { - buffer.append(','); - } - disassembleAsModifier(annotationComponentValues[i], buffer, lineSeparator, tabNumber + 1, mode); - } - buffer.append('}'); - } - } - - private void disassembleAsModifier(AnnotationDefaultAttribute annotationDefaultAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - AnnotationComponentValue componentValue = annotationDefaultAttribute.getMemberValue(); - disassembleAsModifier(componentValue, buffer, lineSeparator, tabNumber + 1, mode); - } - - private void disassembleAsModifier(RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - Annotation[] annotations = runtimeInvisibleAnnotationsAttribute.getAnnotations(); - for (int i = 0, max = annotations.length; i < max; i++) { - disassembleAsModifier(annotations[i], buffer, lineSeparator, tabNumber + 1, mode); - } - } - - private void disassembleAsModifier(RuntimeInvisibleParameterAnnotationsAttribute runtimeInvisibleParameterAnnotationsAttribute, StringBuffer buffer, int index, String lineSeparator, int tabNumber, int mode) { - ParameterAnnotation[] parameterAnnotations = runtimeInvisibleParameterAnnotationsAttribute.getParameterAnnotations(); - if (parameterAnnotations.length > index) { - disassembleAsModifier(parameterAnnotations[index], buffer, lineSeparator, tabNumber + 1, mode); - } - } - - private void disassembleAsModifier(RuntimeVisibleParameterAnnotationsAttribute runtimeVisibleParameterAnnotationsAttribute, StringBuffer buffer, int index, String lineSeparator, int tabNumber, int mode) { - ParameterAnnotation[] parameterAnnotations = runtimeVisibleParameterAnnotationsAttribute.getParameterAnnotations(); - if (parameterAnnotations.length > index) { - disassembleAsModifier(parameterAnnotations[index], buffer, lineSeparator, tabNumber + 1, mode); - } - } - - private void disassembleAsModifier(ParameterAnnotation parameterAnnotation, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - Annotation[] annotations = parameterAnnotation.getAnnotations(); - for (int i = 0, max = annotations.length; i < max; i++) { - if (i > 0) { - buffer.append(' '); - } - disassembleAsModifier(annotations[i], buffer, lineSeparator, tabNumber + 1, mode); - } - } - - private void disassembleAsModifier(RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { - Annotation[] annotations = runtimeVisibleAnnotationsAttribute.getAnnotations(); - for (int i = 0, max = annotations.length; i < max; i++) { - if (i > 0) { - writeNewLine(buffer, lineSeparator, tabNumber); - } - disassembleAsModifier(annotations[i], buffer, lineSeparator, tabNumber + 1, mode); - } - } - - private void disassembleTypeMembers(ClassFileReader classFileReader, char[] className, StringBuffer buffer, String lineSeparator, int tabNumber, int mode, boolean isEnum) { - FieldInfo[] fields = classFileReader.getFieldInfos(); - // sort fields - Arrays.sort(fields, new Comparator() { - public int compare(Object o1, Object o2) { - FieldInfo fieldInfo1 = (FieldInfo) o1; - FieldInfo fieldInfo2 = (FieldInfo) o2; - int compare = new String(fieldInfo1.getName()).compareTo(new String(fieldInfo2.getName())); - if (compare == 0) { - return new String(fieldInfo1.getDescriptor()).compareTo(new String(fieldInfo2.getDescriptor())); - } - return compare; - } - }); - for (int i = 0, max = fields.length; i < max; i++) { - writeNewLine(buffer, lineSeparator, tabNumber); - disassemble(fields[i], buffer, lineSeparator, tabNumber, mode); - } - MethodInfo[] methods = classFileReader.getMethodInfos(); - // sort methods - Arrays.sort(methods, new Comparator() { - public int compare(Object o1, Object o2) { - MethodInfo methodInfo1 = (MethodInfo) o1; - MethodInfo methodInfo2 = (MethodInfo) o2; - int compare = new String(methodInfo1.getName()).compareTo(new String(methodInfo2.getName())); - if (compare == 0) { - return new String(methodInfo1.getDescriptor()).compareTo(new String(methodInfo2.getDescriptor())); - } - return compare; - } - }); - for (int i = 0, max = methods.length; i < max; i++) { - writeNewLine(buffer, lineSeparator, tabNumber); - disassemble(classFileReader, className, methods[i], buffer, lineSeparator, tabNumber, mode); - } - } - - private final void dumpTab(int tabNumber, StringBuffer buffer) { - for (int i = 0; i < tabNumber; i++) { - buffer.append(Messages.disassembler_indentation); - } - } - - private EnclosingMethodAttribute getEnclosingMethodAttribute(ClassFileReader classFileReader) { - ClassFileAttribute[] attributes = classFileReader.getAttributes(); - for (int i = 0, max = attributes.length; i < max; i++) { - if (Arrays.equals(attributes[i].getAttributeName(), AttributeNamesConstants.ENCLOSING_METHOD)) { - return (EnclosingMethodAttribute) attributes[i]; - } - } - return null; - } - - private char[] getSignatureForField(char[] fieldDescriptor) { - char[] newFieldDescriptor = CharOperation.replaceOnCopy(fieldDescriptor, '/', '.'); - newFieldDescriptor = CharOperation.replaceOnCopy(newFieldDescriptor, '$', '%'); - char[] fieldDescriptorSignature = Signature.toCharArray(newFieldDescriptor); - CharOperation.replace(fieldDescriptorSignature, '%', '$'); - return fieldDescriptorSignature; - } - - private boolean isDeprecated(ClassFileReader classFileReader) { - ClassFileAttribute[] attributes = classFileReader.getAttributes(); - for (int i = 0, max = attributes.length; i < max; i++) { - if (Arrays.equals(attributes[i].getAttributeName(), AttributeNamesConstants.DEPRECATED)) { - return true; - } - } - return false; - } - - private boolean isSynthetic(ClassFileReader classFileReader) { - int flags = classFileReader.getAccessFlags(); - if ((flags & IModifierConstants.ACC_SYNTHETIC) != 0) { - return true; - } - ClassFileAttribute[] attributes = classFileReader.getAttributes(); - for (int i = 0, max = attributes.length; i < max; i++) { - if (Arrays.equals(attributes[i].getAttributeName(), AttributeNamesConstants.SYNTHETIC)) { - return true; - } - } - return false; - } - - private boolean checkMode(int mode, int flag) { - return (mode & flag) != 0; - } - - private boolean isCompact(int mode) { - return (mode & Disassembler.COMPACT) != 0; - } - - private char[] returnClassName(char[] classInfoName, char separator, int mode) { - if (classInfoName.length == 0) { - return CharOperation.NO_CHAR; - } else if (isCompact(mode)) { - int lastIndexOfSlash = CharOperation.lastIndexOf(separator, classInfoName); - if (lastIndexOfSlash != -1) { - return CharOperation.subarray(classInfoName, lastIndexOfSlash + 1, classInfoName.length); - } - } - return classInfoName; - } - - private void writeNewLine(StringBuffer buffer, String lineSeparator, int tabNumber) { - buffer.append(lineSeparator); - dumpTab(tabNumber, buffer); - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/EnclosingMethodAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/EnclosingMethodAttribute.java deleted file mode 100644 index f764778fb..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/EnclosingMethodAttribute.java +++ /dev/null @@ -1,101 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class EnclosingMethodAttribute extends ClassFileAttribute { - - private int enclosingClassIndex; - private char[] enclosingClassName; - private int methodDescriptorIndex; - private char[] methodDescriptor; - private int methodNameIndex; - private char[] methodName; - private int methodNameAndTypeIndex; - - EnclosingMethodAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - super(classFileBytes, constantPool, offset); - int index = u2At(classFileBytes, 6, offset); - this.enclosingClassIndex = index; - ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.enclosingClassName = constantPoolEntry.getClassInfoName(); - this.methodNameAndTypeIndex = u2At(classFileBytes, 8, offset); - if (this.methodNameAndTypeIndex != 0) { - constantPoolEntry = constantPool.decodeEntry(this.methodNameAndTypeIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_NameAndType) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.methodDescriptorIndex = constantPoolEntry.getNameAndTypeInfoDescriptorIndex(); - this.methodNameIndex = constantPoolEntry.getNameAndTypeInfoNameIndex(); - constantPoolEntry = constantPool.decodeEntry(this.methodDescriptorIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.methodDescriptor = constantPoolEntry.getUtf8Value(); - constantPoolEntry = constantPool.decodeEntry(this.methodNameIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.methodName = constantPoolEntry.getUtf8Value(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IEnclosingMethodAttribute#getEnclosingClass() - */ - public char[] getEnclosingClass() { - return this.enclosingClassName; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IEnclosingMethodAttribute#getMethodDeclaringClassDescriptorIndex() - */ - public int getEnclosingClassIndex() { - return this.enclosingClassIndex; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IEnclosingMethodAttribute#getMethodDescriptor() - */ - public char[] getMethodDescriptor() { - return this.methodDescriptor; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IEnclosingMethodAttribute#getMethodDescriptorIndex() - */ - public int getMethodDescriptorIndex() { - return this.methodDescriptorIndex; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IEnclosingMethodAttribute#getMethodName() - */ - public char[] getMethodName() { - return this.methodName; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IEnclosingMethodAttribute#getMethodNameIndex() - */ - public int getMethodNameIndex() { - return this.methodNameIndex; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IEnclosingMethodAttribute#getMethodNameAndTypeIndex() - */ - public int getMethodNameAndTypeIndex() { - return this.methodNameAndTypeIndex; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ExceptionAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ExceptionAttribute.java deleted file mode 100644 index 336aae015..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ExceptionAttribute.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class ExceptionAttribute extends ClassFileAttribute { - private int exceptionsNumber; - private char[][] exceptionNames; - private int[] exceptionIndexes; - - ExceptionAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - super(classFileBytes, constantPool, offset); - this.exceptionsNumber = u2At(classFileBytes, 6, offset); - int exceptionLength = this.exceptionsNumber; - this.exceptionNames = CharOperation.NO_CHAR_CHAR; - this.exceptionIndexes = Utility.EMPTY_INT_ARRAY; - if (exceptionLength != 0) { - this.exceptionNames = new char[exceptionLength][]; - this.exceptionIndexes = new int[exceptionLength]; - } - int readOffset = 8; - ConstantPoolEntry constantPoolEntry; - for (int i = 0; i < exceptionLength; i++) { - this.exceptionIndexes[i] = u2At(classFileBytes, readOffset, offset); - constantPoolEntry = constantPool.decodeEntry(this.exceptionIndexes[i]); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.exceptionNames[i] = constantPoolEntry.getClassInfoName(); - readOffset += 2; - } - } - - /* - * @see IExceptionAttribute#getExceptionIndexes() - */ - public int[] getExceptionIndexes() { - return this.exceptionIndexes; - } - - /* - * @see IExceptionAttribute#getExceptionNames() - */ - public char[][] getExceptionNames() { - return this.exceptionNames; - } - - /* - * @see IExceptionAttribute#getExceptionsNumber() - */ - public int getExceptionsNumber() { - return this.exceptionsNumber; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ExceptionTableEntry.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ExceptionTableEntry.java deleted file mode 100644 index 6d889cd27..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ExceptionTableEntry.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class ExceptionTableEntry extends ClassFileStruct { - - private int startPC; - private int endPC; - private int handlerPC; - private int catchTypeIndex; - private char[] catchType; - - ExceptionTableEntry(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - this.startPC = u2At(classFileBytes, 0, offset); - this.endPC = u2At(classFileBytes, 2, offset); - this.handlerPC = u2At(classFileBytes, 4, offset); - this.catchTypeIndex = u2At(classFileBytes, 6, offset); - if (this.catchTypeIndex != 0) { - ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(this.catchTypeIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.catchType = constantPoolEntry.getClassInfoName(); - } - } - - /* - * @see IExceptionTableEntry#getStartPC() - */ - public int getStartPC() { - return this.startPC; - } - - /* - * @see IExceptionTableEntry#getEndPC() - */ - public int getEndPC() { - return this.endPC; - } - - /* - * @see IExceptionTableEntry#getHandlerPC() - */ - public int getHandlerPC() { - return this.handlerPC; - } - - /* - * @see IExceptionTableEntry#getCatchTypeIndex() - */ - public int getCatchTypeIndex() { - return this.catchTypeIndex; - } - - /* - * @see IExceptionTableEntry#getCatchType() - */ - public char[] getCatchType() { - return this.catchType; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/FieldInfo.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/FieldInfo.java deleted file mode 100644 index 9ebd6a86d..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/FieldInfo.java +++ /dev/null @@ -1,170 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -import java.util.Arrays; - -public class FieldInfo extends ClassFileStruct { - private int accessFlags; - private int attributeBytes; - private ClassFileAttribute[] attributes; - private int attributesCount; - private ConstantValueAttribute constantValueAttribute; - private char[] descriptor; - private int descriptorIndex; - private boolean isDeprecated; - private boolean isSynthetic; - private char[] name; - private int nameIndex; - - /* - * @param classFileBytes byte[] - * @param constantPool IConstantPool - * @param offset int - */ - public FieldInfo(byte classFileBytes[], ConstantPool constantPool, int offset) throws ClassFormatException { - final int flags = u2At(classFileBytes, 0, offset); - this.accessFlags = flags; - if ((flags & IModifierConstants.ACC_SYNTHETIC) != 0) { - this.isSynthetic = true; - } - this.nameIndex = u2At(classFileBytes, 2, offset); - ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(this.nameIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.name = constantPoolEntry.getUtf8Value(); - - this.descriptorIndex = u2At(classFileBytes, 4, offset); - constantPoolEntry = constantPool.decodeEntry(this.descriptorIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.descriptor = constantPoolEntry.getUtf8Value(); - - this.attributesCount = u2At(classFileBytes, 6, offset); - this.attributes = ClassFileAttribute.NO_ATTRIBUTES; - int readOffset = 8; - if (this.attributesCount != 0) { - this.attributes = new ClassFileAttribute[this.attributesCount]; - } - int attributesIndex = 0; - for (int i = 0; i < this.attributesCount; i++) { - constantPoolEntry = constantPool.decodeEntry(u2At(classFileBytes, readOffset, offset)); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - char[] attributeName = constantPoolEntry.getUtf8Value(); - if (Arrays.equals(attributeName, AttributeNamesConstants.DEPRECATED)) { - this.isDeprecated = true; - this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, constantPool, offset + readOffset); - } else if (Arrays.equals(attributeName, AttributeNamesConstants.SYNTHETIC)) { - this.isSynthetic = true; - this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, constantPool, offset + readOffset); - } else if (Arrays.equals(attributeName, AttributeNamesConstants.CONSTANT_VALUE)) { - this.constantValueAttribute = new ConstantValueAttribute(classFileBytes, constantPool, offset + readOffset); - this.attributes[attributesIndex++] = this.constantValueAttribute; - } else if (Arrays.equals(attributeName, AttributeNamesConstants.SIGNATURE)) { - this.attributes[attributesIndex++] = new SignatureAttribute(classFileBytes, constantPool, offset + readOffset); - } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_VISIBLE_ANNOTATIONS)) { - this.attributes[attributesIndex++] = new RuntimeVisibleAnnotationsAttribute(classFileBytes, constantPool, offset + readOffset); - } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS)) { - this.attributes[attributesIndex++] = new RuntimeInvisibleAnnotationsAttribute(classFileBytes, constantPool, offset + readOffset); - } else { - this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, constantPool, offset + readOffset); - } - readOffset += (6 + u4At(classFileBytes, readOffset + 2, offset)); - } - - this.attributeBytes = readOffset; - } - - /* - * @see IFieldInfo#getAccessFlags() - */ - public int getAccessFlags() { - return this.accessFlags; - } - - /* - * @see IFieldInfo#getAttributeCount() - */ - public int getAttributeCount() { - return this.attributesCount; - } - - /* - * @see IFieldInfo#getAttributes() - */ - public ClassFileAttribute[] getAttributes() { - return this.attributes; - } - - /* - * @see IFieldInfo#getConstantValueAttribute() - */ - public ConstantValueAttribute getConstantValueAttribute() { - return this.constantValueAttribute; - } - - /* - * @see IFieldInfo#getDescriptor() - */ - public char[] getDescriptor() { - return this.descriptor; - } - - /* - * @see IFieldInfo#getDescriptorIndex() - */ - public int getDescriptorIndex() { - return this.descriptorIndex; - } - - /* - * @see IFieldInfo#getName() - */ - public char[] getName() { - return this.name; - } - - /* - * @see IFieldInfo#getNameIndex() - */ - public int getNameIndex() { - return this.nameIndex; - } - - /* - * @see IFieldInfo#hasConstantValueAttribute() - */ - public boolean hasConstantValueAttribute() { - return this.constantValueAttribute != null; - } - - /* - * @see IFieldInfo#isDeprecated() - */ - public boolean isDeprecated() { - return this.isDeprecated; - } - - /* - * @see IFieldInfo#isSynthetic() - */ - public boolean isSynthetic() { - return this.isSynthetic; - } - - int sizeInBytes() { - return this.attributeBytes; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/IModifierConstants.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/IModifierConstants.java deleted file mode 100644 index 17607b11e..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/IModifierConstants.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public interface IModifierConstants { - - int ACC_PUBLIC = 0x0001; - int ACC_PRIVATE = 0x0002; - int ACC_PROTECTED = 0x0004; - int ACC_STATIC = 0x0008; - int ACC_FINAL = 0x0010; - int ACC_SUPER = 0x0020; - int ACC_SYNCHRONIZED = 0x0020; - int ACC_VOLATILE = 0x0040; - - /** - * Indicates a bridge method (added in J2SE 1.5). - * @since 3.0 - */ - int ACC_BRIDGE = 0x0040; - int ACC_TRANSIENT = 0x0080; - - /** - * Indicates a variable arity method (added in J2SE 1.5). - * @since 3.0 - */ - int ACC_VARARGS = 0x0080; - int ACC_NATIVE = 0x0100; - int ACC_INTERFACE = 0x0200; - int ACC_ABSTRACT = 0x0400; - int ACC_STRICT = 0x0800; - /** - * Indicates a synthetic member. - * @since 3.0 - */ - int ACC_SYNTHETIC = 0x1000; - - /** - * Indicates an annotation (added in J2SE 1.5). - * @since 3.0 - */ - int ACC_ANNOTATION = 0x2000; - - /** - * Indicates an enum (added in J2SE 1.5). - * @since 3.0 - */ - int ACC_ENUM = 0x4000; - - /** - * Configurable option value: {@value}. - * @category OptionValue - */ - public static final String VERSION_1_1 = "1.1"; //$NON-NLS-1$ - /** - * Configurable option value: {@value}. - * @category OptionValue - */ - public static final String VERSION_1_2 = "1.2"; //$NON-NLS-1$ - /** - * Configurable option value: {@value}. - * @since 2.0 - * @category OptionValue - */ - public static final String VERSION_1_3 = "1.3"; //$NON-NLS-1$ - /** - * Configurable option value: {@value}. - * @since 2.0 - * @category OptionValue - */ - public static final String VERSION_1_4 = "1.4"; //$NON-NLS-1$ - /** - * Configurable option value: {@value}. - * @since 3.0 - * @category OptionValue - */ - public static final String VERSION_1_5 = "1.5"; //$NON-NLS-1$ - /** - * Configurable option value: {@value}. - * @since 3.2 - * @category OptionValue - */ - public static final String VERSION_1_6 = "1.6"; //$NON-NLS-1$ - /** - * Configurable option value: {@value}. - * @since 3.3 - * @category OptionValue - */ - public static final String VERSION_1_7 = "1.7"; //$NON-NLS-1$ - /** - * Configurable option value: {@value}. - * @since 3.4 - * @category OptionValue - */ - public static final String VERSION_CLDC_1_1 = "cldc1.1"; //$NON-NLS-1$ -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/IOpcodeMnemonics.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/IOpcodeMnemonics.java deleted file mode 100644 index 720591ed6..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/IOpcodeMnemonics.java +++ /dev/null @@ -1,220 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public interface IOpcodeMnemonics { - - int NOP = 0x00; - int ACONST_NULL = 0x01; - int ICONST_M1 = 0x02; - int ICONST_0 = 0x03; - int ICONST_1 = 0x04; - int ICONST_2 = 0x05; - int ICONST_3 = 0x06; - int ICONST_4 = 0x07; - int ICONST_5 = 0x08; - int LCONST_0 = 0x09; - int LCONST_1 = 0x0A; - int FCONST_0 = 0x0B; - int FCONST_1 = 0x0C; - int FCONST_2 = 0x0D; - int DCONST_0 = 0x0E; - int DCONST_1 = 0x0F; - int BIPUSH = 0x10; - int SIPUSH = 0x11; - int LDC = 0x12; - int LDC_W = 0x13; - int LDC2_W = 0x14; - int ILOAD = 0x15; - int LLOAD = 0x16; - int FLOAD = 0x17; - int DLOAD = 0x18; - int ALOAD = 0x19; - int ILOAD_0 = 0x1A; - int ILOAD_1 = 0x1B; - int ILOAD_2 = 0x1C; - int ILOAD_3 = 0x1D; - int LLOAD_0 = 0x1E; - int LLOAD_1 = 0x1F; - int LLOAD_2 = 0x20; - int LLOAD_3 = 0x21; - int FLOAD_0 = 0x22; - int FLOAD_1 = 0x23; - int FLOAD_2 = 0x24; - int FLOAD_3 = 0x25; - int DLOAD_0 = 0x26; - int DLOAD_1 = 0x27; - int DLOAD_2 = 0x28; - int DLOAD_3 = 0x29; - int ALOAD_0 = 0x2A; - int ALOAD_1 = 0x2B; - int ALOAD_2 = 0x2C; - int ALOAD_3 = 0x2D; - int IALOAD = 0x2E; - int LALOAD = 0x2F; - int FALOAD = 0x30; - int DALOAD = 0x31; - int AALOAD = 0x32; - int BALOAD = 0x33; - int CALOAD = 0x34; - int SALOAD = 0x35; - int ISTORE = 0x36; - int LSTORE = 0x37; - int FSTORE = 0x38; - int DSTORE = 0x39; - int ASTORE = 0x3A; - int ISTORE_0 = 0x3B; - int ISTORE_1 = 0x3C; - int ISTORE_2 = 0x3D; - int ISTORE_3 = 0x3E; - int LSTORE_0 = 0x3F; - int LSTORE_1 = 0x40; - int LSTORE_2 = 0x41; - int LSTORE_3 = 0x42; - int FSTORE_0 = 0x43; - int FSTORE_1 = 0x44; - int FSTORE_2 = 0x45; - int FSTORE_3 = 0x46; - int DSTORE_0 = 0x47; - int DSTORE_1 = 0x48; - int DSTORE_2 = 0x49; - int DSTORE_3 = 0x4A; - int ASTORE_0 = 0x4B; - int ASTORE_1 = 0x4C; - int ASTORE_2 = 0x4D; - int ASTORE_3 = 0x4E; - int IASTORE = 0x4F; - int LASTORE = 0x50; - int FASTORE = 0x51; - int DASTORE = 0x52; - int AASTORE = 0x53; - int BASTORE = 0x54; - int CASTORE = 0x55; - int SASTORE = 0x56; - int POP = 0x57; - int POP2 = 0x58; - int DUP = 0x59; - int DUP_X1 = 0x5A; - int DUP_X2 = 0x5B; - int DUP2 = 0x5C; - int DUP2_X1 = 0x5D; - int DUP2_X2 = 0x5E; - int SWAP = 0x5F; - int IADD = 0x60; - int LADD = 0x61; - int FADD = 0x62; - int DADD = 0x63; - int ISUB = 0x64; - int LSUB = 0x65; - int FSUB = 0x66; - int DSUB = 0x67; - int IMUL = 0x68; - int LMUL = 0x69; - int FMUL = 0x6A; - int DMUL = 0x6B; - int IDIV = 0x6C; - int LDIV = 0x6D; - int FDIV = 0x6E; - int DDIV = 0x6F; - int IREM = 0x70; - int LREM = 0x71; - int FREM = 0x72; - int DREM = 0x73; - int INEG = 0x74; - int LNEG = 0x75; - int FNEG = 0x76; - int DNEG = 0x77; - int ISHL = 0x78; - int LSHL = 0x79; - int ISHR = 0x7A; - int LSHR = 0x7B; - int IUSHR = 0x7C; - int LUSHR = 0x7D; - int IAND = 0x7E; - int LAND = 0x7F; - int IOR = 0x80; - int LOR = 0x81; - int IXOR = 0x82; - int LXOR = 0x83; - int IINC = 0x84; - int I2L = 0x85; - int I2F = 0x86; - int I2D = 0x87; - int L2I = 0x88; - int L2F = 0x89; - int L2D = 0x8A; - int F2I = 0x8B; - int F2L = 0x8C; - int F2D = 0x8D; - int D2I = 0x8E; - int D2L = 0x8F; - int D2F = 0x90; - int I2B = 0x91; - int I2C = 0x92; - int I2S = 0x93; - int LCMP = 0x94; - int FCMPL = 0x95; - int FCMPG = 0x96; - int DCMPL = 0x97; - int DCMPG = 0x98; - int IFEQ = 0x99; - int IFNE = 0x9A; - int IFLT = 0x9B; - int IFGE = 0x9C; - int IFGT = 0x9D; - int IFLE = 0x9E; - int IF_ICMPEQ = 0x9F; - int IF_ICMPNE = 0xA0; - int IF_ICMPLT = 0xA1; - int IF_ICMPGE = 0xA2; - int IF_ICMPGT = 0xA3; - int IF_ICMPLE = 0xA4; - int IF_ACMPEQ = 0xA5; - int IF_ACMPNE = 0xA6; - int GOTO = 0xA7; - int JSR = 0xA8; - int RET = 0xA9; - int TABLESWITCH = 0xAA; - int LOOKUPSWITCH = 0xAB; - int IRETURN = 0xAC; - int LRETURN = 0xAD; - int FRETURN = 0xAE; - int DRETURN = 0xAF; - int ARETURN = 0xB0; - int RETURN = 0xB1; - int GETSTATIC = 0xB2; - int PUTSTATIC = 0xB3; - int GETFIELD = 0xB4; - int PUTFIELD = 0xB5; - int INVOKEVIRTUAL = 0xB6; - int INVOKESPECIAL = 0xB7; - int INVOKESTATIC = 0xB8; - int INVOKEINTERFACE = 0xB9; - int NEW = 0xBB; - int NEWARRAY = 0xBC; - int ANEWARRAY = 0xBD; - int ARRAYLENGTH = 0xBE; - int ATHROW = 0xBF; - int CHECKCAST = 0xC0; - int INSTANCEOF = 0xC1; - int MONITORENTER = 0xC2; - int MONITOREXIT = 0xC3; - int WIDE = 0xC4; - int MULTIANEWARRAY = 0xC5; - int IFNULL = 0xC6; - int IFNONNULL = 0xC7; - int GOTO_W = 0xC8; - int JSR_W = 0xC9; - - int BREAKPOINT = 0xCA; - int IMPDEP1 = 0xFE; - int IMPDEP2 = 0xFF; -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/InnerClassesAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/InnerClassesAttribute.java deleted file mode 100644 index 4a316098b..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/InnerClassesAttribute.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class InnerClassesAttribute extends ClassFileAttribute { - private static final InnerClassesAttributeEntry[] NO_ENTRIES = new InnerClassesAttributeEntry[0]; - - private int numberOfClasses; - private InnerClassesAttributeEntry[] entries; - - /** - * Constructor for InnerClassesAttribute. - * @param classFileBytes - * @param constantPool - * @param offset - * @throws ClassFormatException - */ - public InnerClassesAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - super(classFileBytes, constantPool, offset); - this.numberOfClasses = u2At(classFileBytes, 6, offset); - final int length = this.numberOfClasses; - if (length != 0) { - int readOffset = 8; - this.entries = new InnerClassesAttributeEntry[length]; - for (int i = 0; i < length; i++) { - this.entries[i] = new InnerClassesAttributeEntry(classFileBytes, constantPool, offset + readOffset); - readOffset += 8; - } - } else { - this.entries = NO_ENTRIES; - } - } - - /* - * @see IInnerClassesAttribute#getInnerClassAttributesEntries() - */ - public InnerClassesAttributeEntry[] getInnerClassAttributesEntries() { - return this.entries; - } - - /* - * @see IInnerClassesAttribute#getNumberOfClasses() - */ - public int getNumberOfClasses() { - return this.numberOfClasses; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/InnerClassesAttributeEntry.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/InnerClassesAttributeEntry.java deleted file mode 100644 index 34b267fb2..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/InnerClassesAttributeEntry.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class InnerClassesAttributeEntry extends ClassFileStruct { - - private int innerClassNameIndex; - private int outerClassNameIndex; - private int innerNameIndex; - private char[] innerClassName; - private char[] outerClassName; - private char[] innerName; - private int accessFlags; - - public InnerClassesAttributeEntry(byte classFileBytes[], ConstantPool constantPool, int offset) throws ClassFormatException { - this.innerClassNameIndex = u2At(classFileBytes, 0, offset); - this.outerClassNameIndex = u2At(classFileBytes, 2, offset); - this.innerNameIndex = u2At(classFileBytes, 4, offset); - this.accessFlags = u2At(classFileBytes, 6, offset); - ConstantPoolEntry constantPoolEntry; - if (this.innerClassNameIndex != 0) { - constantPoolEntry = constantPool.decodeEntry(this.innerClassNameIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.innerClassName = constantPoolEntry.getClassInfoName(); - } - if (this.outerClassNameIndex != 0) { - constantPoolEntry = constantPool.decodeEntry(this.outerClassNameIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.outerClassName = constantPoolEntry.getClassInfoName(); - } - if (this.innerNameIndex != 0) { - constantPoolEntry = constantPool.decodeEntry(this.innerNameIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.innerName = constantPoolEntry.getUtf8Value(); - } - } - - /* - * @see IInnerClassesAttributeEntry#getAccessFlags() - */ - public int getAccessFlags() { - return this.accessFlags; - } - - /* - * @see IInnerClassesAttributeEntry#getInnerClassName() - */ - public char[] getInnerClassName() { - return this.innerClassName; - } - - /* - * @see IInnerClassesAttributeEntry#getInnerClassNameIndex() - */ - public int getInnerClassNameIndex() { - return this.innerClassNameIndex; - } - - /* - * @see IInnerClassesAttributeEntry#getInnerName() - */ - public char[] getInnerName() { - return this.innerName; - } - - /* - * @see IInnerClassesAttributeEntry#getInnerNameIndex() - */ - public int getInnerNameIndex() { - return this.innerNameIndex; - } - - /* - * @see IInnerClassesAttributeEntry#getOuterClassName() - */ - public char[] getOuterClassName() { - return this.outerClassName; - } - - /* - * @see IInnerClassesAttributeEntry#getOuterClassNameIndex() - */ - public int getOuterClassNameIndex() { - return this.outerClassNameIndex; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/JarComparator.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/JarComparator.java index 5dbb891bc..7d2b7de43 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/JarComparator.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/JarComparator.java @@ -10,13 +10,19 @@ *******************************************************************************/ package org.eclipse.equinox.p2.internal.repository.comparator; +import org.eclipse.equinox.p2.internal.repository.comparator.java.*; + +import org.eclipse.equinox.p2.repository.tools.comparator.IArtifactComparator; + import java.io.*; import java.util.*; +import java.util.Map.Entry; import java.util.jar.*; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; import org.eclipse.osgi.util.NLS; public class JarComparator implements IArtifactComparator { @@ -80,8 +86,8 @@ public class JarComparator implements IArtifactComparator { if (firstFileSize != secondFileSize) { return newErrorStatus(NLS.bind(Messages.differentNumberOfEntries, new String[] {descriptorString, sourceLocation, Integer.toString(firstFileSize), destinationLocation, Integer.toString(secondFileSize)})); } - for (Enumeration enumeration = firstFile.entries(); enumeration.hasMoreElements();) { - ZipEntry entry = (ZipEntry) enumeration.nextElement(); + for (Enumeration enumeration = firstFile.entries(); enumeration.hasMoreElements();) { + ZipEntry entry = enumeration.nextElement(); String entryName = entry.getName(); final ZipEntry entry2 = secondFile.getEntry(entryName); if (!entry.isDirectory() && entry2 != null) { @@ -145,8 +151,7 @@ public class JarComparator implements IArtifactComparator { Attributes attributes2 = manifest2.getMainAttributes(); if (attributes.size() != attributes2.size()) return false; - for (Iterator iterator = attributes.entrySet().iterator(); iterator.hasNext();) { - Map.Entry entry = (Map.Entry) iterator.next(); + for (Entry entry : attributes.entrySet()) { Object value2 = attributes2.get(entry.getKey()); if (value2 == null) { return false; @@ -192,7 +197,7 @@ public class JarComparator implements IArtifactComparator { return false; props1.keys(); - for (Iterator iterator = props1.keySet().iterator(); iterator.hasNext();) { + for (Iterator iterator = props1.keySet().iterator(); iterator.hasNext();) { String key = (String) iterator.next(); if (!props2.containsKey(key)) return false; diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/MD5ArtifactComparator.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/MD5ArtifactComparator.java new file mode 100644 index 000000000..754aeb22e --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/MD5ArtifactComparator.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.p2.internal.repository.comparator; + +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.artifact.repository.Activator; +import org.eclipse.equinox.p2.internal.repository.tools.Messages; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.tools.comparator.IArtifactComparator; +import org.eclipse.osgi.util.NLS; + +public class MD5ArtifactComparator implements IArtifactComparator { + + public static String MD5_COMPARATOR_ID = "org.eclipse.equinox.artifact.md5.comparator"; //$NON-NLS-1$ + + public IStatus compare(IArtifactRepository source, IArtifactDescriptor sourceDescriptor, IArtifactRepository destination, IArtifactDescriptor destDescriptor) { + String sourceMD5 = sourceDescriptor.getProperty(IArtifactDescriptor.DOWNLOAD_MD5); + String destMD5 = destDescriptor.getProperty(IArtifactDescriptor.DOWNLOAD_MD5); + + if (sourceMD5 == null && destMD5 == null) + return new Status(IStatus.INFO, Activator.ID, NLS.bind(Messages.info_noMD5Infomation, sourceDescriptor)); + + if (sourceMD5 == null) + return new Status(IStatus.INFO, Activator.ID, NLS.bind(Messages.info_noMD5InRepository, source, sourceDescriptor)); + + if (destMD5 == null) + return new Status(IStatus.INFO, Activator.ID, NLS.bind(Messages.info_noMD5InRepository, destination, destDescriptor)); + + if (sourceMD5.equals(destMD5)) + return Status.OK_STATUS; + + return new Status(IStatus.WARNING, Activator.ID, NLS.bind(Messages.warning_differentMD5, new Object[] {URIUtil.toUnencodedString(sourceDescriptor.getRepository().getLocation()), URIUtil.toUnencodedString(destDescriptor.getRepository().getLocation()), sourceDescriptor})); + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Messages.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Messages.java deleted file mode 100644 index 3edd78f26..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Messages.java +++ /dev/null @@ -1,107 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -import org.eclipse.osgi.util.NLS; - -public class Messages extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.equinox.p2.internal.repository.comparator.messages"; //$NON-NLS-1$ - public static String differentNumberOfEntries; - public static String differentEntry; - public static String missingEntry; - public static String ioexception; - public static String disassembler_opentypedeclaration; - public static String disassembler_closetypedeclaration; - public static String disassembler_endofmethodheader; - public static String disassembler_begincommentline; - public static String disassembler_fieldhasconstant; - public static String disassembler_endoffieldheader; - public static String disassembler_sourceattributeheader; - public static String disassembler_enclosingmethodheader; - public static String disassembler_exceptiontableheader; - public static String disassembler_innerattributesheader; - public static String disassembler_inner_class_info_name; - public static String disassembler_outer_class_info_name; - public static String disassembler_inner_name; - public static String disassembler_inner_accessflags; - public static String disassembler_signatureattributeheader; - public static String disassembler_indentation; - public static String disassembler_space; - public static String disassembler_comma; - public static String disassembler_openinnerclassentry; - public static String disassembler_closeinnerclassentry; - public static String disassembler_deprecated; - public static String disassembler_annotationdefaultheader; - public static String disassembler_annotationdefaultvalue; - public static String disassembler_annotationenumvalue; - public static String disassembler_annotationclassvalue; - public static String disassembler_annotationannotationvalue; - public static String disassembler_annotationarrayvaluestart; - public static String disassembler_annotationarrayvalueend; - public static String disassembler_annotationentrystart; - public static String disassembler_annotationentryend; - public static String disassembler_annotationcomponent; - public static String disassembler_runtimevisibleannotationsattributeheader; - public static String disassembler_runtimeinvisibleannotationsattributeheader; - public static String disassembler_runtimevisibleparameterannotationsattributeheader; - public static String disassembler_runtimeinvisibleparameterannotationsattributeheader; - public static String disassembler_parameterannotationentrystart; - public static String classfileformat_versiondetails; - public static String classfileformat_methoddescriptor; - public static String classfileformat_fieldddescriptor; - public static String classfileformat_stacksAndLocals; - public static String classfileformat_superflagisnotset; - public static String classfileformat_superflagisset; - public static String classfileformat_clinitname; - public static String classformat_classformatexception; - public static String classformat_anewarray; - public static String classformat_checkcast; - public static String classformat_instanceof; - public static String classformat_ldc_w_class; - public static String classformat_ldc_w_float; - public static String classformat_ldc_w_integer; - public static String classformat_ldc_w_string; - public static String classformat_ldc2_w_long; - public static String classformat_ldc2_w_double; - public static String classformat_multianewarray; - public static String classformat_new; - public static String classformat_iinc; - public static String classformat_invokespecial; - public static String classformat_invokeinterface; - public static String classformat_invokestatic; - public static String classformat_invokevirtual; - public static String classformat_getfield; - public static String classformat_getstatic; - public static String classformat_putstatic; - public static String classformat_putfield; - public static String classformat_newarray_boolean; - public static String classformat_newarray_char; - public static String classformat_newarray_float; - public static String classformat_newarray_double; - public static String classformat_newarray_byte; - public static String classformat_newarray_short; - public static String classformat_newarray_int; - public static String classformat_newarray_long; - public static String classformat_store; - public static String classformat_load; - public static String classfileformat_anyexceptionhandler; - public static String classfileformat_exceptiontableentry; - public static String classfileformat_versionUnknown; - - static { - // initialize resource bundle - NLS.initializeMessages(BUNDLE_NAME, Messages.class); - } - - private Messages() { - // prevent instantiation - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/MethodInfo.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/MethodInfo.java deleted file mode 100644 index c7789475a..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/MethodInfo.java +++ /dev/null @@ -1,213 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -import java.util.Arrays; - -public class MethodInfo extends ClassFileStruct { - private int accessFlags; - private int attributeBytes; - private ClassFileAttribute[] attributes; - private int attributesCount; - private CodeAttribute codeAttribute; - private char[] descriptor; - private int descriptorIndex; - private ExceptionAttribute exceptionAttribute; - private boolean isDeprecated; - private boolean isSynthetic; - private char[] name; - private int nameIndex; - - /* - * @param classFileBytes byte[] - * @param constantPool IConstantPool - * @param offset int - * @param decodingFlags int - */ - public MethodInfo(byte classFileBytes[], ConstantPool constantPool, int offset, int decodingFlags) throws ClassFormatException { - - boolean no_code_attribute = (decodingFlags & ClassFileReader.METHOD_BODIES) == 0; - final int flags = u2At(classFileBytes, 0, offset); - this.accessFlags = flags; - if ((flags & IModifierConstants.ACC_SYNTHETIC) != 0) { - this.isSynthetic = true; - } - - this.nameIndex = u2At(classFileBytes, 2, offset); - ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(this.nameIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.name = constantPoolEntry.getUtf8Value(); - - this.descriptorIndex = u2At(classFileBytes, 4, offset); - constantPoolEntry = constantPool.decodeEntry(this.descriptorIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.descriptor = constantPoolEntry.getUtf8Value(); - - this.attributesCount = u2At(classFileBytes, 6, offset); - this.attributes = ClassFileAttribute.NO_ATTRIBUTES; - if (this.attributesCount != 0) { - if (no_code_attribute && !isAbstract() && !isNative()) { - if (this.attributesCount != 1) { - this.attributes = new ClassFileAttribute[this.attributesCount - 1]; - } - } else { - this.attributes = new ClassFileAttribute[this.attributesCount]; - } - } - int attributesIndex = 0; - int readOffset = 8; - for (int i = 0; i < this.attributesCount; i++) { - constantPoolEntry = constantPool.decodeEntry(u2At(classFileBytes, readOffset, offset)); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - char[] attributeName = constantPoolEntry.getUtf8Value(); - if (Arrays.equals(attributeName, AttributeNamesConstants.DEPRECATED)) { - this.isDeprecated = true; - this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, constantPool, offset + readOffset); - } else if (Arrays.equals(attributeName, AttributeNamesConstants.SYNTHETIC)) { - this.isSynthetic = true; - this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, constantPool, offset + readOffset); - } else if (Arrays.equals(attributeName, AttributeNamesConstants.CODE)) { - if (!no_code_attribute) { - this.codeAttribute = new CodeAttribute(classFileBytes, constantPool, offset + readOffset); - this.attributes[attributesIndex++] = this.codeAttribute; - } - } else if (Arrays.equals(attributeName, AttributeNamesConstants.EXCEPTIONS)) { - this.exceptionAttribute = new ExceptionAttribute(classFileBytes, constantPool, offset + readOffset); - this.attributes[attributesIndex++] = this.exceptionAttribute; - } else if (Arrays.equals(attributeName, AttributeNamesConstants.SIGNATURE)) { - this.attributes[attributesIndex++] = new SignatureAttribute(classFileBytes, constantPool, offset + readOffset); - } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_VISIBLE_ANNOTATIONS)) { - this.attributes[attributesIndex++] = new RuntimeVisibleAnnotationsAttribute(classFileBytes, constantPool, offset + readOffset); - } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS)) { - this.attributes[attributesIndex++] = new RuntimeInvisibleAnnotationsAttribute(classFileBytes, constantPool, offset + readOffset); - } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS)) { - this.attributes[attributesIndex++] = new RuntimeVisibleParameterAnnotationsAttribute(classFileBytes, constantPool, offset + readOffset); - } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS)) { - this.attributes[attributesIndex++] = new RuntimeInvisibleParameterAnnotationsAttribute(classFileBytes, constantPool, offset + readOffset); - } else if (Arrays.equals(attributeName, AttributeNamesConstants.ANNOTATION_DEFAULT)) { - this.attributes[attributesIndex++] = new AnnotationDefaultAttribute(classFileBytes, constantPool, offset + readOffset); - } else { - this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, constantPool, offset + readOffset); - } - readOffset += (6 + u4At(classFileBytes, readOffset + 2, offset)); - } - this.attributeBytes = readOffset; - } - - /* - * @see IMethodInfo#getAccessFlags() - */ - public int getAccessFlags() { - return this.accessFlags; - } - - /* - * @see IMethodInfo#getAttributeCount() - */ - public int getAttributeCount() { - return this.attributesCount; - } - - /* - * @see IMethodInfo#getAttributes() - */ - public ClassFileAttribute[] getAttributes() { - return this.attributes; - } - - /* - * @see IMethodInfo#getCodeAttribute() - */ - public CodeAttribute getCodeAttribute() { - return this.codeAttribute; - } - - /* - * @see IMethodInfo#getDescriptor() - */ - public char[] getDescriptor() { - return this.descriptor; - } - - /* - * @see IMethodInfo#getDescriptorIndex() - */ - public int getDescriptorIndex() { - return this.descriptorIndex; - } - - /* - * @see IMethodInfo#getExceptionAttribute() - */ - public ExceptionAttribute getExceptionAttribute() { - return this.exceptionAttribute; - } - - /* - * @see IMethodInfo#getName() - */ - public char[] getName() { - return this.name; - } - - /* - * @see IMethodInfo#getNameIndex() - */ - public int getNameIndex() { - return this.nameIndex; - } - - private boolean isAbstract() { - return (this.accessFlags & IModifierConstants.ACC_ABSTRACT) != 0; - } - - /* - * @see IMethodInfo#isClinit() - */ - public boolean isClinit() { - return this.name[0] == '<' && this.name.length == 8; // Can only match - } - - /* - * @see IMethodInfo#isConstructor() - */ - public boolean isConstructor() { - return this.name[0] == '<' && this.name.length == 6; // Can only match - } - - /* - * @see IMethodInfo#isDeprecated() - */ - public boolean isDeprecated() { - return this.isDeprecated; - } - - private boolean isNative() { - return (this.accessFlags & IModifierConstants.ACC_NATIVE) != 0; - } - - /* - * @see IMethodInfo#isSynthetic() - */ - public boolean isSynthetic() { - return this.isSynthetic; - } - - int sizeInBytes() { - return this.attributeBytes; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/OpcodeStringValues.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/OpcodeStringValues.java deleted file mode 100644 index 76f80e9b6..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/OpcodeStringValues.java +++ /dev/null @@ -1,222 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class OpcodeStringValues implements IOpcodeMnemonics { - - public static final String[] BYTECODE_NAMES = new String[256]; - static { - BYTECODE_NAMES[NOP] = "nop"; //$NON-NLS-1$ - BYTECODE_NAMES[ACONST_NULL] = "aconst_null"; //$NON-NLS-1$ - BYTECODE_NAMES[ICONST_M1] = "iconst_m1"; //$NON-NLS-1$ - BYTECODE_NAMES[ICONST_0] = "iconst_0"; //$NON-NLS-1$ - BYTECODE_NAMES[ICONST_1] = "iconst_1"; //$NON-NLS-1$ - BYTECODE_NAMES[ICONST_2] = "iconst_2"; //$NON-NLS-1$ - BYTECODE_NAMES[ICONST_3] = "iconst_3"; //$NON-NLS-1$ - BYTECODE_NAMES[ICONST_4] = "iconst_4"; //$NON-NLS-1$ - BYTECODE_NAMES[ICONST_5] = "iconst_5"; //$NON-NLS-1$ - BYTECODE_NAMES[LCONST_0] = "lconst_0"; //$NON-NLS-1$ - BYTECODE_NAMES[LCONST_1] = "lconst_1"; //$NON-NLS-1$ - BYTECODE_NAMES[FCONST_0] = "fconst_0"; //$NON-NLS-1$ - BYTECODE_NAMES[FCONST_1] = "fconst_1"; //$NON-NLS-1$ - BYTECODE_NAMES[FCONST_2] = "fconst_2"; //$NON-NLS-1$ - BYTECODE_NAMES[DCONST_0] = "dconst_0"; //$NON-NLS-1$ - BYTECODE_NAMES[DCONST_1] = "dconst_1"; //$NON-NLS-1$ - BYTECODE_NAMES[BIPUSH] = "bipush"; //$NON-NLS-1$ - BYTECODE_NAMES[SIPUSH] = "sipush"; //$NON-NLS-1$ - BYTECODE_NAMES[LDC] = "ldc"; //$NON-NLS-1$ - BYTECODE_NAMES[LDC_W] = "ldc_w"; //$NON-NLS-1$ - BYTECODE_NAMES[LDC2_W] = "ldc2_w"; //$NON-NLS-1$ - BYTECODE_NAMES[ILOAD] = "iload"; //$NON-NLS-1$ - BYTECODE_NAMES[LLOAD] = "lload"; //$NON-NLS-1$ - BYTECODE_NAMES[FLOAD] = "fload"; //$NON-NLS-1$ - BYTECODE_NAMES[DLOAD] = "dload"; //$NON-NLS-1$ - BYTECODE_NAMES[ALOAD] = "aload"; //$NON-NLS-1$ - BYTECODE_NAMES[ILOAD_0] = "iload_0"; //$NON-NLS-1$ - BYTECODE_NAMES[ILOAD_1] = "iload_1"; //$NON-NLS-1$ - BYTECODE_NAMES[ILOAD_2] = "iload_2"; //$NON-NLS-1$ - BYTECODE_NAMES[ILOAD_3] = "iload_3"; //$NON-NLS-1$ - BYTECODE_NAMES[LLOAD_0] = "lload_0"; //$NON-NLS-1$ - BYTECODE_NAMES[LLOAD_1] = "lload_1"; //$NON-NLS-1$ - BYTECODE_NAMES[LLOAD_2] = "lload_2"; //$NON-NLS-1$ - BYTECODE_NAMES[LLOAD_3] = "lload_3"; //$NON-NLS-1$ - BYTECODE_NAMES[FLOAD_0] = "fload_0"; //$NON-NLS-1$ - BYTECODE_NAMES[FLOAD_1] = "fload_1"; //$NON-NLS-1$ - BYTECODE_NAMES[FLOAD_2] = "fload_2"; //$NON-NLS-1$ - BYTECODE_NAMES[FLOAD_3] = "fload_3"; //$NON-NLS-1$ - BYTECODE_NAMES[DLOAD_0] = "dload_0"; //$NON-NLS-1$ - BYTECODE_NAMES[DLOAD_1] = "dload_1"; //$NON-NLS-1$ - BYTECODE_NAMES[DLOAD_2] = "dload_2"; //$NON-NLS-1$ - BYTECODE_NAMES[DLOAD_3] = "dload_3"; //$NON-NLS-1$ - BYTECODE_NAMES[ALOAD_0] = "aload_0"; //$NON-NLS-1$ - BYTECODE_NAMES[ALOAD_1] = "aload_1"; //$NON-NLS-1$ - BYTECODE_NAMES[ALOAD_2] = "aload_2"; //$NON-NLS-1$ - BYTECODE_NAMES[ALOAD_3] = "aload_3"; //$NON-NLS-1$ - BYTECODE_NAMES[IALOAD] = "iaload"; //$NON-NLS-1$ - BYTECODE_NAMES[LALOAD] = "laload"; //$NON-NLS-1$ - BYTECODE_NAMES[FALOAD] = "faload"; //$NON-NLS-1$ - BYTECODE_NAMES[DALOAD] = "daload"; //$NON-NLS-1$ - BYTECODE_NAMES[AALOAD] = "aaload"; //$NON-NLS-1$ - BYTECODE_NAMES[BALOAD] = "baload"; //$NON-NLS-1$ - BYTECODE_NAMES[CALOAD] = "caload"; //$NON-NLS-1$ - BYTECODE_NAMES[SALOAD] = "saload"; //$NON-NLS-1$ - BYTECODE_NAMES[ISTORE] = "istore"; //$NON-NLS-1$ - BYTECODE_NAMES[LSTORE] = "lstore"; //$NON-NLS-1$ - BYTECODE_NAMES[FSTORE] = "fstore"; //$NON-NLS-1$ - BYTECODE_NAMES[DSTORE] = "dstore"; //$NON-NLS-1$ - BYTECODE_NAMES[ASTORE] = "astore"; //$NON-NLS-1$ - BYTECODE_NAMES[ISTORE_0] = "istore_0"; //$NON-NLS-1$ - BYTECODE_NAMES[ISTORE_1] = "istore_1"; //$NON-NLS-1$ - BYTECODE_NAMES[ISTORE_2] = "istore_2"; //$NON-NLS-1$ - BYTECODE_NAMES[ISTORE_3] = "istore_3"; //$NON-NLS-1$ - BYTECODE_NAMES[LSTORE_0] = "lstore_0"; //$NON-NLS-1$ - BYTECODE_NAMES[LSTORE_1] = "lstore_1"; //$NON-NLS-1$ - BYTECODE_NAMES[LSTORE_2] = "lstore_2"; //$NON-NLS-1$ - BYTECODE_NAMES[LSTORE_3] = "lstore_3"; //$NON-NLS-1$ - BYTECODE_NAMES[FSTORE_0] = "fstore_0"; //$NON-NLS-1$ - BYTECODE_NAMES[FSTORE_1] = "fstore_1"; //$NON-NLS-1$ - BYTECODE_NAMES[FSTORE_2] = "fstore_2"; //$NON-NLS-1$ - BYTECODE_NAMES[FSTORE_3] = "fstore_3"; //$NON-NLS-1$ - BYTECODE_NAMES[DSTORE_0] = "dstore_0"; //$NON-NLS-1$ - BYTECODE_NAMES[DSTORE_1] = "dstore_1"; //$NON-NLS-1$ - BYTECODE_NAMES[DSTORE_2] = "dstore_2"; //$NON-NLS-1$ - BYTECODE_NAMES[DSTORE_3] = "dstore_3"; //$NON-NLS-1$ - BYTECODE_NAMES[ASTORE_0] = "astore_0"; //$NON-NLS-1$ - BYTECODE_NAMES[ASTORE_1] = "astore_1"; //$NON-NLS-1$ - BYTECODE_NAMES[ASTORE_2] = "astore_2"; //$NON-NLS-1$ - BYTECODE_NAMES[ASTORE_3] = "astore_3"; //$NON-NLS-1$ - BYTECODE_NAMES[IASTORE] = "iastore"; //$NON-NLS-1$ - BYTECODE_NAMES[LASTORE] = "lastore"; //$NON-NLS-1$ - BYTECODE_NAMES[FASTORE] = "fastore"; //$NON-NLS-1$ - BYTECODE_NAMES[DASTORE] = "dastore"; //$NON-NLS-1$ - BYTECODE_NAMES[AASTORE] = "aastore"; //$NON-NLS-1$ - BYTECODE_NAMES[BASTORE] = "bastore"; //$NON-NLS-1$ - BYTECODE_NAMES[CASTORE] = "castore"; //$NON-NLS-1$ - BYTECODE_NAMES[SASTORE] = "sastore"; //$NON-NLS-1$ - BYTECODE_NAMES[POP] = "pop"; //$NON-NLS-1$ - BYTECODE_NAMES[POP2] = "pop2"; //$NON-NLS-1$ - BYTECODE_NAMES[DUP] = "dup"; //$NON-NLS-1$ - BYTECODE_NAMES[DUP_X1] = "dup_x1"; //$NON-NLS-1$ - BYTECODE_NAMES[DUP_X2] = "dup_x2"; //$NON-NLS-1$ - BYTECODE_NAMES[DUP2] = "dup2"; //$NON-NLS-1$ - BYTECODE_NAMES[DUP2_X1] = "dup2_x1"; //$NON-NLS-1$ - BYTECODE_NAMES[DUP2_X2] = "dup2_x2"; //$NON-NLS-1$ - BYTECODE_NAMES[SWAP] = "swap"; //$NON-NLS-1$ - BYTECODE_NAMES[IADD] = "iadd"; //$NON-NLS-1$ - BYTECODE_NAMES[LADD] = "ladd"; //$NON-NLS-1$ - BYTECODE_NAMES[FADD] = "fadd"; //$NON-NLS-1$ - BYTECODE_NAMES[DADD] = "dadd"; //$NON-NLS-1$ - BYTECODE_NAMES[ISUB] = "isub"; //$NON-NLS-1$ - BYTECODE_NAMES[LSUB] = "lsub"; //$NON-NLS-1$ - BYTECODE_NAMES[FSUB] = "fsub"; //$NON-NLS-1$ - BYTECODE_NAMES[DSUB] = "dsub"; //$NON-NLS-1$ - BYTECODE_NAMES[IMUL] = "imul"; //$NON-NLS-1$ - BYTECODE_NAMES[LMUL] = "lmul"; //$NON-NLS-1$ - BYTECODE_NAMES[FMUL] = "fmul"; //$NON-NLS-1$ - BYTECODE_NAMES[DMUL] = "dmul"; //$NON-NLS-1$ - BYTECODE_NAMES[IDIV] = "idiv"; //$NON-NLS-1$ - BYTECODE_NAMES[LDIV] = "ldiv"; //$NON-NLS-1$ - BYTECODE_NAMES[FDIV] = "fdiv"; //$NON-NLS-1$ - BYTECODE_NAMES[DDIV] = "ddiv"; //$NON-NLS-1$ - BYTECODE_NAMES[IREM] = "irem"; //$NON-NLS-1$ - BYTECODE_NAMES[LREM] = "lrem"; //$NON-NLS-1$ - BYTECODE_NAMES[FREM] = "frem"; //$NON-NLS-1$ - BYTECODE_NAMES[DREM] = "drem"; //$NON-NLS-1$ - BYTECODE_NAMES[INEG] = "ineg"; //$NON-NLS-1$ - BYTECODE_NAMES[LNEG] = "lneg"; //$NON-NLS-1$ - BYTECODE_NAMES[FNEG] = "fneg"; //$NON-NLS-1$ - BYTECODE_NAMES[DNEG] = "dneg"; //$NON-NLS-1$ - BYTECODE_NAMES[ISHL] = "ishl"; //$NON-NLS-1$ - BYTECODE_NAMES[LSHL] = "lshl"; //$NON-NLS-1$ - BYTECODE_NAMES[ISHR] = "ishr"; //$NON-NLS-1$ - BYTECODE_NAMES[LSHR] = "lshr"; //$NON-NLS-1$ - BYTECODE_NAMES[IUSHR] = "iushr"; //$NON-NLS-1$ - BYTECODE_NAMES[LUSHR] = "lushr"; //$NON-NLS-1$ - BYTECODE_NAMES[IAND] = "iand"; //$NON-NLS-1$ - BYTECODE_NAMES[LAND] = "land"; //$NON-NLS-1$ - BYTECODE_NAMES[IOR] = "ior"; //$NON-NLS-1$ - BYTECODE_NAMES[LOR] = "lor"; //$NON-NLS-1$ - BYTECODE_NAMES[IXOR] = "ixor"; //$NON-NLS-1$ - BYTECODE_NAMES[LXOR] = "lxor"; //$NON-NLS-1$ - BYTECODE_NAMES[IINC] = "iinc"; //$NON-NLS-1$ - BYTECODE_NAMES[I2L] = "i2l"; //$NON-NLS-1$ - BYTECODE_NAMES[I2F] = "i2f"; //$NON-NLS-1$ - BYTECODE_NAMES[I2D] = "i2d"; //$NON-NLS-1$ - BYTECODE_NAMES[L2I] = "l2i"; //$NON-NLS-1$ - BYTECODE_NAMES[L2F] = "l2f"; //$NON-NLS-1$ - BYTECODE_NAMES[L2D] = "l2d"; //$NON-NLS-1$ - BYTECODE_NAMES[F2I] = "f2i"; //$NON-NLS-1$ - BYTECODE_NAMES[F2L] = "f2l"; //$NON-NLS-1$ - BYTECODE_NAMES[F2D] = "f2d"; //$NON-NLS-1$ - BYTECODE_NAMES[D2I] = "d2i"; //$NON-NLS-1$ - BYTECODE_NAMES[D2L] = "d2l"; //$NON-NLS-1$ - BYTECODE_NAMES[D2F] = "d2f"; //$NON-NLS-1$ - BYTECODE_NAMES[I2B] = "i2b"; //$NON-NLS-1$ - BYTECODE_NAMES[I2C] = "i2c"; //$NON-NLS-1$ - BYTECODE_NAMES[I2S] = "i2s"; //$NON-NLS-1$ - BYTECODE_NAMES[LCMP] = "lcmp"; //$NON-NLS-1$ - BYTECODE_NAMES[FCMPL] = "fcmpl"; //$NON-NLS-1$ - BYTECODE_NAMES[FCMPG] = "fcmpg"; //$NON-NLS-1$ - BYTECODE_NAMES[DCMPL] = "dcmpl"; //$NON-NLS-1$ - BYTECODE_NAMES[DCMPG] = "dcmpg"; //$NON-NLS-1$ - BYTECODE_NAMES[IFEQ] = "ifeq"; //$NON-NLS-1$ - BYTECODE_NAMES[IFNE] = "ifne"; //$NON-NLS-1$ - BYTECODE_NAMES[IFLT] = "iflt"; //$NON-NLS-1$ - BYTECODE_NAMES[IFGE] = "ifge"; //$NON-NLS-1$ - BYTECODE_NAMES[IFGT] = "ifgt"; //$NON-NLS-1$ - BYTECODE_NAMES[IFLE] = "ifle"; //$NON-NLS-1$ - BYTECODE_NAMES[IF_ICMPEQ] = "if_icmpeq"; //$NON-NLS-1$ - BYTECODE_NAMES[IF_ICMPNE] = "if_icmpne"; //$NON-NLS-1$ - BYTECODE_NAMES[IF_ICMPLT] = "if_icmplt"; //$NON-NLS-1$ - BYTECODE_NAMES[IF_ICMPGE] = "if_icmpge"; //$NON-NLS-1$ - BYTECODE_NAMES[IF_ICMPGT] = "if_icmpgt"; //$NON-NLS-1$ - BYTECODE_NAMES[IF_ICMPLE] = "if_icmple"; //$NON-NLS-1$ - BYTECODE_NAMES[IF_ACMPEQ] = "if_acmpeq"; //$NON-NLS-1$ - BYTECODE_NAMES[IF_ACMPNE] = "if_acmpne"; //$NON-NLS-1$ - BYTECODE_NAMES[GOTO] = "goto"; //$NON-NLS-1$ - BYTECODE_NAMES[JSR] = "jsr"; //$NON-NLS-1$ - BYTECODE_NAMES[RET] = "ret"; //$NON-NLS-1$ - BYTECODE_NAMES[TABLESWITCH] = "tableswitch"; //$NON-NLS-1$ - BYTECODE_NAMES[LOOKUPSWITCH] = "lookupswitch"; //$NON-NLS-1$ - BYTECODE_NAMES[IRETURN] = "ireturn"; //$NON-NLS-1$ - BYTECODE_NAMES[LRETURN] = "lreturn"; //$NON-NLS-1$ - BYTECODE_NAMES[FRETURN] = "freturn"; //$NON-NLS-1$ - BYTECODE_NAMES[DRETURN] = "dreturn"; //$NON-NLS-1$ - BYTECODE_NAMES[ARETURN] = "areturn"; //$NON-NLS-1$ - BYTECODE_NAMES[RETURN] = "return"; //$NON-NLS-1$ - BYTECODE_NAMES[GETSTATIC] = "getstatic"; //$NON-NLS-1$ - BYTECODE_NAMES[PUTSTATIC] = "putstatic"; //$NON-NLS-1$ - BYTECODE_NAMES[GETFIELD] = "getfield"; //$NON-NLS-1$ - BYTECODE_NAMES[PUTFIELD] = "putfield"; //$NON-NLS-1$ - BYTECODE_NAMES[INVOKEVIRTUAL] = "invokevirtual"; //$NON-NLS-1$ - BYTECODE_NAMES[INVOKESPECIAL] = "invokespecial"; //$NON-NLS-1$ - BYTECODE_NAMES[INVOKESTATIC] = "invokestatic"; //$NON-NLS-1$ - BYTECODE_NAMES[INVOKEINTERFACE] = "invokeinterface"; //$NON-NLS-1$ - BYTECODE_NAMES[NEW] = "new"; //$NON-NLS-1$ - BYTECODE_NAMES[NEWARRAY] = "newarray"; //$NON-NLS-1$ - BYTECODE_NAMES[ANEWARRAY] = "anewarray"; //$NON-NLS-1$ - BYTECODE_NAMES[ARRAYLENGTH] = "arraylength"; //$NON-NLS-1$ - BYTECODE_NAMES[ATHROW] = "athrow"; //$NON-NLS-1$ - BYTECODE_NAMES[CHECKCAST] = "checkcast"; //$NON-NLS-1$ - BYTECODE_NAMES[INSTANCEOF] = "instanceof"; //$NON-NLS-1$ - BYTECODE_NAMES[MONITORENTER] = "monitorenter"; //$NON-NLS-1$ - BYTECODE_NAMES[MONITOREXIT] = "monitorexit"; //$NON-NLS-1$ - BYTECODE_NAMES[WIDE] = "wide"; //$NON-NLS-1$ - BYTECODE_NAMES[MULTIANEWARRAY] = "multianewarray"; //$NON-NLS-1$ - BYTECODE_NAMES[IFNULL] = "ifnull"; //$NON-NLS-1$ - BYTECODE_NAMES[IFNONNULL] = "ifnonnull"; //$NON-NLS-1$ - BYTECODE_NAMES[GOTO_W] = "goto_w"; //$NON-NLS-1$ - BYTECODE_NAMES[JSR_W] = "jsr_w"; //$NON-NLS-1$ - BYTECODE_NAMES[BREAKPOINT] = "breakpoint"; //$NON-NLS-1$ - BYTECODE_NAMES[IMPDEP1] = "impdep1"; //$NON-NLS-1$ - BYTECODE_NAMES[IMPDEP2] = "impdep2"; //$NON-NLS-1$ - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ParameterAnnotation.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ParameterAnnotation.java deleted file mode 100644 index ad7c6dcac..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/ParameterAnnotation.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class ParameterAnnotation extends ClassFileStruct { - - private static final Annotation[] NO_ENTRIES = new Annotation[0]; - - private int annotationsNumber; - private Annotation[] annotations; - private int readOffset; - - /** - * Constructor for Annotation. - * - * @param classFileBytes - * @param constantPool - * @param offset - * @throws ClassFormatException - */ - public ParameterAnnotation(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - - final int length = u2At(classFileBytes, 0, offset); - this.readOffset = 2; - this.annotationsNumber = length; - if (length != 0) { - this.annotations = new Annotation[length]; - for (int i = 0; i < length; i++) { - Annotation annotation = new Annotation(classFileBytes, constantPool, offset + this.readOffset); - this.annotations[i] = annotation; - this.readOffset += annotation.sizeInBytes(); - } - } else { - this.annotations = NO_ENTRIES; - } - } - - int sizeInBytes() { - return this.readOffset; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IParameterAnnotation#getAnnotations() - */ - public Annotation[] getAnnotations() { - return this.annotations; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IParameterAnnotation#getAnnotationsNumber() - */ - public int getAnnotationsNumber() { - return this.annotationsNumber; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeInvisibleAnnotationsAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeInvisibleAnnotationsAttribute.java deleted file mode 100644 index f2e164c79..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeInvisibleAnnotationsAttribute.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class RuntimeInvisibleAnnotationsAttribute extends ClassFileAttribute { - - private static final Annotation[] NO_ENTRIES = new Annotation[0]; - private int annotationsNumber; - private Annotation[] annotations; - - /** - * Constructor for RuntimeInvisibleAnnotations. - * @param classFileBytes - * @param constantPool - * @param offset - * @throws ClassFormatException - */ - public RuntimeInvisibleAnnotationsAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - super(classFileBytes, constantPool, offset); - final int length = u2At(classFileBytes, 6, offset); - this.annotationsNumber = length; - if (length != 0) { - int readOffset = 8; - this.annotations = new Annotation[length]; - for (int i = 0; i < length; i++) { - Annotation annotation = new Annotation(classFileBytes, constantPool, offset + readOffset); - this.annotations[i] = annotation; - readOffset += annotation.sizeInBytes(); - } - } else { - this.annotations = NO_ENTRIES; - } - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IRuntimeInvisibleAnnotations#getAnnotations() - */ - public Annotation[] getAnnotations() { - return this.annotations; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IRuntimeInvisibleAnnotations#getAnnotationsNumber() - */ - public int getAnnotationsNumber() { - return this.annotationsNumber; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeInvisibleParameterAnnotationsAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeInvisibleParameterAnnotationsAttribute.java deleted file mode 100644 index 3c724dd08..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeInvisibleParameterAnnotationsAttribute.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class RuntimeInvisibleParameterAnnotationsAttribute extends ClassFileAttribute { - - private static final ParameterAnnotation[] NO_ENTRIES = new ParameterAnnotation[0]; - private ParameterAnnotation[] parameterAnnotations; - private int parametersNumber; - - /** - * Constructor for RuntimeVisibleParameterAnnotations. - * @param classFileBytes - * @param constantPool - * @param offset - * @throws ClassFormatException - */ - public RuntimeInvisibleParameterAnnotationsAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - super(classFileBytes, constantPool, offset); - final int length = u1At(classFileBytes, 6, offset); - this.parametersNumber = length; - if (length != 0) { - int readOffset = 7; - this.parameterAnnotations = new ParameterAnnotation[length]; - for (int i = 0; i < length; i++) { - ParameterAnnotation parameterAnnotation = new ParameterAnnotation(classFileBytes, constantPool, offset + readOffset); - this.parameterAnnotations[i] = parameterAnnotation; - readOffset += parameterAnnotation.sizeInBytes(); - } - } else { - this.parameterAnnotations = NO_ENTRIES; - } - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IRuntimeInvisibleParameterAnnotations#getAnnotations() - */ - public ParameterAnnotation[] getParameterAnnotations() { - return this.parameterAnnotations; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IRuntimeInvisibleParameterAnnotations#getParametersNumber() - */ - public int getParametersNumber() { - return this.parametersNumber; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeVisibleAnnotationsAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeVisibleAnnotationsAttribute.java deleted file mode 100644 index ff738fa3c..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeVisibleAnnotationsAttribute.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class RuntimeVisibleAnnotationsAttribute extends ClassFileAttribute { - - private static final Annotation[] NO_ENTRIES = new Annotation[0]; - private int annotationsNumber; - private Annotation[] annotations; - - /** - * Constructor for RuntimeVisibleAnnotations. - * @param classFileBytes - * @param constantPool - * @param offset - * @throws ClassFormatException - */ - public RuntimeVisibleAnnotationsAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - super(classFileBytes, constantPool, offset); - final int length = u2At(classFileBytes, 6, offset); - this.annotationsNumber = length; - if (length != 0) { - int readOffset = 8; - this.annotations = new Annotation[length]; - for (int i = 0; i < length; i++) { - Annotation annotation = new Annotation(classFileBytes, constantPool, offset + readOffset); - this.annotations[i] = annotation; - readOffset += annotation.sizeInBytes(); - } - } else { - this.annotations = NO_ENTRIES; - } - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IRuntimeVisibleAnnotations#getAnnotations() - */ - public Annotation[] getAnnotations() { - return this.annotations; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IRuntimeVisibleAnnotations#getAnnotationsNumber() - */ - public int getAnnotationsNumber() { - return this.annotationsNumber; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeVisibleParameterAnnotationsAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeVisibleParameterAnnotationsAttribute.java deleted file mode 100644 index 71700e217..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/RuntimeVisibleParameterAnnotationsAttribute.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class RuntimeVisibleParameterAnnotationsAttribute extends ClassFileAttribute { - - private static final ParameterAnnotation[] NO_ENTRIES = new ParameterAnnotation[0]; - private int parametersNumber; - private ParameterAnnotation[] parameterAnnotations; - - /** - * Constructor for RuntimeVisibleParameterAnnotations. - * @param classFileBytes - * @param constantPool - * @param offset - * @throws ClassFormatException - */ - public RuntimeVisibleParameterAnnotationsAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - super(classFileBytes, constantPool, offset); - final int length = u1At(classFileBytes, 6, offset); - this.parametersNumber = length; - if (length != 0) { - int readOffset = 7; - this.parameterAnnotations = new ParameterAnnotation[length]; - for (int i = 0; i < length; i++) { - ParameterAnnotation parameterAnnotation = new ParameterAnnotation(classFileBytes, constantPool, offset + readOffset); - this.parameterAnnotations[i] = parameterAnnotation; - readOffset += parameterAnnotation.sizeInBytes(); - } - } else { - this.parameterAnnotations = NO_ENTRIES; - } - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IRuntimeVisibleParameterAnnotations#getAnnotations() - */ - public ParameterAnnotation[] getParameterAnnotations() { - return this.parameterAnnotations; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.IRuntimeVisibleParameterAnnotations#getParametersNumber() - */ - public int getParametersNumber() { - return this.parametersNumber; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Signature.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Signature.java deleted file mode 100644 index e530f1e40..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Signature.java +++ /dev/null @@ -1,1163 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -import java.util.ArrayList; - -/* - * Provides methods for encoding and decoding type and method signature strings. - *

    - * Signatures obtained from parsing source files (i.e. files with one of the - * {@link JavaCore#getJavaLikeExtensions() Java-like extensions}) differ subtly - * from ones obtained from pre-compiled binary (".class") files in class names are - * usually left unresolved in the former. For example, the normal resolved form - * of the type "String" embeds the class's package name ("Ljava.lang.String;" - * or "Ljava/lang/String;"), whereas the unresolved form contains only what is - * written "QString;". - *

    - *

    - * Generic types introduce to the Java language in J2SE 1.5 add three new - * facets to signatures: type variables, parameterized types with type arguments, - * and formal type parameters. Rich signatures containing these facets - * only occur when dealing with code that makes overt use of the new language - * features. All other code, and certainly all Java code written or compiled - * with J2SE 1.4 or earlier, involved only simple signatures. - *

    - *

    - * Note that the "Q" and "!" formats are specific to Eclipse; the remainder - * are specified in the JVM spec. - *

    - *

    - * The syntax for a type signature is: - *

    - * TypeSignature ::=
    - *     "B"  // byte
    - *   | "C"  // char
    - *   | "D"  // double
    - *   | "F"  // float
    - *   | "I"  // int
    - *   | "J"  // long
    - *   | "S"  // short
    - *   | "V"  // void
    - *   | "Z"  // boolean
    - *   | "T" + Identifier + ";" // type variable
    - *   | "[" + TypeSignature  // array X[]
    - *   | "!" + TypeSignature  // capture-of ?
    - *   | ResolvedClassTypeSignature
    - *   | UnresolvedClassTypeSignature
    - *
    - * ResolvedClassTypeSignature ::= // resolved named type (in compiled code)
    - *     "L" + Identifier + OptionalTypeArguments
    - *           ( ( "." | "/" ) + Identifier + OptionalTypeArguments )* + ";"
    - *     | OptionalTypeParameters + "L" + Identifier +
    - *           ( ( "." | "/" ) + Identifier )* + ";"
    - *
    - * UnresolvedClassTypeSignature ::= // unresolved named type (in source code)
    - *     "Q" + Identifier + OptionalTypeArguments
    - *           ( ( "." | "/" ) + Identifier + OptionalTypeArguments )* + ";"
    - *     | OptionalTypeParameters "Q" + Identifier +
    - *           ( ( "." | "/" ) + Identifier )* + ";"
    - *
    - * OptionalTypeArguments ::=
    - *     "<" + TypeArgument+ + ">"
    - *   |
    - *
    - * TypeArgument ::=
    - *   | TypeSignature
    - *   | "*" // wildcard ?
    - *   | "+" TypeSignature // wildcard ? extends X
    - *   | "-" TypeSignature // wildcard ? super X
    - *
    - * OptionalTypeParameters ::=
    - *     "<" + FormalTypeParameterSignature+ + ">"
    - *   |
    - * 
    - *

    - *

    - * Examples: - *

      - *
    • "[[I" denotes int[][]
    • - *
    • "Ljava.lang.String;" denotes java.lang.String in compiled code
    • - *
    • "QString;" denotes String in source code
    • - *
    • "Qjava.lang.String;" denotes java.lang.String in source code
    • - *
    • "[QString;" denotes String[] in source code
    • - *
    • "QMap<QString;*>;" denotes Map<String,?> in source code
    • - *
    • "Qjava.util.List<TV;>;" denotes java.util.List<V> in source code
    • - *
    • "<E;>Ljava.util.List;" denotes <E>java.util.List in source code
    • - *
    - *

    - *

    - * The syntax for a method signature is: - *

    - * MethodSignature ::= OptionalTypeParameters + "(" + ParamTypeSignature* + ")" + ReturnTypeSignature
    - * ParamTypeSignature ::= TypeSignature
    - * ReturnTypeSignature ::= TypeSignature
    - * 
    - *

    - * Examples: - *

      - *
    • "()I" denotes int foo()
    • - *
    • "([Ljava.lang.String;)V" denotes void foo(java.lang.String[]) in compiled code
    • - *
    • "(QString;)QObject;" denotes Object foo(String) in source code
    • - *
    - *

    - *

    - * The syntax for a formal type parameter signature is: - *

    - * FormalTypeParameterSignature ::=
    - *     TypeVariableName + OptionalClassBound + InterfaceBound*
    - * TypeVariableName ::= Identifier
    - * OptionalClassBound ::=
    - *     ":"
    - *   | ":" + TypeSignature
    - * InterfaceBound ::=
    - *     ":" + TypeSignature
    - * 
    - *

    - * Examples: - *

      - *
    • "X:" denotes X
    • - *
    • "X:QReader;" denotes X extends Reader in source code
    • - *
    • "X:QReader;:QSerializable;" denotes X extends Reader & Serializable in source code
    • - *
    - *

    - *

    - * This class provides static methods and constants only. - *

    - * @noinstantiate This class is not intended to be instantiated by clients. - */ -public final class Signature { - /* - * Character constant indicating the primitive type boolean in a signature. - * Value is 'Z'. - */ - public static final char C_BOOLEAN = 'Z'; - - /* - * Character constant indicating the primitive type byte in a signature. - * Value is 'B'. - */ - public static final char C_BYTE = 'B'; - - /* - * Character constant indicating the primitive type char in a signature. - * Value is 'C'. - */ - public static final char C_CHAR = 'C'; - - /* - * Character constant indicating the primitive type double in a signature. - * Value is 'D'. - */ - public static final char C_DOUBLE = 'D'; - - /* - * Character constant indicating the primitive type float in a signature. - * Value is 'F'. - */ - public static final char C_FLOAT = 'F'; - - /* - * Character constant indicating the primitive type int in a signature. - * Value is 'I'. - */ - public static final char C_INT = 'I'; - - /* - * Character constant indicating the semicolon in a signature. - * Value is ';'. - */ - public static final char C_SEMICOLON = ';'; - - /* - * Character constant indicating the colon in a signature. - * Value is ':'. - * @since 3.0 - */ - public static final char C_COLON = ':'; - - /* - * Character constant indicating the primitive type long in a signature. - * Value is 'J'. - */ - public static final char C_LONG = 'J'; - - /* - * Character constant indicating the primitive type short in a signature. - * Value is 'S'. - */ - public static final char C_SHORT = 'S'; - - /* - * Character constant indicating result type void in a signature. - * Value is 'V'. - */ - public static final char C_VOID = 'V'; - - /* - * Character constant indicating the start of a resolved type variable in a - * signature. Value is 'T'. - * @since 3.0 - */ - public static final char C_TYPE_VARIABLE = 'T'; - - /* - * Character constant indicating an unbound wildcard type argument - * in a signature. - * Value is '*'. - * @since 3.0 - */ - public static final char C_STAR = '*'; - - /* - * Character constant indicating an exception in a signature. - * Value is '^'. - * @since 3.1 - */ - public static final char C_EXCEPTION_START = '^'; - - /* - * Character constant indicating a bound wildcard type argument - * in a signature with extends clause. - * Value is '+'. - * @since 3.1 - */ - public static final char C_EXTENDS = '+'; - - /* - * Character constant indicating a bound wildcard type argument - * in a signature with super clause. - * Value is '-'. - * @since 3.1 - */ - public static final char C_SUPER = '-'; - - /* - * Character constant indicating the dot in a signature. - * Value is '.'. - */ - public static final char C_DOT = '.'; - - /* - * Character constant indicating the dollar in a signature. - * Value is '$'. - */ - public static final char C_DOLLAR = '$'; - - /* - * Character constant indicating an array type in a signature. - * Value is '['. - */ - public static final char C_ARRAY = '['; - - /* - * Character constant indicating the start of a resolved, named type in a - * signature. Value is 'L'. - */ - public static final char C_RESOLVED = 'L'; - - /* - * Character constant indicating the start of an unresolved, named type in a - * signature. Value is 'Q'. - */ - public static final char C_UNRESOLVED = 'Q'; - - /* - * Character constant indicating the end of a named type in a signature. - * Value is ';'. - */ - public static final char C_NAME_END = ';'; - - /* - * Character constant indicating the start of a parameter type list in a - * signature. Value is '('. - */ - public static final char C_PARAM_START = '('; - - /* - * Character constant indicating the end of a parameter type list in a - * signature. Value is ')'. - */ - public static final char C_PARAM_END = ')'; - - /* - * Character constant indicating the start of a formal type parameter - * (or type argument) list in a signature. Value is '<'. - * @since 3.0 - */ - public static final char C_GENERIC_START = '<'; - - /* - * Character constant indicating the end of a generic type list in a - * signature. Value is '>'. - * @since 3.0 - */ - public static final char C_GENERIC_END = '>'; - - /* - * Character constant indicating a capture of a wildcard type in a - * signature. Value is '!'. - * @since 3.1 - */ - public static final char C_CAPTURE = '!'; - - /* - * String constant for the signature of the primitive type boolean. - * Value is "Z". - */ - public static final String SIG_BOOLEAN = "Z"; //$NON-NLS-1$ - - /* - * String constant for the signature of the primitive type byte. - * Value is "B". - */ - public static final String SIG_BYTE = "B"; //$NON-NLS-1$ - - /* - * String constant for the signature of the primitive type char. - * Value is "C". - */ - public static final String SIG_CHAR = "C"; //$NON-NLS-1$ - - /* - * String constant for the signature of the primitive type double. - * Value is "D". - */ - public static final String SIG_DOUBLE = "D"; //$NON-NLS-1$ - - /* - * String constant for the signature of the primitive type float. - * Value is "F". - */ - public static final String SIG_FLOAT = "F"; //$NON-NLS-1$ - - /* - * String constant for the signature of the primitive type int. - * Value is "I". - */ - public static final String SIG_INT = "I"; //$NON-NLS-1$ - - /* - * String constant for the signature of the primitive type long. - * Value is "J". - */ - public static final String SIG_LONG = "J"; //$NON-NLS-1$ - - /* - * String constant for the signature of the primitive type short. - * Value is "S". - */ - public static final String SIG_SHORT = "S"; //$NON-NLS-1$ - - /* String constant for the signature of result type void. - * Value is "V". - */ - public static final String SIG_VOID = "V"; //$NON-NLS-1$ - - /* - * Kind constant for a class type signature. - * @see #getTypeSignatureKind(String) - * @since 3.0 - */ - public static final int CLASS_TYPE_SIGNATURE = 1; - - /* - * Kind constant for a base (primitive or void) type signature. - * @see #getTypeSignatureKind(String) - * @since 3.0 - */ - public static final int BASE_TYPE_SIGNATURE = 2; - - /* - * Kind constant for a type variable signature. - * @see #getTypeSignatureKind(String) - * @since 3.0 - */ - public static final int TYPE_VARIABLE_SIGNATURE = 3; - - /* - * Kind constant for an array type signature. - * @see #getTypeSignatureKind(String) - * @since 3.0 - */ - public static final int ARRAY_TYPE_SIGNATURE = 4; - - /* - * Kind constant for a wildcard type signature. - * @see #getTypeSignatureKind(String) - * @since 3.1 - */ - public static final int WILDCARD_TYPE_SIGNATURE = 5; - - /* - * Kind constant for the capture of a wildcard type signature. - * @see #getTypeSignatureKind(String) - * @since 3.1 - */ - public static final int CAPTURE_TYPE_SIGNATURE = 6; - - private static final char[] BOOLEAN = "boolean".toCharArray(); //$NON-NLS-1$ - private static final char[] BYTE = "byte".toCharArray(); //$NON-NLS-1$ - private static final char[] CHAR = "char".toCharArray(); //$NON-NLS-1$ - private static final char[] DOUBLE = "double".toCharArray(); //$NON-NLS-1$ - private static final char[] FLOAT = "float".toCharArray(); //$NON-NLS-1$ - private static final char[] INT = "int".toCharArray(); //$NON-NLS-1$ - private static final char[] LONG = "long".toCharArray(); //$NON-NLS-1$ - private static final char[] SHORT = "short".toCharArray(); //$NON-NLS-1$ - private static final char[] VOID = "void".toCharArray(); //$NON-NLS-1$ - // private static final char[] EXTENDS = "extends".toCharArray(); //$NON-NLS-1$ - // private static final char[] SUPER = "super".toCharArray(); //$NON-NLS-1$ - private static final char[] CAPTURE = "capture-of".toCharArray(); //$NON-NLS-1$ - - /* - * Returns the number of parameter types in the given method signature. - * - * @param methodSignature the method signature - * @return the number of parameters - * @exception IllegalArgumentException if the signature is not syntactically - * correct - * @since 2.0 - */ - public static int getParameterCount(char[] methodSignature) throws IllegalArgumentException { - try { - int count = 0; - int i = CharOperation.indexOf(C_PARAM_START, methodSignature); - if (i < 0) { - throw new IllegalArgumentException(); - } - i++; - for (;;) { - if (methodSignature[i] == C_PARAM_END) { - return count; - } - int e = Utility.scanTypeSignature(methodSignature, i); - if (e < 0) { - throw new IllegalArgumentException(); - } - i = e + 1; - count++; - } - } catch (ArrayIndexOutOfBoundsException e) { - throw new IllegalArgumentException(); - } - } - - /* - * Extracts the parameter type signatures from the given method signature. - * The method signature is expected to be dot-based. - * - * @param methodSignature the method signature - * @return the list of parameter type signatures - * @exception IllegalArgumentException if the signature is syntactically - * incorrect - * - * @since 2.0 - */ - public static char[][] getParameterTypes(char[] methodSignature) throws IllegalArgumentException { - try { - int count = getParameterCount(methodSignature); - char[][] result = new char[count][]; - if (count == 0) { - return result; - } - int i = CharOperation.indexOf(C_PARAM_START, methodSignature); - if (i < 0) { - throw new IllegalArgumentException(); - } - i++; - int t = 0; - for (;;) { - if (methodSignature[i] == C_PARAM_END) { - return result; - } - int e = Utility.scanTypeSignature(methodSignature, i); - if (e < 0) { - throw new IllegalArgumentException(); - } - result[t] = CharOperation.subarray(methodSignature, i, e + 1); - t++; - i = e + 1; - } - } catch (ArrayIndexOutOfBoundsException e) { - throw new IllegalArgumentException(); - } - } - - /* - * Extracts the return type from the given method signature. The method signature is - * expected to be dot-based. - * - * @param methodSignature the method signature - * @return the type signature of the return type - * @exception IllegalArgumentException if the signature is syntactically - * incorrect - * - * @since 2.0 - */ - public static char[] getReturnType(char[] methodSignature) throws IllegalArgumentException { - // skip type parameters - int paren = CharOperation.lastIndexOf(C_PARAM_END, methodSignature); - if (paren == -1) { - throw new IllegalArgumentException(); - } - // there could be thrown exceptions behind, thus scan one type exactly - int last = Utility.scanTypeSignature(methodSignature, paren + 1); - return CharOperation.subarray(methodSignature, paren + 1, last + 1); - } - - /* - * Extracts the class and interface bounds from the given formal type - * parameter signature. The class bound, if present, is listed before - * the interface bounds. The signature is expected to be dot-based. - * - * @param formalTypeParameterSignature the formal type parameter signature - * @return the (possibly empty) list of type signatures for the bounds - * @exception IllegalArgumentException if the signature is syntactically - * incorrect - * @since 3.0 - */ - public static char[][] getTypeParameterBounds(char[] formalTypeParameterSignature) throws IllegalArgumentException { - int p1 = CharOperation.indexOf(C_COLON, formalTypeParameterSignature); - if (p1 < 0) { - // no ":" means can't be a formal type parameter signature - throw new IllegalArgumentException(); - } - if (p1 == formalTypeParameterSignature.length - 1) { - // no class or interface bounds - return CharOperation.NO_CHAR_CHAR; - } - int p2 = CharOperation.indexOf(C_COLON, formalTypeParameterSignature, p1 + 1); - char[] classBound; - if (p2 < 0) { - // no interface bounds - classBound = CharOperation.subarray(formalTypeParameterSignature, p1 + 1, formalTypeParameterSignature.length); - return new char[][] {classBound}; - } - if (p2 == p1 + 1) { - // no class bound, but 1 or more interface bounds - classBound = null; - } else { - classBound = CharOperation.subarray(formalTypeParameterSignature, p1 + 1, p2); - } - char[][] interfaceBounds = CharOperation.splitOn(C_COLON, formalTypeParameterSignature, p2 + 1, formalTypeParameterSignature.length); - if (classBound == null) { - return interfaceBounds; - } - int resultLength = interfaceBounds.length + 1; - char[][] result = new char[resultLength][]; - result[0] = classBound; - System.arraycopy(interfaceBounds, 0, result, 1, interfaceBounds.length); - return result; - } - - /* - * Extracts the type parameter signatures from the given method or type signature. - * The method or type signature is expected to be dot-based. - * - * @param methodOrTypeSignature the method or type signature - * @return the list of type parameter signatures - * @exception IllegalArgumentException if the signature is syntactically - * incorrect - * - * @since 3.1 - */ - public static char[][] getTypeParameters(char[] methodOrTypeSignature) throws IllegalArgumentException { - try { - int length = methodOrTypeSignature.length; - if (length == 0) - return CharOperation.NO_CHAR_CHAR; - if (methodOrTypeSignature[0] != C_GENERIC_START) - return CharOperation.NO_CHAR_CHAR; - - ArrayList paramList = new ArrayList(1); - int paramStart = 1, i = 1; // start after leading '<' - while (i < length) { - if (methodOrTypeSignature[i] == C_GENERIC_END) { - int size = paramList.size(); - if (size == 0) - throw new IllegalArgumentException(); - char[][] result; - paramList.toArray(result = new char[size][]); - return result; - } - i = CharOperation.indexOf(C_COLON, methodOrTypeSignature, i); - if (i < 0 || i >= length) - throw new IllegalArgumentException(); - // iterate over bounds - while (methodOrTypeSignature[i] == ':') { - i++; // skip colon - switch (methodOrTypeSignature[i]) { - case ':' : - // no class bound - break; - case C_GENERIC_END : - break; - case C_RESOLVED : - try { - i = Utility.scanClassTypeSignature(methodOrTypeSignature, i); - i++; // position at start of next param if any - } catch (IllegalArgumentException e) { - // not a class type signature -> it is a new type parameter - } - break; - case C_ARRAY : - try { - i = Utility.scanArrayTypeSignature(methodOrTypeSignature, i); - i++; // position at start of next param if any - } catch (IllegalArgumentException e) { - // not an array type signature -> it is a new type parameter - } - break; - case C_TYPE_VARIABLE : - try { - i = Utility.scanTypeVariableSignature(methodOrTypeSignature, i); - i++; // position at start of next param if any - } catch (IllegalArgumentException e) { - // not a type variable signature -> it is a new type parameter - } - break; - // default: another type parameter is starting - } - } - paramList.add(CharOperation.subarray(methodOrTypeSignature, paramStart, i)); - paramStart = i; // next param start from here - } - } catch (ArrayIndexOutOfBoundsException e) { - // invalid signature, fall through - } - throw new IllegalArgumentException(); - } - - /* - * Converts the given type signature to a readable string. The signature is expected to - * be dot-based. - * - *

    - * For example: - *

    -	 * 
    -	 * toString({'[', 'L', 'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', ';'}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', '[', ']'}
    -	 * toString({'I'}) -> {'i', 'n', 't'}
    -	 * toString({'+', 'L', 'O', 'b', 'j', 'e', 'c', 't', ';'}) -> {'?', ' ', 'e', 'x', 't', 'e', 'n', 'd', 's', ' ', 'O', 'b', 'j', 'e', 'c', 't'}
    -	 * 
    -	 * 
    - *

    - *

    - * Note: This method assumes that a type signature containing a '$' - * is an inner type signature. While this is correct in most cases, someone could - * define a non-inner type name containing a '$'. Handling this - * correctly in all cases would have required resolving the signature, which - * generally not feasible. - *

    - * - * @param signature the type signature - * @return the string representation of the type - * @exception IllegalArgumentException if the signature is not syntactically - * correct - * - * @since 2.0 - */ - public static char[] toCharArray(char[] signature) throws IllegalArgumentException { - int sigLength = signature.length; - if (sigLength == 0 || signature[0] == C_PARAM_START || signature[0] == C_GENERIC_START) { - return toCharArray(signature, CharOperation.NO_CHAR, null, true, true); - } - - StringBuffer buffer = new StringBuffer(signature.length + 10); - appendTypeSignature(signature, 0, true, buffer); - char[] result = new char[buffer.length()]; - buffer.getChars(0, buffer.length(), result, 0); - return result; - } - - /* - * Converts the given method signature to a readable form. The method signature is expected to - * be dot-based. - *

    - * For example: - *

    -	 * 
    -	 * toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
    -	 * 
    -	 * 
    - *

    - * - * @param methodSignature the method signature to convert - * @param methodName the name of the method to insert in the result, or - * null if no method name is to be included - * @param parameterNames the parameter names to insert in the result, or - * null if no parameter names are to be included; if supplied, - * the number of parameter names must match that of the method signature - * @param fullyQualifyTypeNames true if type names should be fully - * qualified, and false to use only simple names - * @param includeReturnType true if the return type is to be - * included - * @param isVargArgs true if the last argument should be displayed as a - * variable argument, false otherwise. - * @return the char array representation of the method signature - * - * @since 3.1 - */ - public static char[] toCharArray(char[] methodSignature, char[] methodName, char[][] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType, boolean isVargArgs) { - int firstParen = CharOperation.indexOf(C_PARAM_START, methodSignature); - if (firstParen == -1) { - throw new IllegalArgumentException(); - } - - StringBuffer buffer = new StringBuffer(methodSignature.length + 10); - - // return type - if (includeReturnType) { - char[] rts = getReturnType(methodSignature); - appendTypeSignature(rts, 0, fullyQualifyTypeNames, buffer); - buffer.append(' '); - } - - // selector - if (methodName != null) { - buffer.append(methodName); - } - - // parameters - buffer.append('('); - char[][] pts = getParameterTypes(methodSignature); - for (int i = 0, max = pts.length; i < max; i++) { - if (i == max - 1) { - appendTypeSignature(pts[i], 0, fullyQualifyTypeNames, buffer, isVargArgs); - } else { - appendTypeSignature(pts[i], 0, fullyQualifyTypeNames, buffer); - } - if (parameterNames != null) { - buffer.append(' '); - buffer.append(parameterNames[i]); - } - if (i != pts.length - 1) { - buffer.append(','); - buffer.append(' '); - } - } - buffer.append(')'); - char[] result = new char[buffer.length()]; - buffer.getChars(0, buffer.length(), result, 0); - return result; - } - - /* - * Scans the given string for a type signature starting at the given - * index and appends it to the given buffer, and returns the index of the last - * character. - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @param fullyQualifyTypeNames true if type names should be fully - * qualified, and false to use only simple names - * @param buffer the string buffer to append to - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not a type signature - * @see Utility#scanTypeSignature(char[], int) - */ - private static int appendTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { - return appendTypeSignature(string, start, fullyQualifyTypeNames, buffer, false); - } - - /* - * Scans the given string for a type signature starting at the given - * index and appends it to the given buffer, and returns the index of the last - * character. - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @param fullyQualifyTypeNames true if type names should be fully - * qualified, and false to use only simple names - * @param buffer the string buffer to append to - * @param isVarArgs true if the type must be displayed as a - * variable argument, false otherwise. In this case, the type must be an array type - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not a type signature, or if isVarArgs is true, - * and the type is not an array type signature. - * @see Utility#scanTypeSignature(char[], int) - */ - private static int appendTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer, boolean isVarArgs) { - // need a minimum 1 char - if (start >= string.length) { - throw new IllegalArgumentException(); - } - char c = string[start]; - if (isVarArgs) { - switch (c) { - case C_ARRAY : - return appendArrayTypeSignature(string, start, fullyQualifyTypeNames, buffer, true); - case C_RESOLVED : - case C_UNRESOLVED : - case C_TYPE_VARIABLE : - case C_BOOLEAN : - case C_BYTE : - case C_CHAR : - case C_DOUBLE : - case C_FLOAT : - case C_INT : - case C_LONG : - case C_SHORT : - case C_VOID : - case C_STAR : - case C_EXTENDS : - case C_SUPER : - case C_CAPTURE : - default : - throw new IllegalArgumentException(); // a var args is an array type - } - } - switch (c) { - case C_ARRAY : - return appendArrayTypeSignature(string, start, fullyQualifyTypeNames, buffer); - case C_RESOLVED : - case C_UNRESOLVED : - return appendClassTypeSignature(string, start, fullyQualifyTypeNames, buffer); - case C_TYPE_VARIABLE : - int e = Utility.scanTypeVariableSignature(string, start); - buffer.append(string, start + 1, e - start - 1); - return e; - case C_BOOLEAN : - buffer.append(BOOLEAN); - return start; - case C_BYTE : - buffer.append(BYTE); - return start; - case C_CHAR : - buffer.append(CHAR); - return start; - case C_DOUBLE : - buffer.append(DOUBLE); - return start; - case C_FLOAT : - buffer.append(FLOAT); - return start; - case C_INT : - buffer.append(INT); - return start; - case C_LONG : - buffer.append(LONG); - return start; - case C_SHORT : - buffer.append(SHORT); - return start; - case C_VOID : - buffer.append(VOID); - return start; - case C_CAPTURE : - return appendCaptureTypeSignature(string, start, fullyQualifyTypeNames, buffer); - case C_STAR : - case C_EXTENDS : - case C_SUPER : - return appendTypeArgumentSignature(string, start, fullyQualifyTypeNames, buffer); - default : - throw new IllegalArgumentException(); - } - } - - /* - * Scans the given string for an array type signature starting at the given - * index and appends it to the given buffer, and returns the index of the last - * character. - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @param fullyQualifyTypeNames true if type names should be fully - * qualified, and false to use only simple names - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not an array type signature - * @see Utility#scanArrayTypeSignature(char[], int) - */ - private static int appendArrayTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { - return appendArrayTypeSignature(string, start, fullyQualifyTypeNames, buffer, false); - } - - /* - * Scans the given string for an array type signature starting at the given - * index and appends it to the given buffer, and returns the index of the last - * character. - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @param fullyQualifyTypeNames true if type names should be fully - * qualified, and false to use only simple names - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not an array type signature - * @see Utility#scanArrayTypeSignature(char[], int) - */ - private static int appendCaptureTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { - // need a minimum 2 char - if (start >= string.length - 1) { - throw new IllegalArgumentException(); - } - char c = string[start]; - if (c != C_CAPTURE) { - throw new IllegalArgumentException(); - } - buffer.append(CAPTURE).append(' '); - return appendTypeArgumentSignature(string, start + 1, fullyQualifyTypeNames, buffer); - } - - /* - * Scans the given string for an array type signature starting at the given - * index and appends it to the given buffer, and returns the index of the last - * character. - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @param fullyQualifyTypeNames true if type names should be fully - * qualified, and false to use only simple names - * @param isVarArgs true if the array type must be displayed as a - * variable argument, false otherwise - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not an array type signature - * @see Utility#scanArrayTypeSignature(char[], int) - */ - private static int appendArrayTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer, boolean isVarArgs) { - int length = string.length; - // need a minimum 2 char - if (start >= length - 1) { - throw new IllegalArgumentException(); - } - char c = string[start]; - if (c != C_ARRAY) { - throw new IllegalArgumentException(); - } - - int index = start; - c = string[++index]; - while (c == C_ARRAY) { - // need a minimum 2 char - if (index >= length - 1) { - throw new IllegalArgumentException(); - } - c = string[++index]; - } - - int e = appendTypeSignature(string, index, fullyQualifyTypeNames, buffer); - - for (int i = 1, dims = index - start; i < dims; i++) { - buffer.append('[').append(']'); - } - - if (isVarArgs) { - buffer.append('.').append('.').append('.'); - } else { - buffer.append('[').append(']'); - } - return e; - } - - /* - * Scans the given string for a class type signature starting at the given - * index and appends it to the given buffer, and returns the index of the last - * character. - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @param fullyQualifyTypeNames true if type names should be fully - * qualified, and false to use only simple names - * @param buffer the string buffer to append to - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not a class type signature - * @see Utility#scanClassTypeSignature(char[], int) - */ - private static int appendClassTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { - // need a minimum 3 chars "Lx;" - if (start >= string.length - 2) { - throw new IllegalArgumentException(); - } - // must start in "L" or "Q" - char c = string[start]; - if (c != C_RESOLVED && c != C_UNRESOLVED) { - throw new IllegalArgumentException(); - } - boolean resolved = (c == C_RESOLVED); - boolean removePackageQualifiers = !fullyQualifyTypeNames; - if (!resolved) { - // keep everything in an unresolved name - removePackageQualifiers = false; - } - int p = start + 1; - int checkpoint = buffer.length(); - int innerTypeStart = -1; - boolean inAnonymousType = false; - while (true) { - if (p >= string.length) { - throw new IllegalArgumentException(); - } - c = string[p]; - switch (c) { - case C_SEMICOLON : - // all done - return p; - case C_GENERIC_START : - int e = appendTypeArgumentSignatures(string, p, fullyQualifyTypeNames, buffer); - // once we hit type arguments there are no more package prefixes - removePackageQualifiers = false; - p = e; - break; - case C_DOT : - if (removePackageQualifiers) { - // erase package prefix - buffer.setLength(checkpoint); - } else { - buffer.append('.'); - } - break; - case '/' : - if (removePackageQualifiers) { - // erase package prefix - buffer.setLength(checkpoint); - } else { - buffer.append('/'); - } - break; - case C_DOLLAR : - innerTypeStart = buffer.length(); - inAnonymousType = false; - if (resolved) { - // once we hit "$" there are no more package prefixes - removePackageQualifiers = false; - /* - * Convert '$' in resolved type signatures into '.'. - * NOTE: This assumes that the type signature is an inner type - * signature. This is true in most cases, but someone can define a - * non-inner type name containing a '$'. - */ - buffer.append('.'); - } - break; - default : - if (innerTypeStart != -1 && !inAnonymousType && Character.isDigit(c)) { - inAnonymousType = true; - buffer.setLength(innerTypeStart); // remove '.' - buffer.insert(checkpoint, "new "); //$NON-NLS-1$ - buffer.append("(){}"); //$NON-NLS-1$ - } - if (!inAnonymousType) - buffer.append(c); - innerTypeStart = -1; - } - p++; - } - } - - /* - * Scans the given string for a list of type arguments signature starting at the - * given index and appends it to the given buffer, and returns the index of the - * last character. - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @param fullyQualifyTypeNames true if type names should be fully - * qualified, and false to use only simple names - * @param buffer the string buffer to append to - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not a list of type argument - * signatures - * @see Utility#scanTypeArgumentSignatures(char[], int) - */ - private static int appendTypeArgumentSignatures(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { - // need a minimum 2 char "<>" - if (start >= string.length - 1) { - throw new IllegalArgumentException(); - } - char c = string[start]; - if (c != C_GENERIC_START) { - throw new IllegalArgumentException(); - } - buffer.append('<'); - int p = start + 1; - int count = 0; - while (true) { - if (p >= string.length) { - throw new IllegalArgumentException(); - } - c = string[p]; - if (c == C_GENERIC_END) { - buffer.append('>'); - return p; - } - if (count != 0) { - buffer.append(','); - } - int e = appendTypeArgumentSignature(string, p, fullyQualifyTypeNames, buffer); - count++; - p = e + 1; - } - } - - /* - * Scans the given string for a type argument signature starting at the given - * index and appends it to the given buffer, and returns the index of the last - * character. - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @param fullyQualifyTypeNames true if type names should be fully - * qualified, and false to use only simple names - * @param buffer the string buffer to append to - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not a type argument signature - * @see Utility#scanTypeArgumentSignature(char[], int) - */ - private static int appendTypeArgumentSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { - // need a minimum 1 char - if (start >= string.length) { - throw new IllegalArgumentException(); - } - char c = string[start]; - switch (c) { - case C_STAR : - buffer.append('?'); - return start; - case C_EXTENDS : - buffer.append("? extends "); //$NON-NLS-1$ - return appendTypeSignature(string, start + 1, fullyQualifyTypeNames, buffer); - case C_SUPER : - buffer.append("? super "); //$NON-NLS-1$ - return appendTypeSignature(string, start + 1, fullyQualifyTypeNames, buffer); - default : - return appendTypeSignature(string, start, fullyQualifyTypeNames, buffer); - } - } - - /* - * Converts the given method signature to a readable form. The method signature is expected to - * be dot-based. - *

    - * For example: - *

    -	 * 
    -	 * toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
    -	 * 
    -	 * 
    - *

    - * - * @param methodSignature the method signature to convert - * @param methodName the name of the method to insert in the result, or - * null if no method name is to be included - * @param parameterNames the parameter names to insert in the result, or - * null if no parameter names are to be included; if supplied, - * the number of parameter names must match that of the method signature - * @param fullyQualifyTypeNames true if type names should be fully - * qualified, and false to use only simple names - * @param includeReturnType true if the return type is to be - * included - * @return the char array representation of the method signature - * - * @since 2.0 - */ - public static char[] toCharArray(char[] methodSignature, char[] methodName, char[][] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType) { - return toCharArray(methodSignature, methodName, parameterNames, fullyQualifyTypeNames, includeReturnType, false); - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/SignatureAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/SignatureAttribute.java deleted file mode 100644 index e6024103a..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/SignatureAttribute.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class SignatureAttribute extends ClassFileAttribute { - - private int signatureIndex; - private char[] signature; - - SignatureAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - super(classFileBytes, constantPool, offset); - final int index = u2At(classFileBytes, 6, offset); - this.signatureIndex = index; - ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(index); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.signature = constantPoolEntry.getUtf8Value(); - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.ISignatureAttribute#getSignatureIndex() - */ - public int getSignatureIndex() { - return this.signatureIndex; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.util.ISignatureAttribute#getSignature() - */ - public char[] getSignature() { - return this.signature; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/SourceFileAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/SourceFileAttribute.java deleted file mode 100644 index f468e8433..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/SourceFileAttribute.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public class SourceFileAttribute extends ClassFileAttribute { - - private int sourceFileIndex; - private char[] sourceFileName; - - /** - * Constructor for SourceFileAttribute. - * @param classFileBytes - * @param constantPool - * @param offset - * @throws ClassFormatException - */ - public SourceFileAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { - super(classFileBytes, constantPool, offset); - this.sourceFileIndex = u2At(classFileBytes, 6, offset); - ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(this.sourceFileIndex); - if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { - throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); - } - this.sourceFileName = constantPoolEntry.getUtf8Value(); - } - - /* - * @see ISourceAttribute#getSourceFileIndex() - */ - public int getSourceFileIndex() { - return this.sourceFileIndex; - } - - /* - * @see ISourceAttribute#getSourceFileName() - */ - public char[] getSourceFileName() { - return this.sourceFileName; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/TypeConstants.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/TypeConstants.java deleted file mode 100644 index 1e000fbd9..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/TypeConstants.java +++ /dev/null @@ -1,153 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -public interface TypeConstants { - - char[] JAVA = "java".toCharArray(); //$NON-NLS-1$ - char[] LANG = "lang".toCharArray(); //$NON-NLS-1$ - char[] IO = "io".toCharArray(); //$NON-NLS-1$ - char[] UTIL = "util".toCharArray(); //$NON-NLS-1$ - char[] ANNOTATION = "annotation".toCharArray(); //$NON-NLS-1$ - char[] REFLECT = "reflect".toCharArray(); //$NON-NLS-1$ - char[] LENGTH = "length".toCharArray(); //$NON-NLS-1$ - char[] CLONE = "clone".toCharArray(); //$NON-NLS-1$ - char[] EQUALS = "equals".toCharArray(); //$NON-NLS-1$ - char[] GETCLASS = "getClass".toCharArray(); //$NON-NLS-1$ - char[] HASHCODE = "hashCode".toCharArray(); //$NON-NLS-1$ - char[] OBJECT = "Object".toCharArray(); //$NON-NLS-1$ - char[] MAIN = "main".toCharArray(); //$NON-NLS-1$ - char[] SERIALVERSIONUID = "serialVersionUID".toCharArray(); //$NON-NLS-1$ - char[] SERIALPERSISTENTFIELDS = "serialPersistentFields".toCharArray(); //$NON-NLS-1$ - char[] READRESOLVE = "readResolve".toCharArray(); //$NON-NLS-1$ - char[] WRITEREPLACE = "writeReplace".toCharArray(); //$NON-NLS-1$ - char[] READOBJECT = "readObject".toCharArray(); //$NON-NLS-1$ - char[] WRITEOBJECT = "writeObject".toCharArray(); //$NON-NLS-1$ - char[] CharArray_JAVA_LANG_OBJECT = "java.lang.Object".toCharArray(); //$NON-NLS-1$ - char[] CharArray_JAVA_LANG_ENUM = "java.lang.Enum".toCharArray(); //$NON-NLS-1$ - char[] CharArray_JAVA_LANG_ANNOTATION_ANNOTATION = "java.lang.annotation.Annotation".toCharArray(); //$NON-NLS-1$ - char[] CharArray_JAVA_IO_OBJECTINPUTSTREAM = "java.io.ObjectInputStream".toCharArray(); //$NON-NLS-1$ - char[] CharArray_JAVA_IO_OBJECTOUTPUTSTREAM = "java.io.ObjectOutputStream".toCharArray(); //$NON-NLS-1$ - char[] CharArray_JAVA_IO_OBJECTSTREAMFIELD = "java.io.ObjectStreamField".toCharArray(); //$NON-NLS-1$ - char[] ANONYM_PREFIX = "new ".toCharArray(); //$NON-NLS-1$ - char[] ANONYM_SUFFIX = "(){}".toCharArray(); //$NON-NLS-1$ - char[] WILDCARD_NAME = {'?'}; - char[] WILDCARD_SUPER = " super ".toCharArray(); //$NON-NLS-1$ - char[] WILDCARD_EXTENDS = " extends ".toCharArray(); //$NON-NLS-1$ - char[] WILDCARD_MINUS = {'-'}; - char[] WILDCARD_STAR = {'*'}; - char[] WILDCARD_PLUS = {'+'}; - char[] WILDCARD_CAPTURE_NAME_PREFIX = "capture#".toCharArray(); //$NON-NLS-1$ - char[] WILDCARD_CAPTURE_NAME_SUFFIX = "-of ".toCharArray(); //$NON-NLS-1$ - char[] WILDCARD_CAPTURE = {'!'}; - char[] BYTE = "byte".toCharArray(); //$NON-NLS-1$ - char[] SHORT = "short".toCharArray(); //$NON-NLS-1$ - char[] INT = "int".toCharArray(); //$NON-NLS-1$ - char[] LONG = "long".toCharArray(); //$NON-NLS-1$ - char[] FLOAT = "float".toCharArray(); //$NON-NLS-1$ - char[] DOUBLE = "double".toCharArray(); //$NON-NLS-1$ - char[] CHAR = "char".toCharArray(); //$NON-NLS-1$ - char[] BOOLEAN = "boolean".toCharArray(); //$NON-NLS-1$ - char[] NULL = "null".toCharArray(); //$NON-NLS-1$ - char[] VOID = "void".toCharArray(); //$NON-NLS-1$ - char[] VALUE = "value".toCharArray(); //$NON-NLS-1$ - char[] VALUES = "values".toCharArray(); //$NON-NLS-1$ - char[] VALUEOF = "valueOf".toCharArray(); //$NON-NLS-1$ - char[] UPPER_SOURCE = "SOURCE".toCharArray(); //$NON-NLS-1$ - char[] UPPER_CLASS = "CLASS".toCharArray(); //$NON-NLS-1$ - char[] UPPER_RUNTIME = "RUNTIME".toCharArray(); //$NON-NLS-1$ - char[] ANNOTATION_PREFIX = "@".toCharArray(); //$NON-NLS-1$ - char[] ANNOTATION_SUFFIX = "()".toCharArray(); //$NON-NLS-1$ - char[] TYPE = "TYPE".toCharArray(); //$NON-NLS-1$ - char[] UPPER_FIELD = "FIELD".toCharArray(); //$NON-NLS-1$ - char[] UPPER_METHOD = "METHOD".toCharArray(); //$NON-NLS-1$ - char[] UPPER_PARAMETER = "PARAMETER".toCharArray(); //$NON-NLS-1$ - char[] UPPER_CONSTRUCTOR = "CONSTRUCTOR".toCharArray(); //$NON-NLS-1$ - char[] UPPER_LOCAL_VARIABLE = "LOCAL_VARIABLE".toCharArray(); //$NON-NLS-1$ - char[] UPPER_ANNOTATION_TYPE = "ANNOTATION_TYPE".toCharArray(); //$NON-NLS-1$ - char[] UPPER_PACKAGE = "PACKAGE".toCharArray(); //$NON-NLS-1$ - - // Constant compound names - char[][] JAVA_LANG = {JAVA, LANG}; - char[][] JAVA_IO = {JAVA, IO}; - char[][] JAVA_LANG_ANNOTATION_ANNOTATION = {JAVA, LANG, ANNOTATION, "Annotation".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_ASSERTIONERROR = {JAVA, LANG, "AssertionError".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_CLASS = {JAVA, LANG, "Class".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_CLASSNOTFOUNDEXCEPTION = {JAVA, LANG, "ClassNotFoundException".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_CLONEABLE = {JAVA, LANG, "Cloneable".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_ENUM = {JAVA, LANG, "Enum".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_EXCEPTION = {JAVA, LANG, "Exception".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_ERROR = {JAVA, LANG, "Error".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_ILLEGALARGUMENTEXCEPTION = {JAVA, LANG, "IllegalArgumentException".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_ITERABLE = {JAVA, LANG, "Iterable".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_NOCLASSDEFERROR = {JAVA, LANG, "NoClassDefError".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_OBJECT = {JAVA, LANG, OBJECT}; - char[][] JAVA_LANG_STRING = {JAVA, LANG, "String".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_STRINGBUFFER = {JAVA, LANG, "StringBuffer".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_STRINGBUILDER = {JAVA, LANG, "StringBuilder".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_SYSTEM = {JAVA, LANG, "System".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_RUNTIMEEXCEPTION = {JAVA, LANG, "RuntimeException".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_THROWABLE = {JAVA, LANG, "Throwable".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_REFLECT_CONSTRUCTOR = {JAVA, LANG, REFLECT, "Constructor".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_IO_PRINTSTREAM = {JAVA, IO, "PrintStream".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_IO_SERIALIZABLE = {JAVA, IO, "Serializable".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_BYTE = {JAVA, LANG, "Byte".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_SHORT = {JAVA, LANG, "Short".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_CHARACTER = {JAVA, LANG, "Character".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_INTEGER = {JAVA, LANG, "Integer".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_LONG = {JAVA, LANG, "Long".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_FLOAT = {JAVA, LANG, "Float".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_DOUBLE = {JAVA, LANG, "Double".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_BOOLEAN = {JAVA, LANG, "Boolean".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_VOID = {JAVA, LANG, "Void".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_UTIL_COLLECTION = {JAVA, UTIL, "Collection".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_UTIL_ITERATOR = {JAVA, UTIL, "Iterator".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_DEPRECATED = {JAVA, LANG, "Deprecated".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_ANNOTATION_DOCUMENTED = {JAVA, LANG, ANNOTATION, "Documented".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_ANNOTATION_INHERITED = {JAVA, LANG, ANNOTATION, "Inherited".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_OVERRIDE = {JAVA, LANG, "Override".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_ANNOTATION_RETENTION = {JAVA, LANG, ANNOTATION, "Retention".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_SUPPRESSWARNINGS = {JAVA, LANG, "SuppressWarnings".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_ANNOTATION_TARGET = {JAVA, LANG, ANNOTATION, "Target".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_ANNOTATION_RETENTIONPOLICY = {JAVA, LANG, ANNOTATION, "RetentionPolicy".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_ANNOTATION_ELEMENTTYPE = {JAVA, LANG, ANNOTATION, "ElementType".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_REFLECT_FIELD = new char[][] {JAVA, LANG, REFLECT, "Field".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_LANG_REFLECT_METHOD = new char[][] {JAVA, LANG, REFLECT, "Method".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_IO_OBJECTSTREAMEXCEPTION = new char[][] {JAVA, IO, "ObjectStreamException".toCharArray()};//$NON-NLS-1$ - char[][] JAVA_IO_EXTERNALIZABLE = {JAVA, IO, "Externalizable".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_IO_IOEXCEPTION = new char[][] {JAVA, IO, "IOException".toCharArray()};//$NON-NLS-1$ - char[][] JAVA_IO_OBJECTOUTPUTSTREAM = new char[][] {JAVA, IO, "ObjectOutputStream".toCharArray()}; //$NON-NLS-1$ - char[][] JAVA_IO_OBJECTINPUTSTREAM = new char[][] {JAVA, IO, "ObjectInputStream".toCharArray()}; //$NON-NLS-1$ - - // Constraints for generic type argument inference - int CONSTRAINT_EQUAL = 0; // Actual = Formal - int CONSTRAINT_EXTENDS = 1; // Actual << Formal - int CONSTRAINT_SUPER = 2; // Actual >> Formal - - // Constants used to perform bound checks - int OK = 0; - int UNCHECKED = 1; - int MISMATCH = 2; - - // Synthetics - char[] INIT = "".toCharArray(); //$NON-NLS-1$ - char[] CLINIT = "".toCharArray(); //$NON-NLS-1$ - char[] SYNTHETIC_SWITCH_ENUM_TABLE = "$SWITCH_TABLE$".toCharArray(); //$NON-NLS-1$ - char[] SYNTHETIC_ENUM_VALUES = "ENUM$VALUES".toCharArray(); //$NON-NLS-1$ - char[] SYNTHETIC_ASSERT_DISABLED = "$assertionsDisabled".toCharArray(); //$NON-NLS-1$ - char[] SYNTHETIC_CLASS = "class$".toCharArray(); //$NON-NLS-1$ - char[] SYNTHETIC_OUTER_LOCAL_PREFIX = "val$".toCharArray(); //$NON-NLS-1$ - char[] SYNTHETIC_ENCLOSING_INSTANCE_PREFIX = "this$".toCharArray(); //$NON-NLS-1$ - char[] SYNTHETIC_ACCESS_METHOD_PREFIX = "access$".toCharArray(); //$NON-NLS-1$ - - // synthetic package-info name - public static final char[] PACKAGE_INFO_NAME = "package-info".toCharArray(); //$NON-NLS-1$ -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Utility.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Utility.java deleted file mode 100644 index 888ce1654..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/Utility.java +++ /dev/null @@ -1,689 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.internal.repository.comparator; - -import java.io.*; -import java.util.Arrays; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -public class Utility { - public static final int[] EMPTY_INT_ARRAY = new int[0]; - public static final String EMPTY_STRING = ""; //$NON-NLS-1$ - private static final int DEFAULT_READING_SIZE = 8192; - private static final char[] BOOLEAN = "boolean".toCharArray(); //$NON-NLS-1$ - private static final char[] BYTE = "byte".toCharArray(); //$NON-NLS-1$ - private static final char[] CHAR = "char".toCharArray(); //$NON-NLS-1$ - private static final char[] DOUBLE = "double".toCharArray(); //$NON-NLS-1$ - private static final char[] FLOAT = "float".toCharArray(); //$NON-NLS-1$ - private static final char[] INT = "int".toCharArray(); //$NON-NLS-1$ - private static final char[] LONG = "long".toCharArray(); //$NON-NLS-1$ - private static final char[] SHORT = "short".toCharArray(); //$NON-NLS-1$ - private static final char[] VOID = "void".toCharArray(); //$NON-NLS-1$ - private static final char[] INIT = "".toCharArray(); //$NON-NLS-1$ - - /** - * Returns the contents of the given zip entry as a byte array. - * @throws IOException if a problem occured reading the zip entry. - */ - public static byte[] getZipEntryByteContent(ZipEntry ze, ZipFile zip) throws IOException { - - InputStream stream = null; - try { - stream = zip.getInputStream(ze); - if (stream == null) - throw new IOException("Invalid zip entry name : " + ze.getName()); //$NON-NLS-1$ - return getInputStreamAsByteArray(stream, (int) ze.getSize()); - } finally { - close(stream); - } - } - - public static void close(Object object) { - if (object == null) - return; - try { - if (object instanceof InputStream) - ((InputStream) object).close(); - else if (object instanceof OutputStream) - ((OutputStream) object).close(); - else if (object instanceof ZipFile) - ((ZipFile) object).close(); - } catch (IOException e) { - //ignore - } - } - - /** - * Returns the given input stream's contents as a byte array. - * If a length is specified (ie. if length != -1), only length bytes - * are returned. Otherwise all bytes in the stream are returned. - * Note this doesn't close the stream. - * @throws IOException if a problem occured reading the stream. - */ - public static byte[] getInputStreamAsByteArray(InputStream stream, int length) throws IOException { - byte[] contents; - if (length == -1) { - contents = new byte[0]; - int contentsLength = 0; - int amountRead = -1; - do { - int amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K - - // resize contents if needed - if (contentsLength + amountRequested > contents.length) { - System.arraycopy(contents, 0, contents = new byte[contentsLength + amountRequested], 0, contentsLength); - } - - // read as many bytes as possible - amountRead = stream.read(contents, contentsLength, amountRequested); - - if (amountRead > 0) { - // remember length of contents - contentsLength += amountRead; - } - } while (amountRead != -1); - - // resize contents if necessary - if (contentsLength < contents.length) { - System.arraycopy(contents, 0, contents = new byte[contentsLength], 0, contentsLength); - } - } else { - contents = new byte[length]; - int len = 0; - int readSize = 0; - while ((readSize != -1) && (len != length)) { - // See PR 1FMS89U - // We record first the read size. In this case len is the actual read size. - len += readSize; - readSize = stream.read(contents, len, length - len); - } - } - - return contents; - } - - public static ClassFileAttribute getAttribute(MethodInfo methodInfo, char[] attributeName) { - ClassFileAttribute[] attributes = methodInfo.getAttributes(); - for (int i = 0, max = attributes.length; i < max; i++) { - if (Arrays.equals(attributes[i].getAttributeName(), attributeName)) { - return attributes[i]; - } - } - return null; - } - - public static ClassFileAttribute getAttribute(FieldInfo fieldInfo, char[] attributeName) { - ClassFileAttribute[] attributes = fieldInfo.getAttributes(); - for (int i = 0, max = attributes.length; i < max; i++) { - if (Arrays.equals(attributes[i].getAttributeName(), attributeName)) { - return attributes[i]; - } - } - return null; - } - - public static ClassFileAttribute getAttribute(ClassFileReader classFileReader, char[] attributeName) { - ClassFileAttribute[] attributes = classFileReader.getAttributes(); - for (int i = 0, max = attributes.length; i < max; i++) { - if (Arrays.equals(attributes[i].getAttributeName(), attributeName)) { - return attributes[i]; - } - } - return null; - } - - /** - * Scans the given string for a type signature starting at the given index - * and returns the index of the last character. - *
    -	 * TypeSignature:
    -	 *  |  BaseTypeSignature
    -	 *  |  ArrayTypeSignature
    -	 *  |  ClassTypeSignature
    -	 *  |  TypeVariableSignature
    -	 * 
    - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not a type signature - */ - public static int scanTypeSignature(char[] string, int start) { - // need a minimum 1 char - if (start >= string.length) { - throw new IllegalArgumentException(); - } - char c = string[start]; - switch (c) { - case Signature.C_ARRAY : - return scanArrayTypeSignature(string, start); - case Signature.C_RESOLVED : - case Signature.C_UNRESOLVED : - return scanClassTypeSignature(string, start); - case Signature.C_TYPE_VARIABLE : - return scanTypeVariableSignature(string, start); - case Signature.C_BOOLEAN : - case Signature.C_BYTE : - case Signature.C_CHAR : - case Signature.C_DOUBLE : - case Signature.C_FLOAT : - case Signature.C_INT : - case Signature.C_LONG : - case Signature.C_SHORT : - case Signature.C_VOID : - return scanBaseTypeSignature(string, start); - case Signature.C_CAPTURE : - return scanCaptureTypeSignature(string, start); - case Signature.C_EXTENDS : - case Signature.C_SUPER : - case Signature.C_STAR : - return scanTypeBoundSignature(string, start); - default : - throw new IllegalArgumentException(); - } - } - - /** - * Scans the given string for a base type signature starting at the given index - * and returns the index of the last character. - *
    -	 * BaseTypeSignature:
    -	 *     B | C | D | F | I
    -	 *   | J | S | V | Z
    -	 * 
    - * Note that although the base type "V" is only allowed in method return types, - * there is no syntactic ambiguity. This method will accept them anywhere - * without complaint. - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not a base type signature - */ - public static int scanBaseTypeSignature(char[] string, int start) { - // need a minimum 1 char - if (start >= string.length) { - throw new IllegalArgumentException(); - } - char c = string[start]; - if ("BCDFIJSVZ".indexOf(c) >= 0) { //$NON-NLS-1$ - return start; - } - throw new IllegalArgumentException(); - } - - /** - * Scans the given string for an array type signature starting at the given - * index and returns the index of the last character. - *
    -	 * ArrayTypeSignature:
    -	 *     [ TypeSignature
    -	 * 
    - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not an array type signature - */ - public static int scanArrayTypeSignature(char[] string, int start) { - int length = string.length; - // need a minimum 2 char - if (start >= length - 1) { - throw new IllegalArgumentException(); - } - char c = string[start]; - if (c != Signature.C_ARRAY) { - throw new IllegalArgumentException(); - } - - c = string[++start]; - while (c == Signature.C_ARRAY) { - // need a minimum 2 char - if (start >= length - 1) { - throw new IllegalArgumentException(); - } - c = string[++start]; - } - return scanTypeSignature(string, start); - } - - /** - * Scans the given string for a capture of a wildcard type signature starting at the given - * index and returns the index of the last character. - *
    -	 * CaptureTypeSignature:
    -	 *     ! TypeBoundSignature
    -	 * 
    - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not a capture type signature - */ - public static int scanCaptureTypeSignature(char[] string, int start) { - // need a minimum 2 char - if (start >= string.length - 1) { - throw new IllegalArgumentException(); - } - char c = string[start]; - if (c != Signature.C_CAPTURE) { - throw new IllegalArgumentException(); - } - return scanTypeBoundSignature(string, start + 1); - } - - /** - * Scans the given string for a type variable signature starting at the given - * index and returns the index of the last character. - *
    -	 * TypeVariableSignature:
    -	 *     T Identifier ;
    -	 * 
    - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not a type variable signature - */ - public static int scanTypeVariableSignature(char[] string, int start) { - // need a minimum 3 chars "Tx;" - if (start >= string.length - 2) { - throw new IllegalArgumentException(); - } - // must start in "T" - char c = string[start]; - if (c != Signature.C_TYPE_VARIABLE) { - throw new IllegalArgumentException(); - } - int id = scanIdentifier(string, start + 1); - c = string[id + 1]; - if (c == Signature.C_SEMICOLON) { - return id + 1; - } - throw new IllegalArgumentException(); - } - - /** - * Scans the given string for an identifier starting at the given - * index and returns the index of the last character. - * Stop characters are: ";", ":", "<", ">", "/", ".". - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not an identifier - */ - public static int scanIdentifier(char[] string, int start) { - // need a minimum 1 char - if (start >= string.length) { - throw new IllegalArgumentException(); - } - int p = start; - while (true) { - char c = string[p]; - if (c == '<' || c == '>' || c == ':' || c == ';' || c == '.' || c == '/') { - return p - 1; - } - p++; - if (p == string.length) { - return p - 1; - } - } - } - - /** - * Scans the given string for a class type signature starting at the given - * index and returns the index of the last character. - *
    -	 * ClassTypeSignature:
    -	 *     { L | Q } Identifier
    -	 *           { { / | . Identifier [ < TypeArgumentSignature* > ] }
    -	 *           ;
    -	 * 
    - * Note that although all "/"-identifiers most come before "."-identifiers, - * there is no syntactic ambiguity. This method will accept them without - * complaint. - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not a class type signature - */ - public static int scanClassTypeSignature(char[] string, int start) { - // need a minimum 3 chars "Lx;" - if (start >= string.length - 2) { - throw new IllegalArgumentException(); - } - // must start in "L" or "Q" - char c = string[start]; - if (c != Signature.C_RESOLVED && c != Signature.C_UNRESOLVED) { - return -1; - } - int p = start + 1; - while (true) { - if (p >= string.length) { - throw new IllegalArgumentException(); - } - c = string[p]; - if (c == Signature.C_SEMICOLON) { - // all done - return p; - } else if (c == Signature.C_GENERIC_START) { - int e = scanTypeArgumentSignatures(string, p); - p = e; - } else if (c == Signature.C_DOT || c == '/') { - int id = scanIdentifier(string, p + 1); - p = id; - } - p++; - } - } - - /** - * Scans the given string for a type bound signature starting at the given - * index and returns the index of the last character. - *
    -	 * TypeBoundSignature:
    -	 *     [-+] TypeSignature ;
    -	 *     *
    -	 * 
    - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not a type variable signature - */ - public static int scanTypeBoundSignature(char[] string, int start) { - // need a minimum 1 char for wildcard - if (start >= string.length) { - throw new IllegalArgumentException(); - } - char c = string[start]; - switch (c) { - case Signature.C_STAR : - return start; - case Signature.C_SUPER : - case Signature.C_EXTENDS : - // need a minimum 3 chars "+[I" - if (start >= string.length - 2) { - throw new IllegalArgumentException(); - } - break; - default : - // must start in "+/-" - throw new IllegalArgumentException(); - - } - c = string[++start]; - switch (c) { - case Signature.C_CAPTURE : - return scanCaptureTypeSignature(string, start); - case Signature.C_SUPER : - case Signature.C_EXTENDS : - return scanTypeBoundSignature(string, start); - case Signature.C_RESOLVED : - case Signature.C_UNRESOLVED : - return scanClassTypeSignature(string, start); - case Signature.C_TYPE_VARIABLE : - return scanTypeVariableSignature(string, start); - case Signature.C_ARRAY : - return scanArrayTypeSignature(string, start); - case Signature.C_STAR : - return start; - default : - throw new IllegalArgumentException(); - } - } - - /** - * Scans the given string for a list of type argument signatures starting at - * the given index and returns the index of the last character. - *
    -	 * TypeArgumentSignatures:
    -	 *     < TypeArgumentSignature* >
    -	 * 
    - * Note that although there is supposed to be at least one type argument, there - * is no syntactic ambiguity if there are none. This method will accept zero - * type argument signatures without complaint. - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not a list of type arguments - * signatures - */ - public static int scanTypeArgumentSignatures(char[] string, int start) { - // need a minimum 2 char "<>" - if (start >= string.length - 1) { - throw new IllegalArgumentException(); - } - char c = string[start]; - if (c != Signature.C_GENERIC_START) { - throw new IllegalArgumentException(); - } - int p = start + 1; - while (true) { - if (p >= string.length) { - throw new IllegalArgumentException(); - } - c = string[p]; - if (c == Signature.C_GENERIC_END) { - return p; - } - int e = scanTypeArgumentSignature(string, p); - p = e + 1; - } - } - - /** - * Scans the given string for a type argument signature starting at the given - * index and returns the index of the last character. - *
    -	 * TypeArgumentSignature:
    -	 *     *
    -	 *  |  + TypeSignature
    -	 *  |  - TypeSignature
    -	 *  |  TypeSignature
    -	 * 
    - * Note that although base types are not allowed in type arguments, there is - * no syntactic ambiguity. This method will accept them without complaint. - * - * @param string the signature string - * @param start the 0-based character index of the first character - * @return the 0-based character index of the last character - * @exception IllegalArgumentException if this is not a type argument signature - */ - public static int scanTypeArgumentSignature(char[] string, int start) { - // need a minimum 1 char - if (start >= string.length) { - throw new IllegalArgumentException(); - } - char c = string[start]; - switch (c) { - case Signature.C_STAR : - return start; - case Signature.C_EXTENDS : - case Signature.C_SUPER : - return scanTypeBoundSignature(string, start); - default : - return scanTypeSignature(string, start); - } - } - - static void appendTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) { - char c = string[start]; - switch (c) { - case Signature.C_ARRAY : - appendArrayTypeSignature(string, start, buffer, compact); - break; - case Signature.C_RESOLVED : - appendClassTypeSignature(string, start, buffer, compact); - break; - case Signature.C_TYPE_VARIABLE : - int e = scanTypeVariableSignature(string, start); - buffer.append(string, start + 1, e - start - 1); - break; - case Signature.C_BOOLEAN : - buffer.append(BOOLEAN); - break; - case Signature.C_BYTE : - buffer.append(BYTE); - break; - case Signature.C_CHAR : - buffer.append(CHAR); - break; - case Signature.C_DOUBLE : - buffer.append(DOUBLE); - break; - case Signature.C_FLOAT : - buffer.append(FLOAT); - break; - case Signature.C_INT : - buffer.append(INT); - break; - case Signature.C_LONG : - buffer.append(LONG); - break; - case Signature.C_SHORT : - buffer.append(SHORT); - break; - case Signature.C_VOID : - buffer.append(VOID); - break; - } - } - - private static void appendArrayTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) { - int length = string.length; - // need a minimum 2 char - if (start >= length - 1) { - throw new IllegalArgumentException(); - } - char c = string[start]; - if (c != Signature.C_ARRAY) { - throw new IllegalArgumentException(); - } - - int index = start; - c = string[++index]; - while (c == Signature.C_ARRAY) { - // need a minimum 2 char - if (index >= length - 1) { - throw new IllegalArgumentException(); - } - c = string[++index]; - } - - appendTypeSignature(string, index, buffer, compact); - - for (int i = 0, dims = index - start; i < dims; i++) { - buffer.append('[').append(']'); - } - } - - private static void appendClassTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) { - char c = string[start]; - if (c != Signature.C_RESOLVED) { - return; - } - int p = start + 1; - int checkpoint = buffer.length(); - while (true) { - c = string[p]; - switch (c) { - case Signature.C_SEMICOLON : - // all done - return; - case Signature.C_DOT : - case '/' : - // erase package prefix - if (compact) { - buffer.setLength(checkpoint); - } else { - buffer.append('.'); - } - break; - case Signature.C_DOLLAR : - /** - * Convert '$' in resolved type signatures into '.'. - * NOTE: This assumes that the type signature is an inner type - * signature. This is true in most cases, but someone can define a - * non-inner type name containing a '$'. - */ - buffer.append('.'); - break; - default : - buffer.append(c); - } - p++; - } - } - - public static String toString(char[] declaringClass, char[] methodName, char[] methodSignature, boolean includeReturnType, boolean compact) { - final boolean isConstructor = Arrays.equals(methodName, INIT); - int firstParen = CharOperation.indexOf(Signature.C_PARAM_START, methodSignature); - if (firstParen == -1) { - return ""; //$NON-NLS-1$ - } - - StringBuffer buffer = new StringBuffer(methodSignature.length + 10); - - // decode declaring class name - // it can be either an array signature or a type signature - if (declaringClass.length > 0) { - char[] declaringClassSignature = null; - if (declaringClass[0] == Signature.C_ARRAY) { - CharOperation.replace(declaringClass, '/', '.'); - declaringClassSignature = Signature.toCharArray(declaringClass); - } else { - CharOperation.replace(declaringClass, '/', '.'); - declaringClassSignature = declaringClass; - } - int lastIndexOfSlash = CharOperation.lastIndexOf('.', declaringClassSignature); - if (compact && lastIndexOfSlash != -1) { - buffer.append(declaringClassSignature, lastIndexOfSlash + 1, declaringClassSignature.length - lastIndexOfSlash - 1); - } else { - buffer.append(declaringClassSignature); - } - } - - // selector - if (!isConstructor) { - buffer.append('.'); - if (methodName != null) { - buffer.append(methodName); - } - } - - // parameters - buffer.append('('); - char[][] pts = Signature.getParameterTypes(methodSignature); - for (int i = 0, max = pts.length; i < max; i++) { - appendTypeSignature(pts[i], 0, buffer, compact); - if (i != pts.length - 1) { - buffer.append(','); - buffer.append(' '); - } - } - buffer.append(')'); - - if (!isConstructor) { - buffer.append(" : "); //$NON-NLS-1$ - // return type - if (includeReturnType) { - char[] rts = Signature.getReturnType(methodSignature); - appendTypeSignature(rts, 0, buffer, compact); - } - } - return String.valueOf(buffer); - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Annotation.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Annotation.java new file mode 100644 index 000000000..db3fea4ce --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Annotation.java @@ -0,0 +1,90 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class Annotation extends ClassFileStruct { + + private static final AnnotationComponent[] NO_ENTRIES = new AnnotationComponent[0]; + + private int typeIndex; + private char[] typeName; + private int componentsNumber; + private AnnotationComponent[] components; + private int readOffset; + + /** + * Constructor for Annotation. + * + * @param classFileBytes + * @param constantPool + * @param offset + * @throws ClassFormatException + */ + public Annotation(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + + final int index = u2At(classFileBytes, 0, offset); + this.typeIndex = index; + if (index != 0) { + ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.typeName = constantPoolEntry.getUtf8Value(); + } else { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + final int length = u2At(classFileBytes, 2, offset); + this.componentsNumber = length; + this.readOffset = 4; + if (length != 0) { + this.components = new AnnotationComponent[length]; + for (int i = 0; i < length; i++) { + AnnotationComponent component = new AnnotationComponent(classFileBytes, constantPool, offset + this.readOffset); + this.components[i] = component; + this.readOffset += component.sizeInBytes(); + } + } else { + this.components = NO_ENTRIES; + } + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotation#getTypeIndex() + */ + public int getTypeIndex() { + return this.typeIndex; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotation#getComponentsNumber() + */ + public int getComponentsNumber() { + return this.componentsNumber; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotation#getComponents() + */ + public AnnotationComponent[] getComponents() { + return this.components; + } + + int sizeInBytes() { + return this.readOffset; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotation#getTypeName() + */ + public char[] getTypeName() { + return this.typeName; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AnnotationComponent.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AnnotationComponent.java new file mode 100644 index 000000000..7a1922d3b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AnnotationComponent.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class AnnotationComponent extends ClassFileStruct { + + private int componentNameIndex; + private char[] componentName; + private AnnotationComponentValue componentValue; + private int readOffset; + + public AnnotationComponent(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + final int nameIndex = u2At(classFileBytes, 0, offset); + this.componentNameIndex = nameIndex; + if (nameIndex != 0) { + ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(nameIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.componentName = constantPoolEntry.getUtf8Value(); + } + this.readOffset = 2; + AnnotationComponentValue value = new AnnotationComponentValue(classFileBytes, constantPool, offset + this.readOffset); + this.componentValue = value; + this.readOffset += value.sizeInBytes(); + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponent#getComponentNameIndex() + */ + public int getComponentNameIndex() { + return this.componentNameIndex; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponent#getComponentName() + */ + public char[] getComponentName() { + return this.componentName; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponent#getComponentValue() + */ + public AnnotationComponentValue getComponentValue() { + return this.componentValue; + } + + int sizeInBytes() { + return this.readOffset; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AnnotationComponentValue.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AnnotationComponentValue.java new file mode 100644 index 000000000..74a26447c --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AnnotationComponentValue.java @@ -0,0 +1,277 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class AnnotationComponentValue extends ClassFileStruct { + /** + * Tag value for a constant of type byte + * @since 3.1 + */ + public static final int BYTE_TAG = 'B'; + /** + * Tag value for a constant of type char + * @since 3.1 + */ + public static final int CHAR_TAG = 'C'; + /** + * Tag value for a constant of type double + * @since 3.1 + */ + public static final int DOUBLE_TAG = 'D'; + /** + * Tag value for a constant of type float + * @since 3.1 + */ + public static final int FLOAT_TAG = 'F'; + /** + * Tag value for a constant of type int + * @since 3.1 + */ + public static final int INTEGER_TAG = 'I'; + /** + * Tag value for a constant of type long + * @since 3.1 + */ + public static final int LONG_TAG = 'J'; + /** + * Tag value for a constant of type short + * @since 3.1 + */ + public static final int SHORT_TAG = 'S'; + /** + * Tag value for a constant of type boolean + * @since 3.1 + */ + public static final int BOOLEAN_TAG = 'Z'; + /** + * Tag value for a constant of type java.lang.String + * @since 3.1 + */ + public static final int STRING_TAG = 's'; + /** + * Tag value for a value that represents an enum constant + * @since 3.1 + */ + public static final int ENUM_TAG = 'e'; + /** + * Tag value for a value that represents a class + * @since 3.1 + */ + public static final int CLASS_TAG = 'c'; + /** + * Tag value for a value that represents an annotation + * @since 3.1 + */ + public static final int ANNOTATION_TAG = '@'; + /** + * Tag value for a value that represents an array + * @since 3.1 + */ + public static final int ARRAY_TAG = '['; + + private static final AnnotationComponentValue[] NO_VALUES = new AnnotationComponentValue[0]; + + private AnnotationComponentValue[] annotationComponentValues; + private Annotation annotationValue; + private ConstantPoolEntry classInfo; + private int classFileInfoIndex; + private ConstantPoolEntry constantValue; + private int constantValueIndex; + private int enumConstantTypeNameIndex; + private int enumConstantNameIndex; + private char[] enumConstantTypeName; + private char[] enumConstantName; + + private int readOffset; + private int tag; + private int valuesNumber; + + public AnnotationComponentValue(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + this.classFileInfoIndex = -1; + this.constantValueIndex = -1; + this.enumConstantTypeNameIndex = -1; + this.enumConstantNameIndex = -1; + final int t = u1At(classFileBytes, 0, offset); + this.tag = t; + this.readOffset = 1; + switch (t) { + case 'B' : + case 'C' : + case 'D' : + case 'F' : + case 'I' : + case 'J' : + case 'S' : + case 'Z' : + case 's' : + final int constantIndex = u2At(classFileBytes, this.readOffset, offset); + this.constantValueIndex = constantIndex; + if (constantIndex != 0) { + ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(constantIndex); + switch (constantPoolEntry.getKind()) { + case ConstantPoolConstant.CONSTANT_Long : + case ConstantPoolConstant.CONSTANT_Float : + case ConstantPoolConstant.CONSTANT_Double : + case ConstantPoolConstant.CONSTANT_Integer : + case ConstantPoolConstant.CONSTANT_Utf8 : + break; + default : + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.constantValue = constantPoolEntry; + } + this.readOffset += 2; + break; + case 'e' : + int index = u2At(classFileBytes, this.readOffset, offset); + this.enumConstantTypeNameIndex = index; + if (index != 0) { + ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.enumConstantTypeName = constantPoolEntry.getUtf8Value(); + } + this.readOffset += 2; + index = u2At(classFileBytes, this.readOffset, offset); + this.enumConstantNameIndex = index; + if (index != 0) { + ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.enumConstantName = constantPoolEntry.getUtf8Value(); + } + this.readOffset += 2; + break; + case 'c' : + final int classFileIndex = u2At(classFileBytes, this.readOffset, offset); + this.classFileInfoIndex = classFileIndex; + if (classFileIndex != 0) { + ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(classFileIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.classInfo = constantPoolEntry; + } + this.readOffset += 2; + break; + case '@' : + Annotation annotation = new Annotation(classFileBytes, constantPool, this.readOffset + offset); + this.annotationValue = annotation; + this.readOffset += annotation.sizeInBytes(); + break; + case '[' : + final int numberOfValues = u2At(classFileBytes, this.readOffset, offset); + this.valuesNumber = numberOfValues; + this.readOffset += 2; + if (numberOfValues != 0) { + this.annotationComponentValues = new AnnotationComponentValue[numberOfValues]; + for (int i = 0; i < numberOfValues; i++) { + AnnotationComponentValue value = new AnnotationComponentValue(classFileBytes, constantPool, offset + this.readOffset); + this.annotationComponentValues[i] = value; + this.readOffset += value.sizeInBytes(); + } + } else { + this.annotationComponentValues = NO_VALUES; + } + break; + } + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getAnnotationComponentValues() + */ + public AnnotationComponentValue[] getAnnotationComponentValues() { + return this.annotationComponentValues; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getAnnotationValue() + */ + public Annotation getAnnotationValue() { + return this.annotationValue; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getClassInfo() + */ + public ConstantPoolEntry getClassInfo() { + return this.classInfo; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getClassInfoIndex() + */ + public int getClassInfoIndex() { + return this.classFileInfoIndex; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getConstantValue() + */ + public ConstantPoolEntry getConstantValue() { + return this.constantValue; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getConstantValueIndex() + */ + public int getConstantValueIndex() { + return this.constantValueIndex; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getEnumConstantName() + */ + public char[] getEnumConstantName() { + return this.enumConstantName; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getEnumConstantNameIndex() + */ + public int getEnumConstantNameIndex() { + return this.enumConstantNameIndex; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getEnumConstantTypeName() + */ + public char[] getEnumConstantTypeName() { + return this.enumConstantTypeName; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getEnumConstantTypeNameIndex() + */ + public int getEnumConstantTypeNameIndex() { + return this.enumConstantTypeNameIndex; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getTag() + */ + public int getTag() { + return this.tag; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationComponentValue#getValuesNumber() + */ + public int getValuesNumber() { + return this.valuesNumber; + } + + int sizeInBytes() { + return this.readOffset; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AnnotationDefaultAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AnnotationDefaultAttribute.java new file mode 100644 index 000000000..638adb12d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AnnotationDefaultAttribute.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class AnnotationDefaultAttribute extends ClassFileAttribute { + + private AnnotationComponentValue memberValue; + + /** + * Constructor for AnnotationDefaultAttribute. + * @param classFileBytes + * @param constantPool + * @param offset + * @throws ClassFormatException + */ + public AnnotationDefaultAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + super(classFileBytes, constantPool, offset); + this.memberValue = new AnnotationComponentValue(classFileBytes, constantPool, offset + 6); + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IAnnotationDefaultAttribute#getMemberValue() + */ + public AnnotationComponentValue getMemberValue() { + return this.memberValue; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AttributeNamesConstants.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AttributeNamesConstants.java new file mode 100644 index 000000000..f4d03fcc7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/AttributeNamesConstants.java @@ -0,0 +1,142 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public interface AttributeNamesConstants { + /* + * "Synthetic" attribute. + *

    Note that prior to JDK 1.5, synthetic elements were always marked + * using an attribute; with 1.5, synthetic elements can also be marked + * using the {@link IModifierConstants#ACC_SYNTHETIC} flag. + *

    + * @since 2.0 + */ + char[] SYNTHETIC = "Synthetic".toCharArray(); //$NON-NLS-1$ + + /* + * "ConstantValue" attribute. + * @since 2.0 + */ + char[] CONSTANT_VALUE = "ConstantValue".toCharArray(); //$NON-NLS-1$ + + /* + * "LineNumberTable" attribute. + * @since 2.0 + */ + char[] LINE_NUMBER = "LineNumberTable".toCharArray(); //$NON-NLS-1$ + + /* + * "LocalVariableTable" attribute. + * @since 2.0 + */ + char[] LOCAL_VARIABLE = "LocalVariableTable".toCharArray(); //$NON-NLS-1$ + + /* + * "InnerClasses" attribute. + * @since 2.0 + */ + char[] INNER_CLASSES = "InnerClasses".toCharArray(); //$NON-NLS-1$ + + /* + * "Code" attribute. + * @since 2.0 + */ + char[] CODE = "Code".toCharArray(); //$NON-NLS-1$ + + /* + * "Exceptions" attribute. + * @since 2.0 + */ + char[] EXCEPTIONS = "Exceptions".toCharArray(); //$NON-NLS-1$ + + /* + * "SourceFile" attribute. + * @since 2.0 + */ + char[] SOURCE = "SourceFile".toCharArray(); //$NON-NLS-1$ + + /* + * "Deprecated" attribute. + * @since 2.0 + */ + char[] DEPRECATED = "Deprecated".toCharArray(); //$NON-NLS-1$ + + /* + * "Signature" attribute (added in J2SE 1.5). + * Class file readers which support J2SE 1.5 return + * attributes with this name represented by objects + * implementing {@link ISignatureAttribute}. + * @since 3.0 + */ + char[] SIGNATURE = "Signature".toCharArray(); //$NON-NLS-1$ + + /* + * "EnclosingMethod" attribute (added in J2SE 1.5). + * Class file readers which support J2SE 1.5 return + * attributes with this name represented by objects + * implementing {@link IEnclosingMethodAttribute}. + * @since 3.0 + */ + char[] ENCLOSING_METHOD = "EnclosingMethod".toCharArray(); //$NON-NLS-1$ + + /* + * "LocalVariableTypeTable" attribute (added in J2SE 1.5). + * @since 3.0 + */ + char[] LOCAL_VARIABLE_TYPE_TABLE = "LocalVariableTypeTable".toCharArray(); //$NON-NLS-1$ + + /* + * "RuntimeVisibleAnnotations" attribute (added in J2SE 1.5). + * @since 3.0 + */ + char[] RUNTIME_VISIBLE_ANNOTATIONS = "RuntimeVisibleAnnotations".toCharArray(); //$NON-NLS-1$ + + /* + * "RuntimeInvisibleAnnotations" attribute (added in J2SE 1.5). + * @since 3.0 + */ + char[] RUNTIME_INVISIBLE_ANNOTATIONS = "RuntimeInvisibleAnnotations".toCharArray(); //$NON-NLS-1$ + + /* + * "RuntimeVisibleParameterAnnotations" attribute (added in J2SE 1.5). + * @since 3.0 + */ + char[] RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS = "RuntimeVisibleParameterAnnotations".toCharArray(); //$NON-NLS-1$ + + /* + * "RuntimeInvisibleParameterAnnotations" attribute (added in J2SE 1.5). + * @since 3.0 + */ + char[] RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS = "RuntimeInvisibleParameterAnnotations".toCharArray(); //$NON-NLS-1$ + + /* + * "AnnotationDefault" attribute (added in J2SE 1.5). + * @since 3.0 + */ + char[] ANNOTATION_DEFAULT = "AnnotationDefault".toCharArray(); //$NON-NLS-1$ + + /* + * "StackMapTable" attribute (added in J2SE 1.6). + * @since 3.2 + */ + char[] STACK_MAP_TABLE = "StackMapTable".toCharArray(); //$NON-NLS-1$ + + /* + * "StackMap" attribute (added in cldc1.0). + * @since 3.2 + */ + char[] STACK_MAP = "StackMap".toCharArray(); //$NON-NLS-1$ + + /* + * "Varargs" attribute (unspecified). + */ + char[] VAR_ARGS = "Varargs".toCharArray(); //$NON-NLS-1$ +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/CharOperation.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/CharOperation.java new file mode 100644 index 000000000..246c66dbc --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/CharOperation.java @@ -0,0 +1,602 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public final class CharOperation { + public static final char[] This = "this".toCharArray(); //$NON-NLS-1$ + + public static final char[] JAVA_LANG_ANNOTATION_DOCUMENTED = "Ljava/lang/annotation/Documented;".toCharArray(); //$NON-NLS-1$ + public static final char[] JAVA_LANG_ANNOTATION_ELEMENTTYPE = "Ljava/lang/annotation/ElementType;".toCharArray(); //$NON-NLS-1$ + public static final char[] JAVA_LANG_ANNOTATION_RETENTION = "Ljava/lang/annotation/Retention;".toCharArray(); //$NON-NLS-1$ + public static final char[] JAVA_LANG_ANNOTATION_RETENTIONPOLICY = "Ljava/lang/annotation/RetentionPolicy;".toCharArray(); //$NON-NLS-1$ + public static final char[] JAVA_LANG_ANNOTATION_TARGET = "Ljava/lang/annotation/Target;".toCharArray(); //$NON-NLS-1$ + public static final char[] JAVA_LANG_DEPRECATED = "Ljava/lang/Deprecated;".toCharArray(); //$NON-NLS-1$ + public static final char[] JAVA_LANG_ANNOTATION_INHERITED = "Ljava/lang/annotation/Inherited;".toCharArray(); //$NON-NLS-1$ + /** + * Constant for an empty char array + */ + public static final char[] NO_CHAR = new char[0]; + + /** + * Constant for an empty char array with two dimensions. + */ + public static final char[][] NO_CHAR_CHAR = new char[0][]; + + /** + * Answers a hashcode for the array + * + * @param array the array for which a hashcode is required + * @return the hashcode + * @throws NullPointerException if array is null + */ + public static final int hashCode(char[] array) { + int length = array.length; + int hash = length == 0 ? 31 : array[0]; + if (length < 8) { + for (int i = length; --i > 0;) + hash = (hash * 31) + array[i]; + } else { + // 8 characters is enough to compute a decent hash code, don't waste time examining every character + for (int i = length - 1, last = i > 16 ? i - 16 : 0; i > last; i -= 2) + hash = (hash * 31) + array[i]; + } + return hash & 0x7FFFFFFF; + } + + /** + * Answers the last index in the array for which the corresponding character is + * equal to toBeFound starting from the end of the array. + * Answers -1 if no occurrence of this character is found. + *
    + *
    + * For example: + *
      + *
    1. +	 *    toBeFound = 'c'
      +	 *    array = { ' a', 'b', 'c', 'd' , 'c', 'e' }
      +	 *    result => 4
      +	 * 
      + *
    2. + *
    3. +	 *    toBeFound = 'e'
      +	 *    array = { ' a', 'b', 'c', 'd' }
      +	 *    result => -1
      +	 * 
      + *
    4. + *
    + * + * @param toBeFound the character to search + * @param array the array to be searched + * @return the last index in the array for which the corresponding character is + * equal to toBeFound starting from the end of the array, -1 otherwise + * @throws NullPointerException if array is null + */ + public static final int lastIndexOf(char toBeFound, char[] array) { + for (int i = array.length; --i >= 0;) + if (toBeFound == array[i]) + return i; + return -1; + } + + /** + * Return a new array which is the split of the given array using the given divider. + *
    + *
    + * For example: + *
      + *
    1. +	 *    divider = 'b'
      +	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
      +	 *    result => { { 'a' }, {  }, { 'a' }, { 'a' } }
      +	 * 
      + *
    2. + *
    3. +	 *    divider = 'c'
      +	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
      +	 *    result => { { 'a', 'b', 'b', 'a', 'b', 'a' } }
      +	 * 
      + *
    4. + *
    5. +	 *    divider = 'c'
      +	 *    array = { ' ', ' ', 'a' , 'b', 'b', 'a', 'b', 'a', ' ' }
      +	 *    result => { { ' ', 'a', 'b', 'b', 'a', 'b', 'a', ' ' } }
      +	 * 
      + *
    6. + *
    + * + * @param divider the given divider + * @param array the given array + * @return a new array which is the split of the given array using the given divider + */ + public static final char[][] splitOn(char divider, char[] array) { + int length = array == null ? 0 : array.length; + if (length == 0) + return NO_CHAR_CHAR; + + int wordCount = 1; + for (int i = 0; i < length; i++) + if (array[i] == divider) + wordCount++; + char[][] split = new char[wordCount][]; + int last = 0, currentWord = 0; + for (int i = 0; i < length; i++) { + if (array[i] == divider) { + split[currentWord] = new char[i - last]; + System.arraycopy(array, last, split[currentWord++], 0, i - last); + last = i + 1; + } + } + split[currentWord] = new char[length - last]; + System.arraycopy(array, last, split[currentWord], 0, length - last); + return split; + } + + /** + * Answers the first index in the array for which the corresponding character is + * equal to toBeFound starting the search at index start. + * Answers -1 if no occurrence of this character is found. + *
    + *
    + * For example: + *
      + *
    1. +	 *    toBeFound = 'c'
      +	 *    array = { ' a', 'b', 'c', 'd' }
      +	 *    start = 2
      +	 *    result => 2
      +	 * 
      + *
    2. + *
    3. +	 *    toBeFound = 'c'
      +	 *    array = { ' a', 'b', 'c', 'd' }
      +	 *    start = 3
      +	 *    result => -1
      +	 * 
      + *
    4. + *
    5. +	 *    toBeFound = 'e'
      +	 *    array = { ' a', 'b', 'c', 'd' }
      +	 *    start = 1
      +	 *    result => -1
      +	 * 
      + *
    6. + *
    + * + * @param toBeFound the character to search + * @param array the array to be searched + * @param start the starting index + * @return the first index in the array for which the corresponding character is + * equal to toBeFound, -1 otherwise + * @throws NullPointerException if array is null + * @throws ArrayIndexOutOfBoundsException if start is lower than 0 + */ + public static final int indexOf(char toBeFound, char[] array, int start) { + for (int i = start; i < array.length; i++) + if (toBeFound == array[i]) + return i; + return -1; + } + + /** + * Answers a new array with prepending the prefix character and appending the suffix + * character at the end of the array. If array is null, it answers a new array containing the + * prefix and the suffix characters. + *
    + *
    + * For example:
    + *
      + *
    1. +	 *    prefix = 'a'
      +	 *    array = { 'b' }
      +	 *    suffix = 'c'
      +	 *    => result = { 'a', 'b' , 'c' }
      +	 * 
      + *
    2. + *
    3. +	 *    prefix = 'a'
      +	 *    array = null
      +	 *    suffix = 'c'
      +	 *    => result = { 'a', 'c' }
      +	 * 
    4. + *
    + * + * @param prefix the prefix character + * @param array the array that is concatenated with the prefix and suffix characters + * @param suffix the suffix character + * @return the new array + */ + public static final char[] concat(char prefix, char[] array, char suffix) { + if (array == null) + return new char[] {prefix, suffix}; + + int length = array.length; + char[] result = new char[length + 2]; + result[0] = prefix; + System.arraycopy(array, 0, result, 1, length); + result[length + 1] = suffix; + return result; + } + + /** + * Answers the concatenation of the three arrays. It answers null if the three arrays are null. + * If first is null, it answers the concatenation of second and third. + * If second is null, it answers the concatenation of first and third. + * If third is null, it answers the concatenation of first and second. + *
    + *
    + * For example: + *
      + *
    1. +	 *    first = null
      +	 *    second = { 'a' }
      +	 *    third = { 'b' }
      +	 *    => result = { ' a', 'b' }
      +	 * 
      + *
    2. + *
    3. +	 *    first = { 'a' }
      +	 *    second = null
      +	 *    third = { 'b' }
      +	 *    => result = { ' a', 'b' }
      +	 * 
      + *
    4. + *
    5. +	 *    first = { 'a' }
      +	 *    second = { 'b' }
      +	 *    third = null
      +	 *    => result = { ' a', 'b' }
      +	 * 
      + *
    6. + *
    7. +	 *    first = null
      +	 *    second = null
      +	 *    third = null
      +	 *    => result = null
      +	 * 
      + *
    8. + *
    9. +	 *    first = { 'a' }
      +	 *    second = { 'b' }
      +	 *    third = { 'c' }
      +	 *    => result = { 'a', 'b', 'c' }
      +	 * 
      + *
    10. + *
    + * + * @param first the first array to concatenate + * @param second the second array to concatenate + * @param third the third array to concatenate + * + * @return the concatenation of the three arrays, or null if the three arrays are null. + */ + public static final char[] concat(char[] first, char[] second, char[] third) { + if (first == null) + return concat(second, third); + if (second == null) + return concat(first, third); + if (third == null) + return concat(first, second); + + int length1 = first.length; + int length2 = second.length; + int length3 = third.length; + char[] result = new char[length1 + length2 + length3]; + System.arraycopy(first, 0, result, 0, length1); + System.arraycopy(second, 0, result, length1, length2); + System.arraycopy(third, 0, result, length1 + length2, length3); + return result; + } + + /** + * Answers the concatenation of the two arrays. It answers null if the two arrays are null. + * If the first array is null, then the second array is returned. + * If the second array is null, then the first array is returned. + *
    + *
    + * For example: + *
      + *
    1. +	 *    first = null
      +	 *    second = { 'a' }
      +	 *    => result = { ' a' }
      +	 * 
      + *
    2. + *
    3. +	 *    first = { ' a' }
      +	 *    second = null
      +	 *    => result = { ' a' }
      +	 * 
      + *
    4. + *
    5. +	 *    first = { ' a' }
      +	 *    second = { ' b' }
      +	 *    => result = { ' a' , ' b' }
      +	 * 
      + *
    6. + *
    + * + * @param first the first array to concatenate + * @param second the second array to concatenate + * @return the concatenation of the two arrays, or null if the two arrays are null. + */ + public static final char[] concat(char[] first, char[] second) { + if (first == null) + return second; + if (second == null) + return first; + + int length1 = first.length; + int length2 = second.length; + char[] result = new char[length1 + length2]; + System.arraycopy(first, 0, result, 0, length1); + System.arraycopy(second, 0, result, length1, length2); + return result; + } + + /** + * Replace all occurrence of the character to be replaced with the replacement character in the + * given array. + *
    + *
    + * For example: + *
      + *
    1. +	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
      +	 *    toBeReplaced = 'b'
      +	 *    replacementChar = 'a'
      +	 *    result => No returned value, but array is now equals to { 'a' , 'a', 'a', 'a', 'a', 'a' }
      +	 * 
      + *
    2. + *
    3. +	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
      +	 *    toBeReplaced = 'c'
      +	 *    replacementChar = 'a'
      +	 *    result => No returned value, but array is now equals to { 'a' , 'b', 'b', 'a', 'b', 'a' }
      +	 * 
      + *
    4. + *
    + * + * @param array the given array + * @param toBeReplaced the character to be replaced + * @param replacementChar the replacement character + * @throws NullPointerException if the given array is null + */ + public static final void replace(char[] array, char toBeReplaced, char replacementChar) { + if (toBeReplaced != replacementChar) { + for (int i = 0, max = array.length; i < max; i++) { + if (array[i] == toBeReplaced) + array[i] = replacementChar; + } + } + } + + /** + * Replace all occurrence of the character to be replaced with the replacement character + * in a copy of the given array. Returns the given array if no occurrences of the character + * to be replaced are found. + *
    + *
    + * For example: + *
      + *
    1. +	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
      +	 *    toBeReplaced = 'b'
      +	 *    replacementChar = 'a'
      +	 *    result => A new array that is equals to { 'a' , 'a', 'a', 'a', 'a', 'a' }
      +	 * 
      + *
    2. + *
    3. +	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
      +	 *    toBeReplaced = 'c'
      +	 *    replacementChar = 'a'
      +	 *    result => The original array that remains unchanged.
      +	 * 
      + *
    4. + *
    + * + * @param array the given array + * @param toBeReplaced the character to be replaced + * @param replacementChar the replacement character + * @throws NullPointerException if the given array is null + * @since 3.1 + */ + public static final char[] replaceOnCopy(char[] array, char toBeReplaced, char replacementChar) { + + char[] result = null; + for (int i = 0, length = array.length; i < length; i++) { + char c = array[i]; + if (c == toBeReplaced) { + if (result == null) { + result = new char[length]; + System.arraycopy(array, 0, result, 0, i); + } + result[i] = replacementChar; + } else if (result != null) { + result[i] = c; + } + } + if (result == null) + return array; + return result; + } + + /** + * Answers the first index in the array for which the corresponding character is + * equal to toBeFound. Answers -1 if no occurrence of this character is found. + *
    + *
    + * For example: + *
      + *
    1. +	 *    toBeFound = 'c'
      +	 *    array = { ' a', 'b', 'c', 'd' }
      +	 *    result => 2
      +	 * 
      + *
    2. + *
    3. +	 *    toBeFound = 'e'
      +	 *    array = { ' a', 'b', 'c', 'd' }
      +	 *    result => -1
      +	 * 
      + *
    4. + *
    + * + * @param toBeFound the character to search + * @param array the array to be searched + * @return the first index in the array for which the corresponding character is + * equal to toBeFound, -1 otherwise + * @throws NullPointerException if array is null + */ + public static final int indexOf(char toBeFound, char[] array) { + return indexOf(toBeFound, array, 0); + } + + /** + * Answers a new array which is a copy of the given array starting at the given start and + * ending at the given end. The given start is inclusive and the given end is exclusive. + * Answers null if start is greater than end, if start is lower than 0 or if end is greater + * than the length of the given array. If end equals -1, it is converted to the array length. + *
    + *
    + * For example: + *
      + *
    1. +	 *    array = { 'a' , 'b' }
      +	 *    start = 0
      +	 *    end = 1
      +	 *    result => { 'a' }
      +	 * 
      + *
    2. + *
    3. +	 *    array = { 'a', 'b' }
      +	 *    start = 0
      +	 *    end = -1
      +	 *    result => { 'a' , 'b' }
      +	 * 
      + *
    4. + *
    + * + * @param array the given array + * @param start the given starting index + * @param end the given ending index + * @return a new array which is a copy of the given array starting at the given start and + * ending at the given end + * @throws NullPointerException if the given array is null + */ + public static final char[] subarray(char[] array, int start, int end) { + if (end == -1) + end = array.length; + if (start > end) + return null; + if (start < 0) + return null; + if (end > array.length) + return null; + + char[] result = new char[end - start]; + System.arraycopy(array, start, result, 0, end - start); + return result; + } + + /** + * Answers a new array which is a copy of the given array starting at the given start and + * ending at the given end. The given start is inclusive and the given end is exclusive. + * Answers null if start is greater than end, if start is lower than 0 or if end is greater + * than the length of the given array. If end equals -1, it is converted to the array length. + *
    + *
    + * For example: + *
      + *
    1. +	 *    array = { { 'a' } , { 'b' } }
      +	 *    start = 0
      +	 *    end = 1
      +	 *    result => { { 'a' } }
      +	 * 
      + *
    2. + *
    3. +	 *    array = { { 'a' } , { 'b' } }
      +	 *    start = 0
      +	 *    end = -1
      +	 *    result => { { 'a' }, { 'b' } }
      +	 * 
      + *
    4. + *
    + * + * @param array the given array + * @param start the given starting index + * @param end the given ending index + * @return a new array which is a copy of the given array starting at the given start and + * ending at the given end + * @throws NullPointerException if the given array is null + */ + public static final char[][] subarray(char[][] array, int start, int end) { + if (end == -1) + end = array.length; + if (start > end) + return null; + if (start < 0) + return null; + if (end > array.length) + return null; + + char[][] result = new char[end - start][]; + System.arraycopy(array, start, result, 0, end - start); + return result; + } + + /** + * Return a new array which is the split of the given array using the given divider. The given end + * is exclusive and the given start is inclusive. + *
    + *
    + * For example: + *
      + *
    1. +	 *    divider = 'b'
      +	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
      +	 *    start = 2
      +	 *    end = 5
      +	 *    result => { {  }, { 'a' }, {  } }
      +	 * 
      + *
    2. + *
    + * + * @param divider the given divider + * @param array the given array + * @param start the given starting index + * @param end the given ending index + * @return a new array which is the split of the given array using the given divider + * @throws ArrayIndexOutOfBoundsException if start is lower than 0 or end is greater than the array length + */ + public static final char[][] splitOn(char divider, char[] array, int start, int end) { + int length = array == null ? 0 : array.length; + if (length == 0 || start > end) + return NO_CHAR_CHAR; + + int wordCount = 1; + for (int i = start; i < end; i++) + if (array[i] == divider) + wordCount++; + char[][] split = new char[wordCount][]; + int last = start, currentWord = 0; + for (int i = start; i < end; i++) { + if (array[i] == divider) { + split[currentWord] = new char[i - last]; + System.arraycopy(array, last, split[currentWord++], 0, i - last); + last = i + 1; + } + } + split[currentWord] = new char[end - last]; + System.arraycopy(array, last, split[currentWord], 0, end - last); + return split; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFileAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFileAttribute.java new file mode 100644 index 000000000..bcc92e718 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFileAttribute.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class ClassFileAttribute extends ClassFileStruct { + public static final ClassFileAttribute[] NO_ATTRIBUTES = new ClassFileAttribute[0]; + private long attributeLength; + private int attributeNameIndex; + private char[] attributeName; + + public ClassFileAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + this.attributeNameIndex = u2At(classFileBytes, 0, offset); + this.attributeLength = u4At(classFileBytes, 2, offset); + ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(this.attributeNameIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.attributeName = constantPoolEntry.getUtf8Value(); + } + + public int getAttributeNameIndex() { + return this.attributeNameIndex; + } + + /* + * @see IClassFileAttribute#getAttributeName() + */ + public char[] getAttributeName() { + return this.attributeName; + } + + /* + * @see IClassFileAttribute#getAttributeLength() + */ + public long getAttributeLength() { + return this.attributeLength; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFileReader.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFileReader.java new file mode 100644 index 000000000..dea13cc34 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFileReader.java @@ -0,0 +1,468 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +import java.util.Arrays; + +public class ClassFileReader extends ClassFileStruct { + /* + * This value should be used to read completely each part of a .class file. + */ + public static final int ALL = 0xFFFF; + + /* + * This value should be used to read only the constant pool entries of a .class file. + */ + public static final int CONSTANT_POOL = 0x0001; + + /* + * This value should be used to read the constant pool entries and + * the method infos of a .class file. + */ + public static final int METHOD_INFOS = 0x0002 + CONSTANT_POOL; + + /* + * This value should be used to read the constant pool entries and + * the field infos of a .class file. + */ + public static final int FIELD_INFOS = 0x0004 + CONSTANT_POOL; + + /* + * This value should be used to read the constant pool entries and + * the super interface names of a .class file. + */ + public static final int SUPER_INTERFACES = 0x0008 + CONSTANT_POOL; + + /* + * This value should be used to read the constant pool entries and + * the attributes of a .class file. + */ + public static final int CLASSFILE_ATTRIBUTES = 0x0010 + CONSTANT_POOL; + + /* + * This value should be used to read the method bodies. + * It has to be used with METHOD_INFOS. + */ + public static final int METHOD_BODIES = 0x0020; + + /* + * This value should be used to read the whole contents of the .class file except the + * method bodies. + */ + public static final int ALL_BUT_METHOD_BODIES = ALL & ~METHOD_BODIES; + + private static final FieldInfo[] NO_FIELD_INFOS = new FieldInfo[0]; + private static final char[][] NO_INTERFACES_NAMES = CharOperation.NO_CHAR_CHAR; + private static final MethodInfo[] NO_METHOD_INFOS = new MethodInfo[0]; + private int accessFlags; + private ClassFileAttribute[] attributes; + private int attributesCount; + private char[] className; + private int classNameIndex; + + private ConstantPool constantPool; + private FieldInfo[] fields; + private int fieldsCount; + private InnerClassesAttribute innerClassesAttribute; + private int[] interfaceIndexes; + private char[][] interfaceNames; + private int interfacesCount; + private int magicNumber; + private int majorVersion; + private MethodInfo[] methods; + private int methodsCount; + private int minorVersion; + private SourceFileAttribute sourceFileAttribute; + private char[] superclassName; + private int superclassNameIndex; + + /* + * Constructor for ClassFileReader. + * + * @param classFileBytes the raw bytes of the .class file + * @param decodingFlags the decoding flags + * + * @see IClassFileReader#ALL + * @see IClassFileReader#CLASSFILE_ATTRIBUTES + * @see IClassFileReader#CONSTANT_POOL + * @see IClassFileReader#FIELD_INFOS + */ + public ClassFileReader(byte[] classFileBytes, int decodingFlags) throws ClassFormatException { + + // This method looks ugly but is actually quite simple, the constantPool is constructed + // in 3 passes. All non-primitive constant pool members that usually refer to other members + // by index are tweaked to have their value in inst vars, this minor cost at read-time makes + // all subsequent uses of the constant pool element faster. + int constantPoolCount; + int[] constantPoolOffsets; + try { + this.magicNumber = (int) u4At(classFileBytes, 0, 0); + if (this.magicNumber != 0xCAFEBABE) { + throw new ClassFormatException(ClassFormatException.INVALID_MAGIC_NUMBER); + } + + int readOffset = 10; + this.minorVersion = u2At(classFileBytes, 4, 0); + this.majorVersion = u2At(classFileBytes, 6, 0); + + if ((decodingFlags & CONSTANT_POOL) == 0) { + // no need to go further + return; + } + + constantPoolCount = u2At(classFileBytes, 8, 0); + // Pass #1 - Fill in all primitive constants + constantPoolOffsets = new int[constantPoolCount]; + for (int i = 1; i < constantPoolCount; i++) { + int tag = u1At(classFileBytes, readOffset, 0); + switch (tag) { + case ConstantPoolConstant.CONSTANT_Utf8 : + constantPoolOffsets[i] = readOffset; + readOffset += u2At(classFileBytes, readOffset + 1, 0); + readOffset += ConstantPoolConstant.CONSTANT_Utf8_SIZE; + break; + case ConstantPoolConstant.CONSTANT_Integer : + constantPoolOffsets[i] = readOffset; + readOffset += ConstantPoolConstant.CONSTANT_Integer_SIZE; + break; + case ConstantPoolConstant.CONSTANT_Float : + constantPoolOffsets[i] = readOffset; + readOffset += ConstantPoolConstant.CONSTANT_Float_SIZE; + break; + case ConstantPoolConstant.CONSTANT_Long : + constantPoolOffsets[i] = readOffset; + readOffset += ConstantPoolConstant.CONSTANT_Long_SIZE; + i++; + break; + case ConstantPoolConstant.CONSTANT_Double : + constantPoolOffsets[i] = readOffset; + readOffset += ConstantPoolConstant.CONSTANT_Double_SIZE; + i++; + break; + case ConstantPoolConstant.CONSTANT_Class : + constantPoolOffsets[i] = readOffset; + readOffset += ConstantPoolConstant.CONSTANT_Class_SIZE; + break; + case ConstantPoolConstant.CONSTANT_String : + constantPoolOffsets[i] = readOffset; + readOffset += ConstantPoolConstant.CONSTANT_String_SIZE; + break; + case ConstantPoolConstant.CONSTANT_Fieldref : + constantPoolOffsets[i] = readOffset; + readOffset += ConstantPoolConstant.CONSTANT_Fieldref_SIZE; + break; + case ConstantPoolConstant.CONSTANT_Methodref : + constantPoolOffsets[i] = readOffset; + readOffset += ConstantPoolConstant.CONSTANT_Methodref_SIZE; + break; + case ConstantPoolConstant.CONSTANT_InterfaceMethodref : + constantPoolOffsets[i] = readOffset; + readOffset += ConstantPoolConstant.CONSTANT_InterfaceMethodref_SIZE; + break; + case ConstantPoolConstant.CONSTANT_NameAndType : + constantPoolOffsets[i] = readOffset; + readOffset += ConstantPoolConstant.CONSTANT_NameAndType_SIZE; + break; + default : + throw new ClassFormatException(ClassFormatException.INVALID_TAG_CONSTANT); + } + } + + this.constantPool = new ConstantPool(classFileBytes, constantPoolOffsets); + // Read and validate access flags + this.accessFlags = u2At(classFileBytes, readOffset, 0); + readOffset += 2; + + // Read the classname, use exception handlers to catch bad format + this.classNameIndex = u2At(classFileBytes, readOffset, 0); + this.className = getConstantClassNameAt(classFileBytes, constantPoolOffsets, this.classNameIndex); + readOffset += 2; + + // Read the superclass name, can be zero for java.lang.Object + this.superclassNameIndex = u2At(classFileBytes, readOffset, 0); + readOffset += 2; + // if superclassNameIndex is equals to 0 there is no need to set a value for the + // field this.superclassName. null is fine. + if (this.superclassNameIndex != 0) { + this.superclassName = getConstantClassNameAt(classFileBytes, constantPoolOffsets, this.superclassNameIndex); + } + + // Read the interfaces, use exception handlers to catch bad format + this.interfacesCount = u2At(classFileBytes, readOffset, 0); + readOffset += 2; + this.interfaceNames = NO_INTERFACES_NAMES; + this.interfaceIndexes = Utility.EMPTY_INT_ARRAY; + if (this.interfacesCount != 0) { + if ((decodingFlags & SUPER_INTERFACES) != CONSTANT_POOL) { + this.interfaceNames = new char[this.interfacesCount][]; + this.interfaceIndexes = new int[this.interfacesCount]; + for (int i = 0; i < this.interfacesCount; i++) { + this.interfaceIndexes[i] = u2At(classFileBytes, readOffset, 0); + this.interfaceNames[i] = getConstantClassNameAt(classFileBytes, constantPoolOffsets, this.interfaceIndexes[i]); + readOffset += 2; + } + } else { + readOffset += (2 * this.interfacesCount); + } + } + // Read the this.fields, use exception handlers to catch bad format + this.fieldsCount = u2At(classFileBytes, readOffset, 0); + readOffset += 2; + this.fields = NO_FIELD_INFOS; + if (this.fieldsCount != 0) { + if ((decodingFlags & FIELD_INFOS) != CONSTANT_POOL) { + FieldInfo field; + this.fields = new FieldInfo[this.fieldsCount]; + for (int i = 0; i < this.fieldsCount; i++) { + field = new FieldInfo(classFileBytes, this.constantPool, readOffset); + this.fields[i] = field; + readOffset += field.sizeInBytes(); + } + } else { + for (int i = 0; i < this.fieldsCount; i++) { + int attributeCountForField = u2At(classFileBytes, 6, readOffset); + readOffset += 8; + if (attributeCountForField != 0) { + for (int j = 0; j < attributeCountForField; j++) { + int attributeLength = (int) u4At(classFileBytes, 2, readOffset); + readOffset += (6 + attributeLength); + } + } + } + } + } + // Read the this.methods + this.methodsCount = u2At(classFileBytes, readOffset, 0); + readOffset += 2; + this.methods = NO_METHOD_INFOS; + if (this.methodsCount != 0) { + if ((decodingFlags & METHOD_INFOS) != CONSTANT_POOL) { + this.methods = new MethodInfo[this.methodsCount]; + MethodInfo method; + for (int i = 0; i < this.methodsCount; i++) { + method = new MethodInfo(classFileBytes, this.constantPool, readOffset, decodingFlags); + this.methods[i] = method; + readOffset += method.sizeInBytes(); + } + } else { + for (int i = 0; i < this.methodsCount; i++) { + int attributeCountForMethod = u2At(classFileBytes, 6, readOffset); + readOffset += 8; + if (attributeCountForMethod != 0) { + for (int j = 0; j < attributeCountForMethod; j++) { + int attributeLength = (int) u4At(classFileBytes, 2, readOffset); + readOffset += (6 + attributeLength); + } + } + } + } + } + + // Read the attributes + this.attributesCount = u2At(classFileBytes, readOffset, 0); + readOffset += 2; + + int attributesIndex = 0; + this.attributes = ClassFileAttribute.NO_ATTRIBUTES; + if (this.attributesCount != 0) { + if ((decodingFlags & CLASSFILE_ATTRIBUTES) != CONSTANT_POOL) { + this.attributes = new ClassFileAttribute[this.attributesCount]; + for (int i = 0; i < this.attributesCount; i++) { + int utf8Offset = constantPoolOffsets[u2At(classFileBytes, readOffset, 0)]; + char[] attributeName = utf8At(classFileBytes, utf8Offset + 3, 0, u2At(classFileBytes, utf8Offset + 1, 0)); + if (Arrays.equals(attributeName, AttributeNamesConstants.INNER_CLASSES)) { + this.innerClassesAttribute = new InnerClassesAttribute(classFileBytes, this.constantPool, readOffset); + this.attributes[attributesIndex++] = this.innerClassesAttribute; + } else if (Arrays.equals(attributeName, AttributeNamesConstants.SOURCE)) { + this.sourceFileAttribute = new SourceFileAttribute(classFileBytes, this.constantPool, readOffset); + this.attributes[attributesIndex++] = this.sourceFileAttribute; + } else if (Arrays.equals(attributeName, AttributeNamesConstants.ENCLOSING_METHOD)) { + this.attributes[attributesIndex++] = new EnclosingMethodAttribute(classFileBytes, this.constantPool, readOffset); + } else if (Arrays.equals(attributeName, AttributeNamesConstants.SIGNATURE)) { + this.attributes[attributesIndex++] = new SignatureAttribute(classFileBytes, this.constantPool, readOffset); + } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_VISIBLE_ANNOTATIONS)) { + this.attributes[attributesIndex++] = new RuntimeVisibleAnnotationsAttribute(classFileBytes, this.constantPool, readOffset); + } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS)) { + this.attributes[attributesIndex++] = new RuntimeInvisibleAnnotationsAttribute(classFileBytes, this.constantPool, readOffset); + } else { + this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, this.constantPool, readOffset); + } + readOffset += (6 + u4At(classFileBytes, readOffset + 2, 0)); + } + } else { + for (int i = 0; i < this.attributesCount; i++) { + readOffset += (6 + u4At(classFileBytes, readOffset + 2, 0)); + } + } + } + if (readOffset != classFileBytes.length) { + throw new ClassFormatException(ClassFormatException.TOO_MANY_BYTES); + } + } catch (ClassFormatException e) { + throw e; + } catch (Exception e) { + e.printStackTrace(); + throw new ClassFormatException(ClassFormatException.ERROR_TRUNCATED_INPUT); + } + } + + /* + * @see IClassFileReader#getAccessFlags() + */ + public int getAccessFlags() { + return this.accessFlags; + } + + /* + * @see IClassFileReader#getAttributeCount() + */ + public int getAttributeCount() { + return this.attributesCount; + } + + /* + * @see IClassFileReader#getAttributes() + */ + public ClassFileAttribute[] getAttributes() { + return this.attributes; + } + + /* + * @see IClassFileReader#getClassIndex() + */ + public int getClassIndex() { + return this.classNameIndex; + } + + /* + * @see IClassFileReader#getClassName() + */ + public char[] getClassName() { + return this.className; + } + + private char[] getConstantClassNameAt(byte[] classFileBytes, int[] constantPoolOffsets, int constantPoolIndex) { + int utf8Offset = constantPoolOffsets[u2At(classFileBytes, constantPoolOffsets[constantPoolIndex] + 1, 0)]; + return utf8At(classFileBytes, utf8Offset + 3, 0, u2At(classFileBytes, utf8Offset + 1, 0)); + } + + /* + * @see IClassFileReader#getConstantPool() + */ + public ConstantPool getConstantPool() { + return this.constantPool; + } + + /* + * @see IClassFileReader#getFieldInfos() + */ + public FieldInfo[] getFieldInfos() { + return this.fields; + } + + /* + * @see IClassFileReader#getFieldsCount() + */ + public int getFieldsCount() { + return this.fieldsCount; + } + + /* + * @see IClassFileReader#getInnerClassesAttribute() + */ + public InnerClassesAttribute getInnerClassesAttribute() { + return this.innerClassesAttribute; + } + + /* + * @see IClassFileReader#getInterfaceIndexes() + */ + public int[] getInterfaceIndexes() { + return this.interfaceIndexes; + } + + /* + * @see IClassFileReader#getInterfaceNames() + */ + public char[][] getInterfaceNames() { + return this.interfaceNames; + } + + /* + * @see IClassFileReader#getMagic() + */ + public int getMagic() { + return this.magicNumber; + } + + /* + * @see IClassFileReader#getMajorVersion() + */ + public int getMajorVersion() { + return this.majorVersion; + } + + /* + * @see IClassFileReader#getMethodInfos() + */ + public MethodInfo[] getMethodInfos() { + return this.methods; + } + + /* + * @see IClassFileReader#getMethodsCount() + */ + public int getMethodsCount() { + return this.methodsCount; + } + + /* + * @see IClassFileReader#getMinorVersion() + */ + public int getMinorVersion() { + return this.minorVersion; + } + + /* + * @see IClassFileReader#getSourceFileAttribute() + */ + public SourceFileAttribute getSourceFileAttribute() { + return this.sourceFileAttribute; + } + + /* + * @see IClassFileReader#getSuperclassIndex() + */ + public int getSuperclassIndex() { + return this.superclassNameIndex; + } + + /* + * @see IClassFileReader#getSuperclassName() + */ + public char[] getSuperclassName() { + return this.superclassName; + } + + /* + * @see IClassFileReader#isClass() + */ + public boolean isClass() { + return !isInterface(); + } + + /* + * @see IClassFileReader#isInterface() + */ + public boolean isInterface() { + return (getAccessFlags() & IModifierConstants.ACC_INTERFACE) != 0; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFileStruct.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFileStruct.java new file mode 100644 index 000000000..24e4f6493 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFileStruct.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public abstract class ClassFileStruct { + + protected double doubleAt(byte[] reference, int relativeOffset, int structOffset) { + return (Double.longBitsToDouble(i8At(reference, relativeOffset, structOffset))); + } + + protected float floatAt(byte[] reference, int relativeOffset, int structOffset) { + return (Float.intBitsToFloat(i4At(reference, relativeOffset, structOffset))); + } + + protected int i1At(byte[] reference, int relativeOffset, int structOffset) { + return reference[relativeOffset + structOffset]; + } + + protected int i2At(byte[] reference, int relativeOffset, int structOffset) { + int position = relativeOffset + structOffset; + return (reference[position++] << 8) + (reference[position] & 0xFF); + } + + protected int i4At(byte[] reference, int relativeOffset, int structOffset) { + int position = relativeOffset + structOffset; + return ((reference[position++] & 0xFF) << 24) + ((reference[position++] & 0xFF) << 16) + ((reference[position++] & 0xFF) << 8) + (reference[position] & 0xFF); + } + + protected long i8At(byte[] reference, int relativeOffset, int structOffset) { + int position = relativeOffset + structOffset; + return (((long) (reference[position++] & 0xFF)) << 56) + (((long) (reference[position++] & 0xFF)) << 48) + (((long) (reference[position++] & 0xFF)) << 40) + (((long) (reference[position++] & 0xFF)) << 32) + (((long) (reference[position++] & 0xFF)) << 24) + (((long) (reference[position++] & 0xFF)) << 16) + (((long) (reference[position++] & 0xFF)) << 8) + (reference[position++] & 0xFF); + } + + protected int u1At(byte[] reference, int relativeOffset, int structOffset) { + return (reference[relativeOffset + structOffset] & 0xFF); + } + + protected int u2At(byte[] reference, int relativeOffset, int structOffset) { + int position = relativeOffset + structOffset; + return ((reference[position++] & 0xFF) << 8) + (reference[position] & 0xFF); + } + + protected long u4At(byte[] reference, int relativeOffset, int structOffset) { + int position = relativeOffset + structOffset; + return (((reference[position++] & 0xFFL) << 24) + ((reference[position++] & 0xFF) << 16) + ((reference[position++] & 0xFF) << 8) + (reference[position] & 0xFF)); + } + + protected char[] utf8At(byte[] reference, int relativeOffset, int structOffset, int bytesAvailable) { + int length = bytesAvailable; + char outputBuf[] = new char[bytesAvailable]; + int outputPos = 0; + int readOffset = structOffset + relativeOffset; + + while (length != 0) { + int x = reference[readOffset++] & 0xFF; + length--; + if ((0x80 & x) != 0) { + if ((x & 0x20) != 0) { + length -= 2; + x = ((x & 0xF) << 12) + ((reference[readOffset++] & 0x3F) << 6) + (reference[readOffset++] & 0x3F); + } else { + length--; + x = ((x & 0x1F) << 6) + (reference[readOffset++] & 0x3F); + } + } + outputBuf[outputPos++] = (char) x; + } + + if (outputPos != bytesAvailable) { + System.arraycopy(outputBuf, 0, (outputBuf = new char[outputPos]), 0, outputPos); + } + return outputBuf; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFormatException.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFormatException.java new file mode 100644 index 000000000..32d05426f --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ClassFormatException.java @@ -0,0 +1,59 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class ClassFormatException extends Exception { + + public static final int ERROR_MALFORMED_UTF8 = 1; + public static final int ERROR_TRUNCATED_INPUT = 2; + public static final int INVALID_CONSTANT_POOL_ENTRY = 3; + public static final int TOO_MANY_BYTES = 4; + public static final int INVALID_ARGUMENTS_FOR_INVOKEINTERFACE = 5; + public static final int INVALID_BYTECODE = 6; + + /** + * @since 3.0 + */ + public static final int INVALID_TAG_CONSTANT = 7; + + /** + * @since 3.0 + */ + public static final int INVALID_MAGIC_NUMBER = 8; + + private static final long serialVersionUID = 6582900558320612988L; // backward compatible + + /** + * Constructor for ClassFormatException. + * @param errorID the given error ID + */ + public ClassFormatException(int errorID) { + // TODO (olivier) what is the errorID? + } + + /** + * Constructor for ClassFormatException. + * @param message the message for the exception + */ + public ClassFormatException(String message) { + super(message); + } + + /** + * Constructor for ClassFormatException. + * @param message the message for the exception + * @param cause the cause of the exception + * @since 3.5 + */ + public ClassFormatException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/CodeAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/CodeAttribute.java new file mode 100644 index 000000000..70f5f3dc2 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/CodeAttribute.java @@ -0,0 +1,1114 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class CodeAttribute extends ClassFileAttribute { + private static final ExceptionTableEntry[] NO_EXCEPTION_TABLE = new ExceptionTableEntry[0]; + private ClassFileAttribute[] attributes; + private int attributesCount; + private byte[] bytecodes; + private byte[] classFileBytes; + private long codeLength; + private int codeOffset; + private ConstantPool constantPool; + private ExceptionTableEntry[] exceptionTableEntries; + private int exceptionTableLength; + private int maxLocals; + private int maxStack; + + CodeAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + super(classFileBytes, constantPool, offset); + this.classFileBytes = classFileBytes; + this.constantPool = constantPool; + this.maxStack = u2At(classFileBytes, 6, offset); + this.maxLocals = u2At(classFileBytes, 8, offset); + this.codeLength = u4At(classFileBytes, 10, offset); + this.codeOffset = offset + 14; + int readOffset = (int) (14 + this.codeLength); + this.exceptionTableLength = u2At(classFileBytes, readOffset, offset); + readOffset += 2; + this.exceptionTableEntries = NO_EXCEPTION_TABLE; + if (this.exceptionTableLength != 0) { + this.exceptionTableEntries = new ExceptionTableEntry[this.exceptionTableLength]; + for (int i = 0; i < this.exceptionTableLength; i++) { + this.exceptionTableEntries[i] = new ExceptionTableEntry(classFileBytes, constantPool, offset + readOffset); + readOffset += 8; + } + } + this.attributesCount = u2At(classFileBytes, readOffset, offset); + this.attributes = ClassFileAttribute.NO_ATTRIBUTES; + if (this.attributesCount != 0) { + this.attributes = new ClassFileAttribute[this.attributesCount]; + } + readOffset += 2; + for (int i = 0; i < this.attributesCount; i++) { + ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(u2At(classFileBytes, readOffset, offset)); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + readOffset += (6 + u4At(classFileBytes, readOffset + 2, offset)); + } + } + + /* + * @see ICodeAttribute#getAttributes() + */ + public ClassFileAttribute[] getAttributes() { + return this.attributes; + } + + /* + * @see ICodeAttribute#getAttributesCount() + */ + public int getAttributesCount() { + return this.attributesCount; + } + + /* + * @see ICodeAttribute#getBytecodes() + */ + public byte[] getBytecodes() { + if (this.bytecodes == null) { + System.arraycopy(this.classFileBytes, this.codeOffset, (this.bytecodes = new byte[(int) this.codeLength]), 0, (int) this.codeLength); + } + return this.bytecodes; + } + + /* + * @see ICodeAttribute#getCodeLength() + */ + public long getCodeLength() { + return this.codeLength; + } + + /* + * @see ICodeAttribute#getExceptionTable() + */ + public ExceptionTableEntry[] getExceptionTable() { + return this.exceptionTableEntries; + } + + /* + * @see ICodeAttribute#getExceptionTableLength() + */ + public int getExceptionTableLength() { + return this.exceptionTableLength; + } + + /* + * @see ICodeAttribute#getMaxLocals() + */ + public int getMaxLocals() { + return this.maxLocals; + } + + /* + * @see ICodeAttribute#getMaxStack() + */ + public int getMaxStack() { + return this.maxStack; + } + + /* + * @see ICodeAttribute#traverse(IBytecodeVisitor visitor) + */ + public void traverse(DefaultBytecodeVisitor visitor) throws ClassFormatException { + int pc = this.codeOffset; + int opcode, index, _const, branchOffset; + ConstantPoolEntry constantPoolEntry; + while (true) { + opcode = u1At(this.classFileBytes, 0, pc); + switch (opcode) { + case IOpcodeMnemonics.NOP : + visitor._nop(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ACONST_NULL : + visitor._aconst_null(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ICONST_M1 : + visitor._iconst_m1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ICONST_0 : + visitor._iconst_0(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ICONST_1 : + visitor._iconst_1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ICONST_2 : + visitor._iconst_2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ICONST_3 : + visitor._iconst_3(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ICONST_4 : + visitor._iconst_4(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ICONST_5 : + visitor._iconst_5(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LCONST_0 : + visitor._lconst_0(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LCONST_1 : + visitor._lconst_1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FCONST_0 : + visitor._fconst_0(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FCONST_1 : + visitor._fconst_1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FCONST_2 : + visitor._fconst_2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DCONST_0 : + visitor._dconst_0(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DCONST_1 : + visitor._dconst_1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.BIPUSH : + visitor._bipush(pc - this.codeOffset, (byte) i1At(this.classFileBytes, 1, pc)); + pc += 2; + break; + case IOpcodeMnemonics.SIPUSH : + visitor._sipush(pc - this.codeOffset, (short) i2At(this.classFileBytes, 1, pc)); + pc += 3; + break; + case IOpcodeMnemonics.LDC : + index = u1At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Float && constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Integer && constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_String && constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + visitor._ldc(pc - this.codeOffset, index, constantPoolEntry); + pc += 2; + break; + case IOpcodeMnemonics.LDC_W : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Float && constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Integer && constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_String && constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + visitor._ldc_w(pc - this.codeOffset, index, constantPoolEntry); + pc += 3; + break; + case IOpcodeMnemonics.LDC2_W : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Double && constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Long) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + visitor._ldc2_w(pc - this.codeOffset, index, constantPoolEntry); + pc += 3; + break; + case IOpcodeMnemonics.ILOAD : + index = u1At(this.classFileBytes, 1, pc); + visitor._iload(pc - this.codeOffset, index); + pc += 2; + break; + case IOpcodeMnemonics.LLOAD : + index = u1At(this.classFileBytes, 1, pc); + visitor._lload(pc - this.codeOffset, index); + pc += 2; + break; + case IOpcodeMnemonics.FLOAD : + index = u1At(this.classFileBytes, 1, pc); + visitor._fload(pc - this.codeOffset, index); + pc += 2; + break; + case IOpcodeMnemonics.DLOAD : + index = u1At(this.classFileBytes, 1, pc); + visitor._dload(pc - this.codeOffset, index); + pc += 2; + break; + case IOpcodeMnemonics.ALOAD : + index = u1At(this.classFileBytes, 1, pc); + visitor._aload(pc - this.codeOffset, index); + pc += 2; + break; + case IOpcodeMnemonics.ILOAD_0 : + visitor._iload_0(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ILOAD_1 : + visitor._iload_1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ILOAD_2 : + visitor._iload_2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ILOAD_3 : + visitor._iload_3(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LLOAD_0 : + visitor._lload_0(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LLOAD_1 : + visitor._lload_1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LLOAD_2 : + visitor._lload_2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LLOAD_3 : + visitor._lload_3(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FLOAD_0 : + visitor._fload_0(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FLOAD_1 : + visitor._fload_1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FLOAD_2 : + visitor._fload_2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FLOAD_3 : + visitor._fload_3(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DLOAD_0 : + visitor._dload_0(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DLOAD_1 : + visitor._dload_1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DLOAD_2 : + visitor._dload_2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DLOAD_3 : + visitor._dload_3(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ALOAD_0 : + visitor._aload_0(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ALOAD_1 : + visitor._aload_1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ALOAD_2 : + visitor._aload_2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ALOAD_3 : + visitor._aload_3(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.IALOAD : + visitor._iaload(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LALOAD : + visitor._laload(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FALOAD : + visitor._faload(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DALOAD : + visitor._daload(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.AALOAD : + visitor._aaload(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.BALOAD : + visitor._baload(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.CALOAD : + visitor._caload(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.SALOAD : + visitor._saload(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ISTORE : + index = u1At(this.classFileBytes, 1, pc); + visitor._istore(pc - this.codeOffset, index); + pc += 2; + break; + case IOpcodeMnemonics.LSTORE : + index = u1At(this.classFileBytes, 1, pc); + visitor._lstore(pc - this.codeOffset, index); + pc += 2; + break; + case IOpcodeMnemonics.FSTORE : + index = u1At(this.classFileBytes, 1, pc); + visitor._fstore(pc - this.codeOffset, index); + pc += 2; + break; + case IOpcodeMnemonics.DSTORE : + index = u1At(this.classFileBytes, 1, pc); + visitor._dstore(pc - this.codeOffset, index); + pc += 2; + break; + case IOpcodeMnemonics.ASTORE : + index = u1At(this.classFileBytes, 1, pc); + visitor._astore(pc - this.codeOffset, index); + pc += 2; + break; + case IOpcodeMnemonics.ISTORE_0 : + visitor._istore_0(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ISTORE_1 : + visitor._istore_1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ISTORE_2 : + visitor._istore_2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ISTORE_3 : + visitor._istore_3(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LSTORE_0 : + visitor._lstore_0(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LSTORE_1 : + visitor._lstore_1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LSTORE_2 : + visitor._lstore_2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LSTORE_3 : + visitor._lstore_3(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FSTORE_0 : + visitor._fstore_0(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FSTORE_1 : + visitor._fstore_1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FSTORE_2 : + visitor._fstore_2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FSTORE_3 : + visitor._fstore_3(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DSTORE_0 : + visitor._dstore_0(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DSTORE_1 : + visitor._dstore_1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DSTORE_2 : + visitor._dstore_2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DSTORE_3 : + visitor._dstore_3(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ASTORE_0 : + visitor._astore_0(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ASTORE_1 : + visitor._astore_1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ASTORE_2 : + visitor._astore_2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ASTORE_3 : + visitor._astore_3(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.IASTORE : + visitor._iastore(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LASTORE : + visitor._lastore(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FASTORE : + visitor._fastore(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DASTORE : + visitor._dastore(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.AASTORE : + visitor._aastore(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.BASTORE : + visitor._bastore(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.CASTORE : + visitor._castore(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.SASTORE : + visitor._sastore(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.POP : + visitor._pop(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.POP2 : + visitor._pop2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DUP : + visitor._dup(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DUP_X1 : + visitor._dup_x1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DUP_X2 : + visitor._dup_x2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DUP2 : + visitor._dup2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DUP2_X1 : + visitor._dup2_x1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DUP2_X2 : + visitor._dup2_x2(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.SWAP : + visitor._swap(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.IADD : + visitor._iadd(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LADD : + visitor._ladd(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FADD : + visitor._fadd(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DADD : + visitor._dadd(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ISUB : + visitor._isub(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LSUB : + visitor._lsub(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FSUB : + visitor._fsub(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DSUB : + visitor._dsub(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.IMUL : + visitor._imul(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LMUL : + visitor._lmul(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FMUL : + visitor._fmul(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DMUL : + visitor._dmul(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.IDIV : + visitor._idiv(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LDIV : + visitor._ldiv(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FDIV : + visitor._fdiv(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DDIV : + visitor._ddiv(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.IREM : + visitor._irem(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LREM : + visitor._lrem(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FREM : + visitor._frem(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DREM : + visitor._drem(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.INEG : + visitor._ineg(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LNEG : + visitor._lneg(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FNEG : + visitor._fneg(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DNEG : + visitor._dneg(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ISHL : + visitor._ishl(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LSHL : + visitor._lshl(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ISHR : + visitor._ishr(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LSHR : + visitor._lshr(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.IUSHR : + visitor._iushr(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LUSHR : + visitor._lushr(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.IAND : + visitor._iand(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LAND : + visitor._land(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.IOR : + visitor._ior(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LOR : + visitor._lor(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.IXOR : + visitor._ixor(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LXOR : + visitor._lxor(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.IINC : + index = u1At(this.classFileBytes, 1, pc); + _const = i1At(this.classFileBytes, 2, pc); + visitor._iinc(pc - this.codeOffset, index, _const); + pc += 3; + break; + case IOpcodeMnemonics.I2L : + visitor._i2l(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.I2F : + visitor._i2f(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.I2D : + visitor._i2d(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.L2I : + visitor._l2i(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.L2F : + visitor._l2f(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.L2D : + visitor._l2d(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.F2I : + visitor._f2i(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.F2L : + visitor._f2l(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.F2D : + visitor._f2d(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.D2I : + visitor._d2i(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.D2L : + visitor._d2l(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.D2F : + visitor._d2f(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.I2B : + visitor._i2b(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.I2C : + visitor._i2c(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.I2S : + visitor._i2s(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LCMP : + visitor._lcmp(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FCMPL : + visitor._fcmpl(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FCMPG : + visitor._fcmpg(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DCMPL : + visitor._dcmpl(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DCMPG : + visitor._dcmpg(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.IFEQ : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._ifeq(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.IFNE : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._ifne(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.IFLT : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._iflt(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.IFGE : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._ifge(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.IFGT : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._ifgt(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.IFLE : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._ifle(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.IF_ICMPEQ : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._if_icmpeq(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.IF_ICMPNE : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._if_icmpne(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.IF_ICMPLT : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._if_icmplt(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.IF_ICMPGE : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._if_icmpge(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.IF_ICMPGT : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._if_icmpgt(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.IF_ICMPLE : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._if_icmple(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.IF_ACMPEQ : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._if_acmpeq(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.IF_ACMPNE : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._if_acmpne(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.GOTO : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._goto(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.JSR : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._jsr(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.RET : + index = u1At(this.classFileBytes, 1, pc); + visitor._ret(pc - this.codeOffset, index); + pc += 2; + break; + case IOpcodeMnemonics.TABLESWITCH : + int startpc = pc; + pc++; + while (((pc - this.codeOffset) & 0x03) != 0) { // faster than % 4 + pc++; + } + int defaultOffset = i4At(this.classFileBytes, 0, pc); + pc += 4; + int low = i4At(this.classFileBytes, 0, pc); + pc += 4; + int high = i4At(this.classFileBytes, 0, pc); + pc += 4; + int length = high - low + 1; + int[] jumpOffsets = new int[length]; + for (int i = 0; i < length; i++) { + jumpOffsets[i] = i4At(this.classFileBytes, 0, pc); + pc += 4; + } + visitor._tableswitch(startpc - this.codeOffset, defaultOffset, low, high, jumpOffsets); + break; + case IOpcodeMnemonics.LOOKUPSWITCH : + startpc = pc; + pc++; + while (((pc - this.codeOffset) & 0x03) != 0) { + pc++; + } + defaultOffset = i4At(this.classFileBytes, 0, pc); + pc += 4; + int npairs = (int) u4At(this.classFileBytes, 0, pc); + int[][] offset_pairs = new int[npairs][2]; + pc += 4; + for (int i = 0; i < npairs; i++) { + offset_pairs[i][0] = i4At(this.classFileBytes, 0, pc); + pc += 4; + offset_pairs[i][1] = i4At(this.classFileBytes, 0, pc); + pc += 4; + } + visitor._lookupswitch(startpc - this.codeOffset, defaultOffset, npairs, offset_pairs); + break; + case IOpcodeMnemonics.IRETURN : + visitor._ireturn(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.LRETURN : + visitor._lreturn(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.FRETURN : + visitor._freturn(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.DRETURN : + visitor._dreturn(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ARETURN : + visitor._areturn(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.RETURN : + visitor._return(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.GETSTATIC : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Fieldref) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + visitor._getstatic(pc - this.codeOffset, index, constantPoolEntry); + pc += 3; + break; + case IOpcodeMnemonics.PUTSTATIC : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Fieldref) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + visitor._putstatic(pc - this.codeOffset, index, constantPoolEntry); + pc += 3; + break; + case IOpcodeMnemonics.GETFIELD : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Fieldref) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + visitor._getfield(pc - this.codeOffset, index, constantPoolEntry); + pc += 3; + break; + case IOpcodeMnemonics.PUTFIELD : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Fieldref) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + visitor._putfield(pc - this.codeOffset, index, constantPoolEntry); + pc += 3; + break; + case IOpcodeMnemonics.INVOKEVIRTUAL : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Methodref) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + visitor._invokevirtual(pc - this.codeOffset, index, constantPoolEntry); + pc += 3; + break; + case IOpcodeMnemonics.INVOKESPECIAL : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Methodref) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + visitor._invokespecial(pc - this.codeOffset, index, constantPoolEntry); + pc += 3; + break; + case IOpcodeMnemonics.INVOKESTATIC : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Methodref) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + visitor._invokestatic(pc - this.codeOffset, index, constantPoolEntry); + pc += 3; + break; + case IOpcodeMnemonics.INVOKEINTERFACE : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_InterfaceMethodref) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + byte count = (byte) u1At(this.classFileBytes, 3, pc); + int extraArgs = u1At(this.classFileBytes, 4, pc); + if (extraArgs != 0) { + throw new ClassFormatException(ClassFormatException.INVALID_ARGUMENTS_FOR_INVOKEINTERFACE); + } + visitor._invokeinterface(pc - this.codeOffset, index, count, constantPoolEntry); + pc += 5; + break; + case IOpcodeMnemonics.NEW : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + visitor._new(pc - this.codeOffset, index, constantPoolEntry); + pc += 3; + break; + case IOpcodeMnemonics.NEWARRAY : + int atype = u1At(this.classFileBytes, 1, pc); + visitor._newarray(pc - this.codeOffset, atype); + pc += 2; + break; + case IOpcodeMnemonics.ANEWARRAY : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + visitor._anewarray(pc - this.codeOffset, index, constantPoolEntry); + pc += 3; + break; + case IOpcodeMnemonics.ARRAYLENGTH : + visitor._arraylength(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.ATHROW : + visitor._athrow(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.CHECKCAST : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + visitor._checkcast(pc - this.codeOffset, index, constantPoolEntry); + pc += 3; + break; + case IOpcodeMnemonics.INSTANCEOF : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + visitor._instanceof(pc - this.codeOffset, index, constantPoolEntry); + pc += 3; + break; + case IOpcodeMnemonics.MONITORENTER : + visitor._monitorenter(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.MONITOREXIT : + visitor._monitorexit(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.WIDE : + opcode = u1At(this.classFileBytes, 1, pc); + if (opcode == IOpcodeMnemonics.IINC) { + index = u2At(this.classFileBytes, 2, pc); + _const = i2At(this.classFileBytes, 4, pc); + visitor._wide(pc - this.codeOffset, opcode, index, _const); + pc += 6; + } else { + index = u2At(this.classFileBytes, 2, pc); + visitor._wide(pc - this.codeOffset, opcode, index); + pc += 4; + } + break; + case IOpcodeMnemonics.MULTIANEWARRAY : + index = u2At(this.classFileBytes, 1, pc); + constantPoolEntry = this.constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + int dimensions = u1At(this.classFileBytes, 3, pc); + visitor._multianewarray(pc - this.codeOffset, index, dimensions, constantPoolEntry); + pc += 4; + break; + case IOpcodeMnemonics.IFNULL : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._ifnull(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.IFNONNULL : + branchOffset = i2At(this.classFileBytes, 1, pc); + visitor._ifnonnull(pc - this.codeOffset, branchOffset); + pc += 3; + break; + case IOpcodeMnemonics.GOTO_W : + branchOffset = i4At(this.classFileBytes, 1, pc); + visitor._goto_w(pc - this.codeOffset, branchOffset); + pc += 5; + break; + case IOpcodeMnemonics.JSR_W : + branchOffset = i4At(this.classFileBytes, 1, pc); + visitor._jsr_w(pc - this.codeOffset, branchOffset); + pc += 5; + break; + case IOpcodeMnemonics.BREAKPOINT : + visitor._breakpoint(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.IMPDEP1 : + visitor._impdep1(pc - this.codeOffset); + pc++; + break; + case IOpcodeMnemonics.IMPDEP2 : + visitor._impdep2(pc - this.codeOffset); + pc++; + break; + default : + throw new ClassFormatException(ClassFormatException.INVALID_BYTECODE); + } + if (pc >= (this.codeLength + this.codeOffset)) { + break; + } + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantPool.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantPool.java new file mode 100644 index 000000000..a6c585ab2 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantPool.java @@ -0,0 +1,104 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class ConstantPool extends ClassFileStruct { + + private int constantPoolCount; + private int[] constantPoolOffset; + private byte[] classFileBytes; + + ConstantPool(byte[] reference, int[] constantPoolOffset) { + this.constantPoolCount = constantPoolOffset.length; + this.constantPoolOffset = constantPoolOffset; + this.classFileBytes = reference; + } + + /* + * @see IConstantPool#decodeEntry(int) + */ + public ConstantPoolEntry decodeEntry(int index) { + ConstantPoolEntry constantPoolEntry = new ConstantPoolEntry(); + constantPoolEntry.reset(); + int kind = getEntryKind(index); + constantPoolEntry.setKind(kind); + switch (kind) { + case ConstantPoolConstant.CONSTANT_Class : + constantPoolEntry.setClassInfoNameIndex(u2At(this.classFileBytes, 1, this.constantPoolOffset[index])); + constantPoolEntry.setClassInfoName(getUtf8ValueAt(constantPoolEntry.getClassInfoNameIndex())); + break; + case ConstantPoolConstant.CONSTANT_Double : + constantPoolEntry.setDoubleValue(doubleAt(this.classFileBytes, 1, this.constantPoolOffset[index])); + break; + case ConstantPoolConstant.CONSTANT_Fieldref : + constantPoolEntry.setClassIndex(u2At(this.classFileBytes, 1, this.constantPoolOffset[index])); + int declaringClassIndex = u2At(this.classFileBytes, 1, this.constantPoolOffset[constantPoolEntry.getClassIndex()]); + constantPoolEntry.setClassName(getUtf8ValueAt(declaringClassIndex)); + constantPoolEntry.setNameAndTypeIndex(u2At(this.classFileBytes, 3, this.constantPoolOffset[index])); + int fieldNameIndex = u2At(this.classFileBytes, 1, this.constantPoolOffset[constantPoolEntry.getNameAndTypeIndex()]); + int fieldDescriptorIndex = u2At(this.classFileBytes, 3, this.constantPoolOffset[constantPoolEntry.getNameAndTypeIndex()]); + constantPoolEntry.setFieldName(getUtf8ValueAt(fieldNameIndex)); + constantPoolEntry.setFieldDescriptor(getUtf8ValueAt(fieldDescriptorIndex)); + break; + case ConstantPoolConstant.CONSTANT_Methodref : + case ConstantPoolConstant.CONSTANT_InterfaceMethodref : + constantPoolEntry.setClassIndex(u2At(this.classFileBytes, 1, this.constantPoolOffset[index])); + declaringClassIndex = u2At(this.classFileBytes, 1, this.constantPoolOffset[constantPoolEntry.getClassIndex()]); + constantPoolEntry.setClassName(getUtf8ValueAt(declaringClassIndex)); + constantPoolEntry.setNameAndTypeIndex(u2At(this.classFileBytes, 3, this.constantPoolOffset[index])); + int methodNameIndex = u2At(this.classFileBytes, 1, this.constantPoolOffset[constantPoolEntry.getNameAndTypeIndex()]); + int methodDescriptorIndex = u2At(this.classFileBytes, 3, this.constantPoolOffset[constantPoolEntry.getNameAndTypeIndex()]); + constantPoolEntry.setMethodName(getUtf8ValueAt(methodNameIndex)); + constantPoolEntry.setMethodDescriptor(getUtf8ValueAt(methodDescriptorIndex)); + break; + case ConstantPoolConstant.CONSTANT_Float : + constantPoolEntry.setFloatValue(floatAt(this.classFileBytes, 1, this.constantPoolOffset[index])); + break; + case ConstantPoolConstant.CONSTANT_Integer : + constantPoolEntry.setIntegerValue(i4At(this.classFileBytes, 1, this.constantPoolOffset[index])); + break; + case ConstantPoolConstant.CONSTANT_Long : + constantPoolEntry.setLongValue(i8At(this.classFileBytes, 1, this.constantPoolOffset[index])); + break; + case ConstantPoolConstant.CONSTANT_NameAndType : + constantPoolEntry.setNameAndTypeNameIndex(u2At(this.classFileBytes, 1, this.constantPoolOffset[index])); + constantPoolEntry.setNameAndTypeDescriptorIndex(u2At(this.classFileBytes, 3, this.constantPoolOffset[index])); + break; + case ConstantPoolConstant.CONSTANT_String : + constantPoolEntry.setStringIndex(u2At(this.classFileBytes, 1, this.constantPoolOffset[index])); + constantPoolEntry.setStringValue(getUtf8ValueAt(constantPoolEntry.getStringIndex())); + break; + case ConstantPoolConstant.CONSTANT_Utf8 : + constantPoolEntry.setUtf8Length(u2At(this.classFileBytes, 1, this.constantPoolOffset[index])); + constantPoolEntry.setUtf8Value(getUtf8ValueAt(index)); + } + return constantPoolEntry; + } + + /* + * @see IConstantPool#getConstantPoolCount() + */ + public int getConstantPoolCount() { + return this.constantPoolCount; + } + + /* + * @see IConstantPool#getEntryKind(int) + */ + public int getEntryKind(int index) { + return u1At(this.classFileBytes, 0, this.constantPoolOffset[index]); + } + + private char[] getUtf8ValueAt(int utf8Index) { + int utf8Offset = this.constantPoolOffset[utf8Index]; + return utf8At(this.classFileBytes, 0, utf8Offset + 3, u2At(this.classFileBytes, 0, utf8Offset + 1)); + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantPoolConstant.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantPoolConstant.java new file mode 100644 index 000000000..abc13b255 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantPoolConstant.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public interface ConstantPoolConstant { + + int CONSTANT_Class = 7; + int CONSTANT_Fieldref = 9; + int CONSTANT_Methodref = 10; + int CONSTANT_InterfaceMethodref = 11; + int CONSTANT_String = 8; + int CONSTANT_Integer = 3; + int CONSTANT_Float = 4; + int CONSTANT_Long = 5; + int CONSTANT_Double = 6; + int CONSTANT_NameAndType = 12; + int CONSTANT_Utf8 = 1; + + int CONSTANT_Methodref_SIZE = 5; + int CONSTANT_Class_SIZE = 3; + int CONSTANT_Double_SIZE = 9; + int CONSTANT_Fieldref_SIZE = 5; + int CONSTANT_Float_SIZE = 5; + int CONSTANT_Integer_SIZE = 5; + int CONSTANT_InterfaceMethodref_SIZE = 5; + int CONSTANT_Long_SIZE = 9; + int CONSTANT_String_SIZE = 3; + int CONSTANT_Utf8_SIZE = 3; + int CONSTANT_NameAndType_SIZE = 5; + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantPoolEntry.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantPoolEntry.java new file mode 100644 index 000000000..881356fce --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantPoolEntry.java @@ -0,0 +1,396 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class ConstantPoolEntry { + + private int kind; + private int classInfoNameIndex; + private int classIndex; + private int nameAndTypeIndex; + private int stringIndex; + private char[] stringValue; + private int integerValue; + private float floatValue; + private double doubleValue; + private long longValue; + private int nameAndTypeDescriptorIndex; + private int nameAndTypeNameIndex; + private char[] className; + private char[] fieldName; + private char[] methodName; + private char[] fieldDescriptor; + private char[] methodDescriptor; + private char[] utf8Value; + private int utf8Length; + private char[] classInfoName; + + public ConstantPoolEntry() { + this.classInfoNameIndex = -1; + this.classIndex = -1; + this.nameAndTypeIndex = -1; + this.stringIndex = -1; + this.stringValue = null; + this.integerValue = -1; + this.floatValue = -0.0f; + this.doubleValue = -0 - 0; + this.longValue = -1; + this.nameAndTypeDescriptorIndex = -1; + this.nameAndTypeNameIndex = -1; + this.className = null; + this.fieldName = null; + this.methodName = null; + this.fieldDescriptor = null; + this.methodDescriptor = null; + this.utf8Value = null; + this.utf8Length = -1; + this.classInfoName = null; + } + + /* + * @see IConstantPoolEntry#getKind() + */ + public int getKind() { + return this.kind; + } + + /* + * Sets the kind. + * @param kind The kind to set + */ + public void setKind(int kind) { + this.kind = kind; + } + + /* + * @see IConstantPoolEntry#getClassInfoNameIndex() + */ + public int getClassInfoNameIndex() { + return this.classInfoNameIndex; + } + + /* + * @see IConstantPoolEntry#getClassIndex() + */ + public int getClassIndex() { + return this.classIndex; + } + + /* + * @see IConstantPoolEntry#getNameAndTypeIndex() + */ + public int getNameAndTypeIndex() { + return this.nameAndTypeIndex; + } + + /* + * @see IConstantPoolEntry#getStringIndex() + */ + public int getStringIndex() { + return this.stringIndex; + } + + /* + * @see IConstantPoolEntry#getStringValue() + */ + public String getStringValue() { + return new String(this.stringValue); + } + + /* + * @see IConstantPoolEntry#getIntegerValue() + */ + public int getIntegerValue() { + return this.integerValue; + } + + /* + * @see IConstantPoolEntry#getFloatValue() + */ + public float getFloatValue() { + return this.floatValue; + } + + /* + * @see IConstantPoolEntry#getDoubleValue() + */ + public double getDoubleValue() { + return this.doubleValue; + } + + /* + * @see IConstantPoolEntry#getLongValue() + */ + public long getLongValue() { + return this.longValue; + } + + /* + * @see IConstantPoolEntry#getNameAndTypeInfoDescriptorIndex() + */ + public int getNameAndTypeInfoDescriptorIndex() { + return this.nameAndTypeDescriptorIndex; + } + + /* + * @see IConstantPoolEntry#getNameAndTypeInfoNameIndex() + */ + public int getNameAndTypeInfoNameIndex() { + return this.nameAndTypeNameIndex; + } + + /* + * @see IConstantPoolEntry#getClassName() + */ + public char[] getClassName() { + return this.className; + } + + /* + * @see IConstantPoolEntry#getFieldName() + */ + public char[] getFieldName() { + return this.fieldName; + } + + /* + * @see IConstantPoolEntry#getMethodName() + */ + public char[] getMethodName() { + return this.methodName; + } + + /* + * @see IConstantPoolEntry#getFieldDescriptor() + */ + public char[] getFieldDescriptor() { + return this.fieldDescriptor; + } + + /* + * @see IConstantPoolEntry#getMethodDescriptor() + */ + public char[] getMethodDescriptor() { + return this.methodDescriptor; + } + + /* + * @see IConstantPoolEntry#getUtf8Value() + */ + public char[] getUtf8Value() { + return this.utf8Value; + } + + /* + * @see IConstantPoolEntry#getClassInfoName() + */ + public char[] getClassInfoName() { + return this.classInfoName; + } + + /* + * Sets the classInfoNameIndex. + * @param classInfoNameIndex The classInfoNameIndex to set + */ + public void setClassInfoNameIndex(int classInfoNameIndex) { + this.classInfoNameIndex = classInfoNameIndex; + } + + /* + * Sets the classIndex. + * @param classIndex The classIndex to set + */ + public void setClassIndex(int classIndex) { + this.classIndex = classIndex; + } + + /* + * Sets the nameAndTypeIndex. + * @param nameAndTypeIndex The nameAndTypeIndex to set + */ + public void setNameAndTypeIndex(int nameAndTypeIndex) { + this.nameAndTypeIndex = nameAndTypeIndex; + } + + /* + * Sets the stringIndex. + * @param stringIndex The stringIndex to set + */ + public void setStringIndex(int stringIndex) { + this.stringIndex = stringIndex; + } + + /* + * Sets the stringValue. + * @param stringValue The stringValue to set + */ + public void setStringValue(char[] stringValue) { + this.stringValue = stringValue; + } + + /* + * Sets the integerValue. + * @param integerValue The integerValue to set + */ + public void setIntegerValue(int integerValue) { + this.integerValue = integerValue; + } + + /* + * Sets the floatValue. + * @param floatValue The floatValue to set + */ + public void setFloatValue(float floatValue) { + this.floatValue = floatValue; + } + + /* + * Sets the doubleValue. + * @param doubleValue The doubleValue to set + */ + public void setDoubleValue(double doubleValue) { + this.doubleValue = doubleValue; + } + + /* + * Sets the longValue. + * @param longValue The longValue to set + */ + public void setLongValue(long longValue) { + this.longValue = longValue; + } + + /* + * Gets the nameAndTypeDescriptorIndex. + * @return Returns a int + */ + public int getNameAndTypeDescriptorIndex() { + return this.nameAndTypeDescriptorIndex; + } + + /* + * Sets the nameAndTypeDescriptorIndex. + * @param nameAndTypeDescriptorIndex The nameAndTypeDescriptorIndex to set + */ + public void setNameAndTypeDescriptorIndex(int nameAndTypeDescriptorIndex) { + this.nameAndTypeDescriptorIndex = nameAndTypeDescriptorIndex; + } + + /* + * Gets the nameAndTypeNameIndex. + * @return Returns a int + */ + public int getNameAndTypeNameIndex() { + return this.nameAndTypeNameIndex; + } + + /* + * Sets the nameAndTypeNameIndex. + * @param nameAndTypeNameIndex The nameAndTypeNameIndex to set + */ + public void setNameAndTypeNameIndex(int nameAndTypeNameIndex) { + this.nameAndTypeNameIndex = nameAndTypeNameIndex; + } + + /* + * Sets the className. + * @param className The className to set + */ + public void setClassName(char[] className) { + this.className = className; + } + + /* + * Sets the fieldName. + * @param fieldName The fieldName to set + */ + public void setFieldName(char[] fieldName) { + this.fieldName = fieldName; + } + + /* + * Sets the methodName. + * @param methodName The methodName to set + */ + public void setMethodName(char[] methodName) { + this.methodName = methodName; + } + + /* + * Sets the fieldDescriptor. + * @param fieldDescriptor The fieldDescriptor to set + */ + public void setFieldDescriptor(char[] fieldDescriptor) { + this.fieldDescriptor = fieldDescriptor; + } + + /* + * Sets the methodDescriptor. + * @param methodDescriptor The methodDescriptor to set + */ + public void setMethodDescriptor(char[] methodDescriptor) { + this.methodDescriptor = methodDescriptor; + } + + /* + * Sets the utf8Value. + * @param utf8Value The utf8Value to set + */ + public void setUtf8Value(char[] utf8Value) { + this.utf8Value = utf8Value; + } + + /* + * Sets the classInfoName. + * @param classInfoName The classInfoName to set + */ + public void setClassInfoName(char[] classInfoName) { + this.classInfoName = classInfoName; + } + + /* + * @see IConstantPoolEntry#getUtf8Length() + */ + public int getUtf8Length() { + return this.utf8Length; + } + + /* + * Sets the utf8Length. + * @param utf8Length The utf8Length to set + */ + public void setUtf8Length(int utf8Length) { + this.utf8Length = utf8Length; + } + + public void reset() { + this.kind = 0; + this.classInfoNameIndex = 0; + this.classIndex = 0; + this.nameAndTypeIndex = 0; + this.stringIndex = 0; + this.stringValue = null; + this.integerValue = 0; + this.floatValue = 0.0f; + this.doubleValue = 0.0; + this.longValue = 0L; + this.nameAndTypeDescriptorIndex = 0; + this.nameAndTypeNameIndex = 0; + this.className = null; + this.fieldName = null; + this.methodName = null; + this.fieldDescriptor = null; + this.methodDescriptor = null; + this.utf8Value = null; + this.utf8Length = 0; + this.classInfoName = null; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantValueAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantValueAttribute.java new file mode 100644 index 000000000..cfc20ec56 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ConstantValueAttribute.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class ConstantValueAttribute extends ClassFileAttribute { + + private int constantValueIndex; + private ConstantPoolEntry constantPoolEntry; + + ConstantValueAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + super(classFileBytes, constantPool, offset); + this.constantValueIndex = u2At(classFileBytes, 6, offset); + this.constantPoolEntry = constantPool.decodeEntry(this.constantValueIndex); + } + + /* + * @see IConstantValueAttribute#getConstantValue() + */ + public ConstantPoolEntry getConstantValue() { + return this.constantPoolEntry; + } + + /* + * @see IConstantValueAttribute#getConstantValueIndex() + */ + public int getConstantValueIndex() { + return this.constantValueIndex; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/DefaultBytecodeVisitor.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/DefaultBytecodeVisitor.java new file mode 100644 index 000000000..90b8599a3 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/DefaultBytecodeVisitor.java @@ -0,0 +1,2071 @@ +/****************************************************************************** + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +import org.eclipse.osgi.util.NLS; + +public class DefaultBytecodeVisitor { + private static final String EMPTY_CLASS_NAME = "\"\""; //$NON-NLS-1$ + private static final String EMPTY_LOCAL_NAME = ""; //$NON-NLS-1$ + private static final int T_BOOLEAN = 4; + private static final int T_CHAR = 5; + private static final int T_FLOAT = 6; + private static final int T_DOUBLE = 7; + private static final int T_BYTE = 8; + private static final int T_SHORT = 9; + private static final int T_INT = 10; + private static final int T_LONG = 11; + + private StringBuffer buffer; + private String lineSeparator; + private int tabNumber; + private int digitNumberForPC; + private int mode; + + public DefaultBytecodeVisitor(CodeAttribute codeAttribute, char[] methodDescriptor, boolean isStatic, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + this.buffer = buffer; + this.lineSeparator = lineSeparator; + this.tabNumber = tabNumber + 1; + long codeLength = codeAttribute.getCodeLength(); + this.digitNumberForPC = Long.toString(codeLength).length(); + this.mode = mode; + } + + /* + * @see IBytecodeVisitor#_aaload(int) + */ + public void _aaload(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.AALOAD]); + writeNewLine(); + } + + private void dumpPcNumber(int pc) { + writeTabs(); + int digitForPC = 1; + if (pc != 0) { + digitForPC = Integer.toString(pc).length(); + } + for (int i = 0, max = this.digitNumberForPC - digitForPC; i < max; i++) { + this.buffer.append(' '); + } + this.buffer.append(pc); + this.buffer.append(Messages.disassembler_indentation); + } + + /* + * @see IBytecodeVisitor#_aastore(int) + */ + public void _aastore(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.AASTORE]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_aconst_null(int) + */ + public void _aconst_null(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ACONST_NULL]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_aload_0(int) + */ + public void _aload_0(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ALOAD_0], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_aload_1(int) + */ + public void _aload_1(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ALOAD_1], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_aload_2(int) + */ + public void _aload_2(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ALOAD_2], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_aload_3(int) + */ + public void _aload_3(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ALOAD_3], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_aload(int, int) + */ + public void _aload(int pc, int index) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ALOAD], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_anewarray(int, int, ConstantPoolEntry) + */ + public void _anewarray(int pc, int index, ConstantPoolEntry constantClass) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_anewarray, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ANEWARRAY], returnConstantClassName(constantClass)})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_areturn(int) + */ + public void _areturn(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ARETURN]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_arraylength(int) + */ + public void _arraylength(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ARRAYLENGTH]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_astore_0(int) + */ + public void _astore_0(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ASTORE_0], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_astore_1(int) + */ + public void _astore_1(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ASTORE_1], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_astore_2(int) + */ + public void _astore_2(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ASTORE_2], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_astore_3(int) + */ + public void _astore_3(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ASTORE_3], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_astore(int, int) + */ + public void _astore(int pc, int index) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ASTORE], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_athrow(int) + */ + public void _athrow(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ATHROW]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_baload(int) + */ + public void _baload(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.BALOAD]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_bastore(int) + */ + public void _bastore(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.BASTORE]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_bipush(int, byte) + */ + public void _bipush(int pc, byte _byte) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.BIPUSH]).append(Messages.disassembler_space).append(_byte); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_caload(int) + */ + public void _caload(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.CALOAD]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_castore(int) + */ + public void _castore(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.CASTORE]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_checkcast(int, int, ConstantPoolEntry) + */ + public void _checkcast(int pc, int index, ConstantPoolEntry constantClass) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_checkcast, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.CHECKCAST], returnConstantClassName(constantClass)})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_d2f(int) + */ + public void _d2f(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.D2F]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_d2i(int) + */ + public void _d2i(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.D2I]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_d2l(int) + */ + public void _d2l(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.D2L]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dadd(int) + */ + public void _dadd(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DADD]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_daload(int) + */ + public void _daload(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DALOAD]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dastore(int) + */ + public void _dastore(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DASTORE]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dcmpg(int) + */ + public void _dcmpg(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DCMPG]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dcmpl(int) + */ + public void _dcmpl(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DCMPL]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dconst_0(int) + */ + public void _dconst_0(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DCONST_0]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dconst_1(int) + */ + public void _dconst_1(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DCONST_1]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ddiv(int) + */ + public void _ddiv(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DDIV]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dload_0(int) + */ + public void _dload_0(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DLOAD_0], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dload_1(int) + */ + public void _dload_1(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DLOAD_1], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dload_2(int) + */ + public void _dload_2(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DLOAD_2], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dload_3(int) + */ + public void _dload_3(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DLOAD_3], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dload(int, int) + */ + public void _dload(int pc, int index) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DLOAD], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dmul(int) + */ + public void _dmul(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DMUL]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dneg(int) + */ + public void _dneg(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DNEG]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_drem(int) + */ + public void _drem(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DREM]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dreturn(int) + */ + public void _dreturn(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DRETURN]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dstore_0(int) + */ + public void _dstore_0(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DSTORE_0], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dstore_1(int) + */ + public void _dstore_1(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DSTORE_1], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dstore_2(int) + */ + public void _dstore_2(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DSTORE_2], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dstore_3(int) + */ + public void _dstore_3(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DSTORE_3], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dstore(int,int) + */ + public void _dstore(int pc, int index) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DSTORE], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dsub(int) + */ + public void _dsub(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DSUB]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dup_x1(int) + */ + public void _dup_x1(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DUP_X1]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dup_x2(int) + */ + public void _dup_x2(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DUP_X2]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dup(int) + */ + public void _dup(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DUP]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dup2_x1(int) + */ + public void _dup2_x1(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DUP2_X1]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dup2_x2(int) + */ + public void _dup2_x2(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DUP2_X2]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_dup2(int) + */ + public void _dup2(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.DUP2]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_f2d(int) + */ + public void _f2d(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.F2D]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_f2i(int) + */ + public void _f2i(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.F2I]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_f2l(int) + */ + public void _f2l(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.F2L]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fadd(int) + */ + public void _fadd(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FADD]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_faload(int) + */ + public void _faload(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FALOAD]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fastore(int) + */ + public void _fastore(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FASTORE]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fcmpg(int) + */ + public void _fcmpg(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FCMPG]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fcmpl(int) + */ + public void _fcmpl(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FCMPL]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fconst_0(int) + */ + public void _fconst_0(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FCONST_0]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fconst_1(int) + */ + public void _fconst_1(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FCONST_1]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fconst_2(int) + */ + public void _fconst_2(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FCONST_2]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fdiv(int) + */ + public void _fdiv(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FDIV]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fload_0(int) + */ + public void _fload_0(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FLOAD_0], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fload_1(int) + */ + public void _fload_1(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FLOAD_1], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fload_2(int) + */ + public void _fload_2(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FLOAD_2], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fload_3(int) + */ + public void _fload_3(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FLOAD_3], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fload(int, int) + */ + public void _fload(int pc, int index) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FLOAD], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fmul(int) + */ + public void _fmul(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FMUL]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fneg(int) + */ + public void _fneg(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FNEG]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_frem(int) + */ + public void _frem(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FREM]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_freturn(int) + */ + public void _freturn(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FRETURN]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fstore_0(int) + */ + public void _fstore_0(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FSTORE_0], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fstore_1(int) + */ + public void _fstore_1(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FSTORE_1], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fstore_2(int) + */ + public void _fstore_2(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FSTORE_2], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fstore_3(int) + */ + public void _fstore_3(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FSTORE_3], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fstore(int, int) + */ + public void _fstore(int pc, int index) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FSTORE], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_fsub(int) + */ + public void _fsub(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.FSUB]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_getfield(int, int, ConstantPoolEntry) + */ + public void _getfield(int pc, int index, ConstantPoolEntry constantFieldref) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_getfield, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.GETFIELD], returnDeclaringClassName(constantFieldref), new String(constantFieldref.getFieldName()), returnClassName(Signature.toCharArray(constantFieldref.getFieldDescriptor()))})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_getstatic(int, int, ConstantPoolEntry) + */ + public void _getstatic(int pc, int index, ConstantPoolEntry constantFieldref) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_getstatic, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.GETSTATIC], returnDeclaringClassName(constantFieldref), new String(constantFieldref.getFieldName()), returnClassName(Signature.toCharArray(constantFieldref.getFieldDescriptor()))})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_goto_w(int, int) + */ + public void _goto_w(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.GOTO_W]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_goto(int, int) + */ + public void _goto(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.GOTO]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_i2b(int) + */ + public void _i2b(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.I2B]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_i2c(int) + */ + public void _i2c(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.I2C]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_i2d(int) + */ + public void _i2d(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.I2D]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_i2f(int) + */ + public void _i2f(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.I2F]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_i2l(int) + */ + public void _i2l(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.I2L]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_i2s(int) + */ + public void _i2s(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.I2S]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iadd(int) + */ + public void _iadd(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IADD]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iaload(int) + */ + public void _iaload(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IALOAD]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iand(int) + */ + public void _iand(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IAND]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iastore(int) + */ + public void _iastore(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IASTORE]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_if_acmpeq(int, int) + */ + public void _if_acmpeq(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ACMPEQ]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_if_acmpne(int, int) + */ + public void _if_acmpne(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ACMPNE]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_if_icmpeq(int, int) + */ + public void _if_icmpeq(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ICMPEQ]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_if_icmpge(int, int) + */ + public void _if_icmpge(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ICMPGE]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_if_icmpgt(int, int) + */ + public void _if_icmpgt(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ICMPGT]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_if_icmple(int, int) + */ + public void _if_icmple(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ICMPLE]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_if_icmplt(int, int) + */ + public void _if_icmplt(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ICMPLT]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_if_icmpne(int, int) + */ + public void _if_icmpne(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IF_ICMPNE]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iconst_0(int) + */ + public void _iconst_0(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ICONST_0]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iconst_1(int) + */ + public void _iconst_1(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ICONST_1]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iconst_2(int) + */ + public void _iconst_2(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ICONST_2]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iconst_3(int) + */ + public void _iconst_3(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ICONST_3]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iconst_4(int) + */ + public void _iconst_4(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ICONST_4]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iconst_5(int) + */ + public void _iconst_5(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ICONST_5]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iconst_m1(int) + */ + public void _iconst_m1(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ICONST_M1]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_idiv(int) + */ + public void _idiv(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IDIV]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ifeq(int, int) + */ + public void _ifeq(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFEQ]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ifge(int, int) + */ + public void _ifge(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFGE]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ifgt(int, int) + */ + public void _ifgt(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFGT]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ifle(int, int) + */ + public void _ifle(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFLE]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iflt(int, int) + */ + public void _iflt(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFLT]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ifne(int, int) + */ + public void _ifne(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFNE]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ifnonnull(int, int) + */ + public void _ifnonnull(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFNONNULL]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ifnull(int, int) + */ + public void _ifnull(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IFNULL]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iinc(int, int, int) + */ + public void _iinc(int pc, int index, int _const) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_iinc, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IINC], Integer.toString(index), Integer.toString(_const), EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iload_0(int) + */ + public void _iload_0(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ILOAD_0], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iload_1(int) + */ + public void _iload_1(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ILOAD_1], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iload_2(int) + */ + public void _iload_2(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ILOAD_2], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iload_3(int) + */ + public void _iload_3(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ILOAD_3], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iload(int, int) + */ + public void _iload(int pc, int index) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ILOAD], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_imul(int) + */ + public void _imul(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IMUL]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ineg(int) + */ + public void _ineg(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.INEG]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_instanceof(int, int, ConstantPoolEntry) + */ + public void _instanceof(int pc, int index, ConstantPoolEntry constantClass) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_instanceof, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.INSTANCEOF], returnConstantClassName(constantClass)})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_invokeinterface(int, int, byte, ConstantPoolEntry) + */ + public void _invokeinterface(int pc, int index, byte nargs, ConstantPoolEntry constantInterfaceMethodref) { + + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_invokeinterface, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.INVOKEINTERFACE], Integer.toString(nargs), Utility.toString(constantInterfaceMethodref.getClassName(), constantInterfaceMethodref.getMethodName(), constantInterfaceMethodref.getMethodDescriptor(), true, isCompact())})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_invokespecial(int, int, ConstantPoolEntry) + */ + public void _invokespecial(int pc, int index, ConstantPoolEntry constantMethodref) { + dumpPcNumber(pc); + final String signature = returnMethodSignature(constantMethodref); + this.buffer.append(NLS.bind(Messages.classformat_invokespecial, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.INVOKESPECIAL], signature})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_invokestatic(int, int, ConstantPoolEntry) + */ + public void _invokestatic(int pc, int index, ConstantPoolEntry constantMethodref) { + dumpPcNumber(pc); + final String signature = returnMethodSignature(constantMethodref); + this.buffer.append(NLS.bind(Messages.classformat_invokestatic, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.INVOKESTATIC], signature})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_invokevirtual(int, int, ConstantPoolEntry) + */ + public void _invokevirtual(int pc, int index, ConstantPoolEntry constantMethodref) { + dumpPcNumber(pc); + final String signature = returnMethodSignature(constantMethodref); + this.buffer.append(NLS.bind(Messages.classformat_invokevirtual, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.INVOKEVIRTUAL], signature})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ior(int) + */ + public void _ior(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IOR]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_irem(int) + */ + public void _irem(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IREM]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ireturn(int) + */ + public void _ireturn(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IRETURN]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ishl(int) + */ + public void _ishl(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISHL]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ishr(int) + */ + public void _ishr(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISHR]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_istore_0(int) + */ + public void _istore_0(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISTORE_0], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_istore_1(int) + */ + public void _istore_1(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISTORE_1], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_istore_2(int) + */ + public void _istore_2(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISTORE_2], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_istore_3(int) + */ + public void _istore_3(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISTORE_3], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_istore(int, int) + */ + public void _istore(int pc, int index) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISTORE], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_isub(int) + */ + public void _isub(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.ISUB]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_iushr(int) + */ + public void _iushr(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IUSHR]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ixor(int) + */ + public void _ixor(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IXOR]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_jsr_w(int, int) + */ + public void _jsr_w(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.JSR_W]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_jsr(int, int) + */ + public void _jsr(int pc, int branchOffset) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.JSR]).append(Messages.disassembler_space).append(branchOffset + pc); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_l2d(int) + */ + public void _l2d(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.L2D]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_l2f(int) + */ + public void _l2f(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.L2F]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_l2i(int) + */ + public void _l2i(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.L2I]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ladd(int) + */ + public void _ladd(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LADD]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_laload(int) + */ + public void _laload(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LALOAD]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_land(int) + */ + public void _land(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LAND]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lastore(int) + */ + public void _lastore(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LASTORE]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lcmp(int) + */ + public void _lcmp(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LCMP]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lconst_0(int) + */ + public void _lconst_0(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LCONST_0]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lconst_1(int) + */ + public void _lconst_1(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LCONST_1]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ldc_w(int, int, ConstantPoolEntry) + */ + public void _ldc_w(int pc, int index, ConstantPoolEntry constantPoolEntry) { + dumpPcNumber(pc); + switch (constantPoolEntry.getKind()) { + case ConstantPoolConstant.CONSTANT_Float : + this.buffer.append(NLS.bind(Messages.classformat_ldc_w_float, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC_W], Float.toString(constantPoolEntry.getFloatValue())})); + break; + case ConstantPoolConstant.CONSTANT_Integer : + this.buffer.append(NLS.bind(Messages.classformat_ldc_w_integer, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC_W], Integer.toString(constantPoolEntry.getIntegerValue())})); + break; + case ConstantPoolConstant.CONSTANT_String : + this.buffer.append(NLS.bind(Messages.classformat_ldc_w_string, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC_W], Disassembler.escapeString(constantPoolEntry.getStringValue())})); + break; + case ConstantPoolConstant.CONSTANT_Class : + this.buffer.append(NLS.bind(Messages.classformat_ldc_w_class, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC_W], returnConstantClassName(constantPoolEntry)})); + } + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ldc(int, int, ConstantPoolEntry) + */ + public void _ldc(int pc, int index, ConstantPoolEntry constantPoolEntry) { + dumpPcNumber(pc); + switch (constantPoolEntry.getKind()) { + case ConstantPoolConstant.CONSTANT_Float : + this.buffer.append(NLS.bind(Messages.classformat_ldc_w_float, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC], Float.toString(constantPoolEntry.getFloatValue())})); + break; + case ConstantPoolConstant.CONSTANT_Integer : + this.buffer.append(NLS.bind(Messages.classformat_ldc_w_integer, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC], Integer.toString(constantPoolEntry.getIntegerValue())})); + break; + case ConstantPoolConstant.CONSTANT_String : + this.buffer.append(NLS.bind(Messages.classformat_ldc_w_string, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC], Disassembler.escapeString(constantPoolEntry.getStringValue())})); + break; + case ConstantPoolConstant.CONSTANT_Class : + this.buffer.append(NLS.bind(Messages.classformat_ldc_w_class, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC], returnConstantClassName(constantPoolEntry)})); + } + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ldc2_w(int, int, ConstantPoolEntry) + */ + public void _ldc2_w(int pc, int index, ConstantPoolEntry constantPoolEntry) { + dumpPcNumber(pc); + switch (constantPoolEntry.getKind()) { + case ConstantPoolConstant.CONSTANT_Long : + this.buffer.append(NLS.bind(Messages.classformat_ldc2_w_long, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC2_W], Long.toString(constantPoolEntry.getLongValue())})); + break; + case ConstantPoolConstant.CONSTANT_Double : + this.buffer.append(NLS.bind(Messages.classformat_ldc2_w_double, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDC2_W], Double.toString(constantPoolEntry.getDoubleValue())})); + } + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ldiv(int) + */ + public void _ldiv(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LDIV]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lload_0(int) + */ + public void _lload_0(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LLOAD_0], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lload_1(int) + */ + public void _lload_1(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LLOAD_1], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lload_2(int) + */ + public void _lload_2(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LLOAD_2], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lload_3(int) + */ + public void _lload_3(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LLOAD_3], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lload(int, int) + */ + public void _lload(int pc, int index) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_load, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LLOAD], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lmul(int) + */ + public void _lmul(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LMUL]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lneg(int) + */ + public void _lneg(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LNEG]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lookupswitch(int, int, int, int[][]) + */ + public void _lookupswitch(int pc, int defaultoffset, int npairs, int[][] offset_pairs) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LOOKUPSWITCH]).append(" default: ") //$NON-NLS-1$ + .append(defaultoffset + pc); + writeNewLine(); + for (int i = 0; i < npairs; i++) { + writeExtraTabs(3); + this.buffer.append("case ") //$NON-NLS-1$ + .append(offset_pairs[i][0]).append(": ") //$NON-NLS-1$ + .append(offset_pairs[i][1] + pc); + writeNewLine(); + } + } + + /* + * @see IBytecodeVisitor#_lor(int) + */ + public void _lor(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LOR]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lrem(int) + */ + public void _lrem(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LREM]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lreturn(int) + */ + public void _lreturn(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LRETURN]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lshl(int) + */ + public void _lshl(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSHL]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lshr(int) + */ + public void _lshr(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSHR]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lstore_0(int) + */ + public void _lstore_0(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSTORE_0], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lstore_1(int) + */ + public void _lstore_1(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSTORE_1], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lstore_2(int) + */ + public void _lstore_2(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSTORE_2], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lstore_3(int) + */ + public void _lstore_3(int pc) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSTORE_3], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lstore(int, int) + */ + public void _lstore(int pc, int index) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_store, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSTORE], EMPTY_LOCAL_NAME})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lsub(int) + */ + public void _lsub(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LSUB]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lushr(int) + */ + public void _lushr(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LUSHR]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_lxor(int) + */ + public void _lxor(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.LXOR]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_monitorenter(int) + */ + public void _monitorenter(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.MONITORENTER]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_monitorexit(int) + */ + public void _monitorexit(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.MONITOREXIT]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_multianewarray(int, int, int, ConstantPoolEntry) + */ + public void _multianewarray(int pc, int index, int dimensions, ConstantPoolEntry constantClass) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_multianewarray, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.MULTIANEWARRAY], returnConstantClassName(constantClass)})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_new(int, int, ConstantPoolEntry) + */ + public void _new(int pc, int index, ConstantPoolEntry constantClass) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_new, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEW], returnConstantClassName(constantClass)})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_newarray(int, int) + */ + public void _newarray(int pc, int atype) { + dumpPcNumber(pc); + switch (atype) { + case T_BOOLEAN : + this.buffer.append(NLS.bind(Messages.classformat_newarray_boolean, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); + break; + case T_CHAR : + this.buffer.append(NLS.bind(Messages.classformat_newarray_char, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); + break; + case T_FLOAT : + this.buffer.append(NLS.bind(Messages.classformat_newarray_float, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); + break; + case T_DOUBLE : + this.buffer.append(NLS.bind(Messages.classformat_newarray_double, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); + break; + case T_BYTE : + this.buffer.append(NLS.bind(Messages.classformat_newarray_byte, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); + break; + case T_SHORT : + this.buffer.append(NLS.bind(Messages.classformat_newarray_short, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); + break; + case T_INT : + this.buffer.append(NLS.bind(Messages.classformat_newarray_int, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); + break; + case T_LONG : + this.buffer.append(NLS.bind(Messages.classformat_newarray_long, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NEWARRAY], Integer.toString(atype)})); + } + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_nop(int) + */ + public void _nop(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.NOP]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_pop(int) + */ + public void _pop(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.POP]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_pop2(int) + */ + public void _pop2(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.POP2]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_putfield(int, int, ConstantPoolEntry) + */ + public void _putfield(int pc, int index, ConstantPoolEntry constantFieldref) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_putfield, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.PUTFIELD], returnDeclaringClassName(constantFieldref), new String(constantFieldref.getFieldName()), returnClassName(Signature.toCharArray(constantFieldref.getFieldDescriptor()))})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_putstatic(int, int, ConstantPoolEntry) + */ + public void _putstatic(int pc, int index, ConstantPoolEntry constantFieldref) { + dumpPcNumber(pc); + this.buffer.append(NLS.bind(Messages.classformat_putstatic, new String[] {OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.PUTSTATIC], returnDeclaringClassName(constantFieldref), new String(constantFieldref.getFieldName()), returnClassName(Signature.toCharArray(constantFieldref.getFieldDescriptor()))})); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_ret(int, int) + */ + public void _ret(int pc, int index) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.RET]).append(Messages.disassembler_space).append(index); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_return(int) + */ + public void _return(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.RETURN]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_saload(int) + */ + public void _saload(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.SALOAD]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_sastore(int) + */ + public void _sastore(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.SASTORE]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_sipush(int, short) + */ + public void _sipush(int pc, short value) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.SIPUSH]).append(Messages.disassembler_space).append(value); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_swap(int) + */ + public void _swap(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.SWAP]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_tableswitch(int, int, int, int, int[]) + */ + public void _tableswitch(int pc, int defaultoffset, int low, int high, int[] jump_offsets) { + + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.TABLESWITCH]).append(" default: ") //$NON-NLS-1$ + .append(defaultoffset + pc); + writeNewLine(); + for (int i = low; i < high + 1; i++) { + writeExtraTabs(3); + this.buffer.append("case ") //$NON-NLS-1$ + .append(i).append(": ") //$NON-NLS-1$ + .append(jump_offsets[i - low] + pc); + writeNewLine(); + } + } + + /* + * @see IBytecodeVisitor#_wide(int, int, int) + */ + public void _wide(int pc, int iincopcode, int index, int _const) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.WIDE]); + writeNewLine(); + _iinc(pc + 1, index, _const); + } + + /* + * @see IBytecodeVisitor#_wide(int, int, int) + */ + public void _wide(int pc, int opcode, int index) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.WIDE]); + writeNewLine(); + switch (opcode) { + case IOpcodeMnemonics.ILOAD : + _iload(pc + 1, index); + break; + case IOpcodeMnemonics.FLOAD : + _fload(pc + 1, index); + break; + case IOpcodeMnemonics.ALOAD : + _aload(pc + 1, index); + break; + case IOpcodeMnemonics.LLOAD : + _lload(pc + 1, index); + break; + case IOpcodeMnemonics.DLOAD : + _dload(pc + 1, index); + break; + case IOpcodeMnemonics.ISTORE : + _istore(pc + 1, index); + break; + case IOpcodeMnemonics.FSTORE : + _fstore(pc + 1, index); + break; + case IOpcodeMnemonics.ASTORE : + _astore(pc + 1, index); + break; + case IOpcodeMnemonics.LSTORE : + _lstore(pc + 1, index); + break; + case IOpcodeMnemonics.DSTORE : + _dstore(pc + 1, index); + break; + case IOpcodeMnemonics.RET : + _ret(pc + 1, index); + } + } + + /* + * @see IBytecodeVisitor#_breakpoint(int) + */ + public void _breakpoint(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.BREAKPOINT]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_impdep1(int) + */ + public void _impdep1(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IMPDEP1]); + writeNewLine(); + } + + /* + * @see IBytecodeVisitor#_impdep2(int) + */ + public void _impdep2(int pc) { + dumpPcNumber(pc); + this.buffer.append(OpcodeStringValues.BYTECODE_NAMES[IOpcodeMnemonics.IMPDEP2]); + writeNewLine(); + } + + private boolean isCompact() { + return (this.mode & Disassembler.COMPACT) != 0; + } + + private String returnConstantClassName(ConstantPoolEntry constantClass) { + char[] className = constantClass.getClassInfoName(); + if (className.length == 0) { + return EMPTY_CLASS_NAME; + } + switch (className[0]) { + case '[' : + StringBuffer classNameBuffer = new StringBuffer(); + Utility.appendTypeSignature(className, 0, classNameBuffer, isCompact()); + return classNameBuffer.toString(); + default : + return returnClassName(className); + } + } + + private String returnClassName(char[] classInfoName) { + if (classInfoName.length == 0) { + return EMPTY_CLASS_NAME; + } else if (isCompact()) { + int lastIndexOfSlash = CharOperation.lastIndexOf('/', classInfoName); + if (lastIndexOfSlash != -1) { + return new String(classInfoName, lastIndexOfSlash + 1, classInfoName.length - lastIndexOfSlash - 1); + } + } + CharOperation.replace(classInfoName, '/', '.'); + return new String(classInfoName); + } + + private String returnDeclaringClassName(ConstantPoolEntry constantRef) { + final char[] className = constantRef.getClassName(); + return returnClassName(className); + } + + private String returnMethodSignature(ConstantPoolEntry constantMethodref) { + final char[] methodDescriptor = constantMethodref.getMethodDescriptor(); + CharOperation.replace(methodDescriptor, '$', '#'); + final char[] signature = Utility.toString(constantMethodref.getClassName(), constantMethodref.getMethodName(), methodDescriptor, true, isCompact()).toCharArray(); + CharOperation.replace(signature, '#', '$'); + return String.valueOf(signature); + } + + private void writeNewLine() { + this.buffer.append(this.lineSeparator); + } + + private void writeTabs() { + for (int i = 0, max = this.tabNumber; i < max; i++) { + this.buffer.append(Messages.disassembler_indentation); + } + } + + private void writeExtraTabs(int extraTabs) { + for (int i = 0, max = this.tabNumber + extraTabs; i < max; i++) { + this.buffer.append(Messages.disassembler_indentation); + } + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Disassembler.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Disassembler.java new file mode 100644 index 000000000..69a9bfb3c --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Disassembler.java @@ -0,0 +1,1145 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +import java.util.Arrays; +import java.util.Comparator; +import org.eclipse.osgi.util.NLS; + +/** + * Disassembler of .class files. It generates an output in the Writer that looks close to + * the javap output. + */ +public class Disassembler { + /** + * The mode is the detailed mode to disassemble ClassFileReader. It returns the magic + * numbers, the version numbers and field and method descriptors. + */ + public final static int DETAILED = 1; + + /** + * This mode is used to compact the class name to a simple name instead of a qualified name. + * @since 3.1 + */ + public final static int COMPACT = 8; + + private static final char[] ANY_EXCEPTION = Messages.classfileformat_anyexceptionhandler.toCharArray(); + private static final String VERSION_UNKNOWN = Messages.classfileformat_versionUnknown; + + private boolean appendModifier(StringBuffer buffer, int accessFlags, int modifierConstant, String modifier, boolean firstModifier) { + if ((accessFlags & modifierConstant) != 0) { + if (!firstModifier) { + buffer.append(Messages.disassembler_space); + } + if (firstModifier) { + firstModifier = false; + } + buffer.append(modifier); + } + return firstModifier; + } + + private void decodeModifiers(StringBuffer buffer, int accessFlags, int[] checkBits) { + decodeModifiers(buffer, accessFlags, false, false, checkBits); + } + + private void decodeModifiers(StringBuffer buffer, int accessFlags, boolean printDefault, boolean asBridge, int[] checkBits) { + if (checkBits == null) + return; + boolean firstModifier = true; + for (int i = 0, max = checkBits.length; i < max; i++) { + switch (checkBits[i]) { + case IModifierConstants.ACC_PUBLIC : + firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_PUBLIC, "public", firstModifier); //$NON-NLS-1$ + break; + case IModifierConstants.ACC_PROTECTED : + firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_PROTECTED, "protected", firstModifier); //$NON-NLS-1$ + break; + case IModifierConstants.ACC_PRIVATE : + firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_PRIVATE, "private", firstModifier); //$NON-NLS-1$ + break; + case IModifierConstants.ACC_ABSTRACT : + firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_ABSTRACT, "abstract", firstModifier); //$NON-NLS-1$ + break; + case IModifierConstants.ACC_STATIC : + firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_STATIC, "static", firstModifier); //$NON-NLS-1$ + break; + case IModifierConstants.ACC_FINAL : + firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_FINAL, "final", firstModifier); //$NON-NLS-1$ + break; + case IModifierConstants.ACC_SYNCHRONIZED : + firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_SYNCHRONIZED, "synchronized", firstModifier); //$NON-NLS-1$ + break; + case IModifierConstants.ACC_NATIVE : + firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_NATIVE, "native", firstModifier); //$NON-NLS-1$ + break; + case IModifierConstants.ACC_STRICT : + firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_STRICT, "strictfp", firstModifier); //$NON-NLS-1$ + break; + case IModifierConstants.ACC_TRANSIENT : + firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_TRANSIENT, "transient", firstModifier); //$NON-NLS-1$ + break; + case IModifierConstants.ACC_VOLATILE : + // case IModifierConstants.ACC_BRIDGE : + if (asBridge) { + firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_BRIDGE, "bridge", firstModifier); //$NON-NLS-1$ + } else { + firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_VOLATILE, "volatile", firstModifier); //$NON-NLS-1$ + } + break; + case IModifierConstants.ACC_ENUM : + firstModifier = appendModifier(buffer, accessFlags, IModifierConstants.ACC_ENUM, "enum", firstModifier); //$NON-NLS-1$ + break; + } + } + if (!firstModifier) { + if (!printDefault) + buffer.append(Messages.disassembler_space); + } else if (printDefault) { + // no modifier: package default visibility + buffer.append("default"); //$NON-NLS-1$ + } + } + + private void decodeModifiersForField(StringBuffer buffer, int accessFlags) { + decodeModifiers(buffer, accessFlags, new int[] {IModifierConstants.ACC_PUBLIC, IModifierConstants.ACC_PROTECTED, IModifierConstants.ACC_PRIVATE, IModifierConstants.ACC_STATIC, IModifierConstants.ACC_FINAL, IModifierConstants.ACC_TRANSIENT, IModifierConstants.ACC_VOLATILE, IModifierConstants.ACC_ENUM}); + } + + private final void decodeModifiersForInnerClasses(StringBuffer buffer, int accessFlags, boolean printDefault) { + decodeModifiers(buffer, accessFlags, printDefault, false, new int[] {IModifierConstants.ACC_PUBLIC, IModifierConstants.ACC_PROTECTED, IModifierConstants.ACC_PRIVATE, IModifierConstants.ACC_ABSTRACT, IModifierConstants.ACC_STATIC, IModifierConstants.ACC_FINAL,}); + } + + private final void decodeModifiersForMethod(StringBuffer buffer, int accessFlags) { + decodeModifiers(buffer, accessFlags, false, true, new int[] {IModifierConstants.ACC_PUBLIC, IModifierConstants.ACC_PROTECTED, IModifierConstants.ACC_PRIVATE, IModifierConstants.ACC_ABSTRACT, IModifierConstants.ACC_STATIC, IModifierConstants.ACC_FINAL, IModifierConstants.ACC_SYNCHRONIZED, IModifierConstants.ACC_NATIVE, IModifierConstants.ACC_STRICT, IModifierConstants.ACC_BRIDGE,}); + } + + private final void decodeModifiersForType(StringBuffer buffer, int accessFlags) { + decodeModifiers(buffer, accessFlags, new int[] {IModifierConstants.ACC_PUBLIC, IModifierConstants.ACC_ABSTRACT, IModifierConstants.ACC_FINAL,}); + } + + public static String escapeString(String s) { + StringBuffer buffer = new StringBuffer(); + for (int i = 0, max = s.length(); i < max; i++) { + char c = s.charAt(i); + switch (c) { + case '\b' : + buffer.append("\\b"); //$NON-NLS-1$ + break; + case '\t' : + buffer.append("\\t"); //$NON-NLS-1$ + break; + case '\n' : + buffer.append("\\n"); //$NON-NLS-1$ + break; + case '\f' : + buffer.append("\\f"); //$NON-NLS-1$ + break; + case '\r' : + buffer.append("\\r"); //$NON-NLS-1$ + break; + case '\0' : + buffer.append("\\0"); //$NON-NLS-1$ + break; + case '\1' : + buffer.append("\\1"); //$NON-NLS-1$ + break; + case '\2' : + buffer.append("\\2"); //$NON-NLS-1$ + break; + case '\3' : + buffer.append("\\3"); //$NON-NLS-1$ + break; + case '\4' : + buffer.append("\\4"); //$NON-NLS-1$ + break; + case '\5' : + buffer.append("\\5"); //$NON-NLS-1$ + break; + case '\6' : + buffer.append("\\6"); //$NON-NLS-1$ + break; + case '\7' : + buffer.append("\\7"); //$NON-NLS-1$ + break; + default : + buffer.append(c); + } + } + return buffer.toString(); + } + + static String decodeStringValue(char[] chars) { + StringBuffer buffer = new StringBuffer(); + for (int i = 0, max = chars.length; i < max; i++) { + char c = chars[i]; + switch (c) { + case '\b' : + buffer.append("\\b"); //$NON-NLS-1$ + break; + case '\t' : + buffer.append("\\t"); //$NON-NLS-1$ + break; + case '\n' : + buffer.append("\\n"); //$NON-NLS-1$ + break; + case '\f' : + buffer.append("\\f"); //$NON-NLS-1$ + break; + case '\r' : + buffer.append("\\r"); //$NON-NLS-1$ + break; + case '\0' : + buffer.append("\\0"); //$NON-NLS-1$ + break; + case '\1' : + buffer.append("\\1"); //$NON-NLS-1$ + break; + case '\2' : + buffer.append("\\2"); //$NON-NLS-1$ + break; + case '\3' : + buffer.append("\\3"); //$NON-NLS-1$ + break; + case '\4' : + buffer.append("\\4"); //$NON-NLS-1$ + break; + case '\5' : + buffer.append("\\5"); //$NON-NLS-1$ + break; + case '\6' : + buffer.append("\\6"); //$NON-NLS-1$ + break; + case '\7' : + buffer.append("\\7"); //$NON-NLS-1$ + break; + default : + buffer.append(c); + } + } + return buffer.toString(); + } + + static String decodeStringValue(String s) { + return decodeStringValue(s.toCharArray()); + } + + /* + * @see org.eclipse.jdt.core.util.ClassFileBytesDisassembler#disassemble(byte[], java.lang.String, int) + */ + public String disassemble(byte[] classFileBytes, String lineSeparator, int mode) throws ClassFormatException { + try { + return disassemble(new ClassFileReader(classFileBytes, ClassFileReader.ALL), lineSeparator, mode); + } catch (ArrayIndexOutOfBoundsException e) { + throw new ClassFormatException(e.getMessage(), e); + } + } + + private void disassemble(Annotation annotation, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + writeNewLine(buffer, lineSeparator, tabNumber + 1); + final char[] typeName = CharOperation.replaceOnCopy(annotation.getTypeName(), '/', '.'); + buffer.append(NLS.bind(Messages.disassembler_annotationentrystart, new String[] {new String(returnClassName(Signature.toCharArray(typeName), '.', mode))})); + final AnnotationComponent[] components = annotation.getComponents(); + for (int i = 0, max = components.length; i < max; i++) { + disassemble(components[i], buffer, lineSeparator, tabNumber + 1, mode); + } + writeNewLine(buffer, lineSeparator, tabNumber + 1); + buffer.append(Messages.disassembler_annotationentryend); + } + + private void disassemble(AnnotationComponent annotationComponent, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + writeNewLine(buffer, lineSeparator, tabNumber + 1); + buffer.append(NLS.bind(Messages.disassembler_annotationcomponent, new String[] {new String(annotationComponent.getComponentName())})); + disassemble(annotationComponent.getComponentValue(), buffer, lineSeparator, tabNumber + 1, mode); + } + + private void disassemble(AnnotationComponentValue annotationComponentValue, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + switch (annotationComponentValue.getTag()) { + case AnnotationComponentValue.BYTE_TAG : + case AnnotationComponentValue.CHAR_TAG : + case AnnotationComponentValue.DOUBLE_TAG : + case AnnotationComponentValue.FLOAT_TAG : + case AnnotationComponentValue.INTEGER_TAG : + case AnnotationComponentValue.LONG_TAG : + case AnnotationComponentValue.SHORT_TAG : + case AnnotationComponentValue.BOOLEAN_TAG : + case AnnotationComponentValue.STRING_TAG : + ConstantPoolEntry constantPoolEntry = annotationComponentValue.getConstantValue(); + String value = null; + switch (constantPoolEntry.getKind()) { + case ConstantPoolConstant.CONSTANT_Long : + value = constantPoolEntry.getLongValue() + "L"; //$NON-NLS-1$ + break; + case ConstantPoolConstant.CONSTANT_Float : + value = constantPoolEntry.getFloatValue() + "f"; //$NON-NLS-1$ + break; + case ConstantPoolConstant.CONSTANT_Double : + value = Double.toString(constantPoolEntry.getDoubleValue()); + break; + case ConstantPoolConstant.CONSTANT_Integer : + switch (annotationComponentValue.getTag()) { + case AnnotationComponentValue.CHAR_TAG : + value = "'" + (char) constantPoolEntry.getIntegerValue() + "'"; //$NON-NLS-1$//$NON-NLS-2$ + break; + case AnnotationComponentValue.BOOLEAN_TAG : + value = constantPoolEntry.getIntegerValue() == 1 ? "true" : "false";//$NON-NLS-1$//$NON-NLS-2$ + break; + case AnnotationComponentValue.BYTE_TAG : + value = "(byte) " + constantPoolEntry.getIntegerValue(); //$NON-NLS-1$ + break; + case AnnotationComponentValue.SHORT_TAG : + value = "(short) " + constantPoolEntry.getIntegerValue(); //$NON-NLS-1$ + break; + case AnnotationComponentValue.INTEGER_TAG : + value = "(int) " + constantPoolEntry.getIntegerValue(); //$NON-NLS-1$ + } + break; + case ConstantPoolConstant.CONSTANT_Utf8 : + value = "\"" + decodeStringValue(constantPoolEntry.getUtf8Value()) + "\"";//$NON-NLS-1$//$NON-NLS-2$ + } + buffer.append(NLS.bind(Messages.disassembler_annotationdefaultvalue, value)); + break; + case AnnotationComponentValue.ENUM_TAG : + final char[] typeName = CharOperation.replaceOnCopy(annotationComponentValue.getEnumConstantTypeName(), '/', '.'); + final char[] constantName = annotationComponentValue.getEnumConstantName(); + buffer.append(NLS.bind(Messages.disassembler_annotationenumvalue, new String[] {new String(returnClassName(Signature.toCharArray(typeName), '.', mode)), new String(constantName)})); + break; + case AnnotationComponentValue.CLASS_TAG : + constantPoolEntry = annotationComponentValue.getClassInfo(); + final char[] className = CharOperation.replaceOnCopy(constantPoolEntry.getUtf8Value(), '/', '.'); + buffer.append(NLS.bind(Messages.disassembler_annotationclassvalue, new String[] {new String(returnClassName(Signature.toCharArray(className), '.', mode))})); + break; + case AnnotationComponentValue.ANNOTATION_TAG : + buffer.append(Messages.disassembler_annotationannotationvalue); + Annotation annotation = annotationComponentValue.getAnnotationValue(); + disassemble(annotation, buffer, lineSeparator, tabNumber + 1, mode); + break; + case AnnotationComponentValue.ARRAY_TAG : + buffer.append(Messages.disassembler_annotationarrayvaluestart); + final AnnotationComponentValue[] annotationComponentValues = annotationComponentValue.getAnnotationComponentValues(); + for (int i = 0, max = annotationComponentValues.length; i < max; i++) { + writeNewLine(buffer, lineSeparator, tabNumber + 1); + disassemble(annotationComponentValues[i], buffer, lineSeparator, tabNumber + 1, mode); + } + writeNewLine(buffer, lineSeparator, tabNumber + 1); + buffer.append(Messages.disassembler_annotationarrayvalueend); + } + } + + private void disassemble(AnnotationDefaultAttribute annotationDefaultAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + writeNewLine(buffer, lineSeparator, tabNumber + 1); + buffer.append(Messages.disassembler_annotationdefaultheader); + AnnotationComponentValue componentValue = annotationDefaultAttribute.getMemberValue(); + writeNewLine(buffer, lineSeparator, tabNumber + 2); + disassemble(componentValue, buffer, lineSeparator, tabNumber + 1, mode); + } + + /** + * Disassemble a method info header + */ + private void disassemble(ClassFileReader classFileReader, char[] className, MethodInfo methodInfo, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + writeNewLine(buffer, lineSeparator, tabNumber); + final CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); + final char[] methodDescriptor = methodInfo.getDescriptor(); + final SignatureAttribute signatureAttribute = (SignatureAttribute) Utility.getAttribute(methodInfo, AttributeNamesConstants.SIGNATURE); + final ClassFileAttribute runtimeVisibleAnnotationsAttribute = Utility.getAttribute(methodInfo, AttributeNamesConstants.RUNTIME_VISIBLE_ANNOTATIONS); + final ClassFileAttribute runtimeInvisibleAnnotationsAttribute = Utility.getAttribute(methodInfo, AttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS); + final ClassFileAttribute runtimeVisibleParameterAnnotationsAttribute = Utility.getAttribute(methodInfo, AttributeNamesConstants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS); + final ClassFileAttribute runtimeInvisibleParameterAnnotationsAttribute = Utility.getAttribute(methodInfo, AttributeNamesConstants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS); + final ClassFileAttribute annotationDefaultAttribute = Utility.getAttribute(methodInfo, AttributeNamesConstants.ANNOTATION_DEFAULT); + if (checkMode(mode, DETAILED)) { + buffer.append(NLS.bind(Messages.classfileformat_methoddescriptor, new String[] {new String(methodDescriptor)})); + if (methodInfo.isDeprecated()) { + buffer.append(Messages.disassembler_deprecated); + } + writeNewLine(buffer, lineSeparator, tabNumber); + if (signatureAttribute != null) { + buffer.append(NLS.bind(Messages.disassembler_signatureattributeheader, new String(signatureAttribute.getSignature()))); + writeNewLine(buffer, lineSeparator, tabNumber); + } + if (codeAttribute != null) { + buffer.append(NLS.bind(Messages.classfileformat_stacksAndLocals, new String[] {Integer.toString(codeAttribute.getMaxStack()), Integer.toString(codeAttribute.getMaxLocals())})); + writeNewLine(buffer, lineSeparator, tabNumber); + } + // disassemble compact version of annotations + if (runtimeInvisibleAnnotationsAttribute != null) { + disassembleAsModifier((RuntimeInvisibleAnnotationsAttribute) runtimeInvisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); + writeNewLine(buffer, lineSeparator, tabNumber); + } + if (runtimeVisibleAnnotationsAttribute != null) { + disassembleAsModifier((RuntimeVisibleAnnotationsAttribute) runtimeVisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); + writeNewLine(buffer, lineSeparator, tabNumber); + } + } + final int accessFlags = methodInfo.getAccessFlags(); + decodeModifiersForMethod(buffer, accessFlags); + if (methodInfo.isSynthetic()) { + buffer.append("synthetic"); //$NON-NLS-1$ + buffer.append(Messages.disassembler_space); + } + CharOperation.replace(methodDescriptor, '/', '.'); + final boolean isVarArgs = isVarArgs(methodInfo); + char[] methodHeader = null; + if (methodInfo.isConstructor()) { + methodHeader = Signature.toCharArray(methodDescriptor, returnClassName(className, '.', COMPACT), null, !checkMode(mode, COMPACT), false, isVarArgs); + } else if (methodInfo.isClinit()) { + methodHeader = Messages.classfileformat_clinitname.toCharArray(); + } else { + methodHeader = Signature.toCharArray(methodDescriptor, methodInfo.getName(), null, !checkMode(mode, COMPACT), true, isVarArgs); + } + if (checkMode(mode, DETAILED) && (runtimeInvisibleParameterAnnotationsAttribute != null || runtimeVisibleParameterAnnotationsAttribute != null)) { + ParameterAnnotation[] invisibleParameterAnnotations = null; + ParameterAnnotation[] visibleParameterAnnotations = null; + int length = -1; + if (runtimeInvisibleParameterAnnotationsAttribute != null) { + RuntimeInvisibleParameterAnnotationsAttribute attribute = (RuntimeInvisibleParameterAnnotationsAttribute) runtimeInvisibleParameterAnnotationsAttribute; + invisibleParameterAnnotations = attribute.getParameterAnnotations(); + length = invisibleParameterAnnotations.length; + } + if (runtimeVisibleParameterAnnotationsAttribute != null) { + RuntimeVisibleParameterAnnotationsAttribute attribute = (RuntimeVisibleParameterAnnotationsAttribute) runtimeVisibleParameterAnnotationsAttribute; + visibleParameterAnnotations = attribute.getParameterAnnotations(); + length = visibleParameterAnnotations.length; + } + int insertionPosition = CharOperation.indexOf('(', methodHeader) + 1; + int start = 0; + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append(methodHeader, 0, insertionPosition); + for (int i = 0; i < length; i++) { + if (i > 0) { + stringBuffer.append(' '); + } + int stringBufferSize = stringBuffer.length(); + if (runtimeVisibleParameterAnnotationsAttribute != null) { + disassembleAsModifier((RuntimeVisibleParameterAnnotationsAttribute) runtimeVisibleParameterAnnotationsAttribute, stringBuffer, i, lineSeparator, tabNumber, mode); + } + if (runtimeInvisibleParameterAnnotationsAttribute != null) { + if (stringBuffer.length() != stringBufferSize) { + stringBuffer.append(' '); + stringBufferSize = stringBuffer.length(); + } + disassembleAsModifier((RuntimeInvisibleParameterAnnotationsAttribute) runtimeInvisibleParameterAnnotationsAttribute, stringBuffer, i, lineSeparator, tabNumber, mode); + } + if (i == 0 && stringBuffer.length() != stringBufferSize) { + stringBuffer.append(' '); + } + start = insertionPosition; + insertionPosition = CharOperation.indexOf(',', methodHeader, start + 1) + 1; + if (insertionPosition == 0) { + stringBuffer.append(methodHeader, start, methodHeader.length - start); + } else { + stringBuffer.append(methodHeader, start, insertionPosition - start); + } + } + buffer.append(stringBuffer); + } else { + buffer.append(methodHeader); + } + ExceptionAttribute exceptionAttribute = methodInfo.getExceptionAttribute(); + if (exceptionAttribute != null) { + buffer.append(" throws "); //$NON-NLS-1$ + char[][] exceptionNames = exceptionAttribute.getExceptionNames(); + int length = exceptionNames.length; + for (int i = 0; i < length; i++) { + if (i != 0) { + buffer.append(Messages.disassembler_comma).append(Messages.disassembler_space); + } + char[] exceptionName = exceptionNames[i]; + CharOperation.replace(exceptionName, '/', '.'); + buffer.append(returnClassName(exceptionName, '.', mode)); + } + } + if (checkMode(mode, DETAILED)) { + if (annotationDefaultAttribute != null) { + buffer.append(" default "); //$NON-NLS-1$ + disassembleAsModifier((AnnotationDefaultAttribute) annotationDefaultAttribute, buffer, lineSeparator, tabNumber, mode); + } + } + buffer.append(Messages.disassembler_endofmethodheader); + + if (checkMode(mode, DETAILED)) { + if (codeAttribute != null) { + disassemble(codeAttribute, methodDescriptor, (accessFlags & IModifierConstants.ACC_STATIC) != 0, buffer, lineSeparator, tabNumber, mode); + } + if (annotationDefaultAttribute != null) { + disassemble((AnnotationDefaultAttribute) annotationDefaultAttribute, buffer, lineSeparator, tabNumber, mode); + } + if (runtimeVisibleAnnotationsAttribute != null) { + disassemble((RuntimeVisibleAnnotationsAttribute) runtimeVisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); + } + if (runtimeInvisibleAnnotationsAttribute != null) { + disassemble((RuntimeInvisibleAnnotationsAttribute) runtimeInvisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); + } + if (runtimeVisibleParameterAnnotationsAttribute != null) { + disassemble((RuntimeVisibleParameterAnnotationsAttribute) runtimeVisibleParameterAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); + } + if (runtimeInvisibleParameterAnnotationsAttribute != null) { + disassemble((RuntimeInvisibleParameterAnnotationsAttribute) runtimeInvisibleParameterAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); + } + } + } + + /** + * Answers back the disassembled string of the ClassFileReader according to the + * mode. + * This is an output quite similar to the javap tool. + * + * @param classFileReader The classFileReader to be disassembled + * @param lineSeparator the line separator to use. + * @param mode the mode used to disassemble the ClassFileReader + * + * @return the disassembled string of the ClassFileReader according to the mode + */ + private String disassemble(ClassFileReader classFileReader, String lineSeparator, int mode) { + if (classFileReader == null) + return Utility.EMPTY_STRING; + char[] className = classFileReader.getClassName(); + if (className == null) { + // incomplete initialization. We cannot go further. + return Utility.EMPTY_STRING; + } + className = CharOperation.replaceOnCopy(className, '/', '.'); + final int accessFlags = classFileReader.getAccessFlags(); + final boolean isEnum = (accessFlags & IModifierConstants.ACC_ENUM) != 0; + + StringBuffer buffer = new StringBuffer(); + SourceFileAttribute sourceAttribute = classFileReader.getSourceFileAttribute(); + ClassFileAttribute classFileAttribute = Utility.getAttribute(classFileReader, AttributeNamesConstants.SIGNATURE); + SignatureAttribute signatureAttribute = (SignatureAttribute) classFileAttribute; + if (checkMode(mode, DETAILED)) { + int minorVersion = classFileReader.getMinorVersion(); + int majorVersion = classFileReader.getMajorVersion(); + buffer.append(Messages.disassembler_begincommentline); + if (sourceAttribute != null) { + buffer.append(Messages.disassembler_sourceattributeheader); + buffer.append(sourceAttribute.getSourceFileName()); + } + String versionNumber = VERSION_UNKNOWN; + if (minorVersion == 3 && majorVersion == 45) { + versionNumber = IModifierConstants.VERSION_1_1; + } else if (minorVersion == 0 && majorVersion == 46) { + versionNumber = IModifierConstants.VERSION_1_2; + } else if (minorVersion == 0 && majorVersion == 47) { + versionNumber = IModifierConstants.VERSION_1_3; + } else if (minorVersion == 0 && majorVersion == 48) { + versionNumber = IModifierConstants.VERSION_1_4; + } else if (minorVersion == 0 && majorVersion == 49) { + versionNumber = IModifierConstants.VERSION_1_5; + } else if (minorVersion == 0 && majorVersion == 50) { + versionNumber = IModifierConstants.VERSION_1_6; + } else if (minorVersion == 0 && majorVersion == 51) { + versionNumber = IModifierConstants.VERSION_1_7; + } + buffer.append(NLS.bind(Messages.classfileformat_versiondetails, new String[] {versionNumber, Integer.toString(majorVersion), Integer.toString(minorVersion), ((accessFlags & IModifierConstants.ACC_SUPER) != 0 ? Messages.classfileformat_superflagisset : Messages.classfileformat_superflagisnotset) + (isDeprecated(classFileReader) ? ", deprecated" : Utility.EMPTY_STRING)//$NON-NLS-1$ + })); + writeNewLine(buffer, lineSeparator, 0); + if (signatureAttribute != null) { + buffer.append(NLS.bind(Messages.disassembler_signatureattributeheader, new String(signatureAttribute.getSignature()))); + writeNewLine(buffer, lineSeparator, 0); + } + } + + InnerClassesAttribute innerClassesAttribute = classFileReader.getInnerClassesAttribute(); + ClassFileAttribute runtimeVisibleAnnotationsAttribute = Utility.getAttribute(classFileReader, AttributeNamesConstants.RUNTIME_VISIBLE_ANNOTATIONS); + ClassFileAttribute runtimeInvisibleAnnotationsAttribute = Utility.getAttribute(classFileReader, AttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS); + + if (checkMode(mode, DETAILED)) { + // disassemble compact version of annotations + if (runtimeInvisibleAnnotationsAttribute != null) { + disassembleAsModifier((RuntimeInvisibleAnnotationsAttribute) runtimeInvisibleAnnotationsAttribute, buffer, lineSeparator, 0, mode); + writeNewLine(buffer, lineSeparator, 0); + } + if (runtimeVisibleAnnotationsAttribute != null) { + disassembleAsModifier((RuntimeVisibleAnnotationsAttribute) runtimeVisibleAnnotationsAttribute, buffer, lineSeparator, 0, mode); + writeNewLine(buffer, lineSeparator, 0); + } + } + boolean decoded = false; + if (innerClassesAttribute != null) { + // search the right entry + InnerClassesAttributeEntry[] entries = innerClassesAttribute.getInnerClassAttributesEntries(); + for (int i = 0, max = entries.length; i < max; i++) { + InnerClassesAttributeEntry entry = entries[i]; + char[] innerClassName = entry.getInnerClassName(); + if (innerClassName != null) { + if (Arrays.equals(classFileReader.getClassName(), innerClassName)) { + decodeModifiersForInnerClasses(buffer, entry.getAccessFlags(), false); + decoded = true; + } + } + } + } + if (!decoded) { + decodeModifiersForType(buffer, accessFlags); + if (isSynthetic(classFileReader)) { + buffer.append("synthetic"); //$NON-NLS-1$ + buffer.append(Messages.disassembler_space); + } + } + + final boolean isAnnotation = (accessFlags & IModifierConstants.ACC_ANNOTATION) != 0; + boolean isInterface = false; + if (isEnum) { + buffer.append("enum "); //$NON-NLS-1$ + } else if (classFileReader.isClass()) { + buffer.append("class "); //$NON-NLS-1$ + } else { + if (isAnnotation) { + buffer.append("@"); //$NON-NLS-1$ + } + buffer.append("interface "); //$NON-NLS-1$ + isInterface = true; + } + + buffer.append(className); + + char[] superclassName = classFileReader.getSuperclassName(); + if (superclassName != null) { + CharOperation.replace(superclassName, '/', '.'); + if (!isJavaLangObject(superclassName) && !isEnum) { + buffer.append(" extends "); //$NON-NLS-1$ + buffer.append(returnClassName(superclassName, '.', mode)); + } + } + if (!isAnnotation) { + char[][] superclassInterfaces = classFileReader.getInterfaceNames(); + int length = superclassInterfaces.length; + if (length != 0) { + if (isInterface) { + buffer.append(" extends "); //$NON-NLS-1$ + } else { + buffer.append(" implements "); //$NON-NLS-1$ + } + for (int i = 0; i < length; i++) { + if (i != 0) { + buffer.append(Messages.disassembler_comma).append(Messages.disassembler_space); + } + char[] superinterface = superclassInterfaces[i]; + CharOperation.replace(superinterface, '/', '.'); + buffer.append(returnClassName(superinterface, '.', mode)); + } + } + } + buffer.append(Messages.disassembler_opentypedeclaration); + disassembleTypeMembers(classFileReader, className, buffer, lineSeparator, 1, mode, isEnum); + if (checkMode(mode, DETAILED)) { + ClassFileAttribute[] attributes = classFileReader.getAttributes(); + int length = attributes.length; + EnclosingMethodAttribute enclosingMethodAttribute = getEnclosingMethodAttribute(classFileReader); + int remainingAttributesLength = length; + if (innerClassesAttribute != null) { + remainingAttributesLength--; + } + if (enclosingMethodAttribute != null) { + remainingAttributesLength--; + } + if (sourceAttribute != null) { + remainingAttributesLength--; + } + if (signatureAttribute != null) { + remainingAttributesLength--; + } + if (innerClassesAttribute != null || enclosingMethodAttribute != null || remainingAttributesLength != 0) { + writeNewLine(buffer, lineSeparator, 0); + } + if (innerClassesAttribute != null) { + disassemble(innerClassesAttribute, buffer, lineSeparator, 1); + } + if (enclosingMethodAttribute != null) { + disassemble(enclosingMethodAttribute, buffer, lineSeparator, 0); + } + if (runtimeVisibleAnnotationsAttribute != null) { + disassemble((RuntimeVisibleAnnotationsAttribute) runtimeVisibleAnnotationsAttribute, buffer, lineSeparator, 0, mode); + } + if (runtimeInvisibleAnnotationsAttribute != null) { + disassemble((RuntimeInvisibleAnnotationsAttribute) runtimeInvisibleAnnotationsAttribute, buffer, lineSeparator, 0, mode); + } + } + writeNewLine(buffer, lineSeparator, 0); + buffer.append(Messages.disassembler_closetypedeclaration); + return buffer.toString(); + } + + private boolean isJavaLangObject(final char[] className) { + return Arrays.equals(TypeConstants.JAVA_LANG_OBJECT, CharOperation.splitOn('.', className)); + } + + private boolean isVarArgs(MethodInfo methodInfo) { + int accessFlags = methodInfo.getAccessFlags(); + if ((accessFlags & IModifierConstants.ACC_VARARGS) != 0) + return true; + // check the presence of the unspecified Varargs attribute + return Utility.getAttribute(methodInfo, AttributeNamesConstants.VAR_ARGS) != null; + } + + private void disassemble(CodeAttribute codeAttribute, char[] methodDescriptor, boolean isStatic, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + writeNewLine(buffer, lineSeparator, tabNumber - 1); + DefaultBytecodeVisitor visitor = new DefaultBytecodeVisitor(codeAttribute, methodDescriptor, isStatic, buffer, lineSeparator, tabNumber, mode); + try { + codeAttribute.traverse(visitor); + } catch (ClassFormatException e) { + dumpTab(tabNumber + 2, buffer); + buffer.append(Messages.classformat_classformatexception); + writeNewLine(buffer, lineSeparator, tabNumber + 1); + } + final int exceptionTableLength = codeAttribute.getExceptionTableLength(); + if (exceptionTableLength != 0) { + final int tabNumberForExceptionAttribute = tabNumber + 2; + dumpTab(tabNumberForExceptionAttribute, buffer); + final ExceptionTableEntry[] exceptionTableEntries = codeAttribute.getExceptionTable(); + buffer.append(Messages.disassembler_exceptiontableheader); + writeNewLine(buffer, lineSeparator, tabNumberForExceptionAttribute + 1); + for (int i = 0; i < exceptionTableLength; i++) { + if (i != 0) { + writeNewLine(buffer, lineSeparator, tabNumberForExceptionAttribute + 1); + } + ExceptionTableEntry exceptionTableEntry = exceptionTableEntries[i]; + char[] catchType; + if (exceptionTableEntry.getCatchTypeIndex() != 0) { + catchType = exceptionTableEntry.getCatchType(); + CharOperation.replace(catchType, '/', '.'); + catchType = returnClassName(catchType, '.', mode); + } else { + catchType = ANY_EXCEPTION; + } + buffer.append(NLS.bind(Messages.classfileformat_exceptiontableentry, new String[] {Integer.toString(exceptionTableEntry.getStartPC()), Integer.toString(exceptionTableEntry.getEndPC()), Integer.toString(exceptionTableEntry.getHandlerPC()), new String(catchType),})); + } + } + } + + private void disassemble(EnclosingMethodAttribute enclosingMethodAttribute, StringBuffer buffer, String lineSeparator, int tabNumber) { + writeNewLine(buffer, lineSeparator, tabNumber + 1); + buffer.append(Messages.disassembler_enclosingmethodheader); + buffer.append(" ")//$NON-NLS-1$ + .append(enclosingMethodAttribute.getEnclosingClass()); + if (enclosingMethodAttribute.getMethodNameAndTypeIndex() != 0) { + buffer.append(".")//$NON-NLS-1$ + .append(enclosingMethodAttribute.getMethodName()).append(enclosingMethodAttribute.getMethodDescriptor()); + } + } + + /** + * Disassemble a field info + */ + private void disassemble(FieldInfo fieldInfo, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + writeNewLine(buffer, lineSeparator, tabNumber); + final char[] fieldDescriptor = fieldInfo.getDescriptor(); + final SignatureAttribute signatureAttribute = (SignatureAttribute) Utility.getAttribute(fieldInfo, AttributeNamesConstants.SIGNATURE); + if (checkMode(mode, DETAILED)) { + buffer.append(NLS.bind(Messages.classfileformat_fieldddescriptor, new String[] {new String(fieldDescriptor)})); + if (fieldInfo.isDeprecated()) { + buffer.append(Messages.disassembler_deprecated); + } + writeNewLine(buffer, lineSeparator, tabNumber); + if (signatureAttribute != null) { + buffer.append(NLS.bind(Messages.disassembler_signatureattributeheader, new String(signatureAttribute.getSignature()))); + writeNewLine(buffer, lineSeparator, tabNumber); + } + } + final ClassFileAttribute runtimeVisibleAnnotationsAttribute = Utility.getAttribute(fieldInfo, AttributeNamesConstants.RUNTIME_VISIBLE_ANNOTATIONS); + final ClassFileAttribute runtimeInvisibleAnnotationsAttribute = Utility.getAttribute(fieldInfo, AttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS); + if (checkMode(mode, DETAILED)) { + // disassemble compact version of annotations + if (runtimeInvisibleAnnotationsAttribute != null) { + disassembleAsModifier((RuntimeInvisibleAnnotationsAttribute) runtimeInvisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); + writeNewLine(buffer, lineSeparator, tabNumber); + } + if (runtimeVisibleAnnotationsAttribute != null) { + disassembleAsModifier((RuntimeVisibleAnnotationsAttribute) runtimeVisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); + writeNewLine(buffer, lineSeparator, tabNumber); + } + } + decodeModifiersForField(buffer, fieldInfo.getAccessFlags()); + if (fieldInfo.isSynthetic()) { + buffer.append("synthetic"); //$NON-NLS-1$ + buffer.append(Messages.disassembler_space); + } + buffer.append(returnClassName(getSignatureForField(fieldDescriptor), '.', mode)); + buffer.append(' '); + buffer.append(new String(fieldInfo.getName())); + ConstantValueAttribute constantValueAttribute = fieldInfo.getConstantValueAttribute(); + if (constantValueAttribute != null) { + buffer.append(Messages.disassembler_fieldhasconstant); + ConstantPoolEntry constantPoolEntry = constantValueAttribute.getConstantValue(); + switch (constantPoolEntry.getKind()) { + case ConstantPoolConstant.CONSTANT_Long : + buffer.append(constantPoolEntry.getLongValue() + "L"); //$NON-NLS-1$ + break; + case ConstantPoolConstant.CONSTANT_Float : + buffer.append(constantPoolEntry.getFloatValue() + "f"); //$NON-NLS-1$ + break; + case ConstantPoolConstant.CONSTANT_Double : + buffer.append(constantPoolEntry.getDoubleValue()); + break; + case ConstantPoolConstant.CONSTANT_Integer : + switch (fieldDescriptor[0]) { + case 'C' : + buffer.append("'" + (char) constantPoolEntry.getIntegerValue() + "'"); //$NON-NLS-1$//$NON-NLS-2$ + break; + case 'Z' : + buffer.append(constantPoolEntry.getIntegerValue() == 1 ? "true" : "false");//$NON-NLS-1$//$NON-NLS-2$ + break; + case 'B' : + buffer.append(constantPoolEntry.getIntegerValue()); + break; + case 'S' : + buffer.append(constantPoolEntry.getIntegerValue()); + break; + case 'I' : + buffer.append(constantPoolEntry.getIntegerValue()); + } + break; + case ConstantPoolConstant.CONSTANT_String : + buffer.append("\"" + decodeStringValue(constantPoolEntry.getStringValue()) + "\"");//$NON-NLS-1$//$NON-NLS-2$ + } + } + buffer.append(Messages.disassembler_endoffieldheader); + if (checkMode(mode, DETAILED)) { + if (runtimeVisibleAnnotationsAttribute != null) { + disassemble((RuntimeVisibleAnnotationsAttribute) runtimeVisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); + } + if (runtimeInvisibleAnnotationsAttribute != null) { + disassemble((RuntimeInvisibleAnnotationsAttribute) runtimeInvisibleAnnotationsAttribute, buffer, lineSeparator, tabNumber, mode); + } + } + } + + private void disassemble(InnerClassesAttribute innerClassesAttribute, StringBuffer buffer, String lineSeparator, int tabNumber) { + writeNewLine(buffer, lineSeparator, tabNumber); + buffer.append(Messages.disassembler_innerattributesheader); + writeNewLine(buffer, lineSeparator, tabNumber + 1); + InnerClassesAttributeEntry[] innerClassesAttributeEntries = innerClassesAttribute.getInnerClassAttributesEntries(); + int length = innerClassesAttributeEntries.length; + int innerClassNameIndex, outerClassNameIndex, innerNameIndex, accessFlags; + InnerClassesAttributeEntry innerClassesAttributeEntry; + for (int i = 0; i < length; i++) { + if (i != 0) { + buffer.append(Messages.disassembler_comma); + writeNewLine(buffer, lineSeparator, tabNumber + 1); + } + innerClassesAttributeEntry = innerClassesAttributeEntries[i]; + innerClassNameIndex = innerClassesAttributeEntry.getInnerClassNameIndex(); + outerClassNameIndex = innerClassesAttributeEntry.getOuterClassNameIndex(); + innerNameIndex = innerClassesAttributeEntry.getInnerNameIndex(); + accessFlags = innerClassesAttributeEntry.getAccessFlags(); + buffer.append(Messages.disassembler_openinnerclassentry).append(Messages.disassembler_inner_class_info_name); + if (innerClassNameIndex != 0) { + buffer.append(Messages.disassembler_space).append(innerClassesAttributeEntry.getInnerClassName()); + } + buffer.append(Messages.disassembler_comma).append(Messages.disassembler_space).append(Messages.disassembler_outer_class_info_name); + if (outerClassNameIndex != 0) { + buffer.append(Messages.disassembler_space).append(innerClassesAttributeEntry.getOuterClassName()); + } + writeNewLine(buffer, lineSeparator, tabNumber); + dumpTab(tabNumber, buffer); + buffer.append(Messages.disassembler_space); + buffer.append(Messages.disassembler_inner_name); + if (innerNameIndex != 0) { + buffer.append(Messages.disassembler_space).append(innerClassesAttributeEntry.getInnerName()); + } + buffer.append(Messages.disassembler_comma).append(Messages.disassembler_space).append(Messages.disassembler_inner_accessflags).append(accessFlags).append(Messages.disassembler_space); + decodeModifiersForInnerClasses(buffer, accessFlags, true); + buffer.append(Messages.disassembler_closeinnerclassentry); + } + } + + private void disassemble(int index, ParameterAnnotation parameterAnnotation, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + Annotation[] annotations = parameterAnnotation.getAnnotations(); + writeNewLine(buffer, lineSeparator, tabNumber + 1); + buffer.append(NLS.bind(Messages.disassembler_parameterannotationentrystart, new String[] {Integer.toString(index), Integer.toString(annotations.length)})); + for (int i = 0, max = annotations.length; i < max; i++) { + disassemble(annotations[i], buffer, lineSeparator, tabNumber + 1, mode); + } + } + + private void disassemble(RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + writeNewLine(buffer, lineSeparator, tabNumber + 1); + buffer.append(Messages.disassembler_runtimeinvisibleannotationsattributeheader); + Annotation[] annotations = runtimeInvisibleAnnotationsAttribute.getAnnotations(); + for (int i = 0, max = annotations.length; i < max; i++) { + disassemble(annotations[i], buffer, lineSeparator, tabNumber + 1, mode); + } + } + + private void disassemble(RuntimeInvisibleParameterAnnotationsAttribute runtimeInvisibleParameterAnnotationsAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + writeNewLine(buffer, lineSeparator, tabNumber + 1); + buffer.append(Messages.disassembler_runtimeinvisibleparameterannotationsattributeheader); + ParameterAnnotation[] parameterAnnotations = runtimeInvisibleParameterAnnotationsAttribute.getParameterAnnotations(); + for (int i = 0, max = parameterAnnotations.length; i < max; i++) { + disassemble(i, parameterAnnotations[i], buffer, lineSeparator, tabNumber + 1, mode); + } + } + + private void disassemble(RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + writeNewLine(buffer, lineSeparator, tabNumber + 1); + buffer.append(Messages.disassembler_runtimevisibleannotationsattributeheader); + Annotation[] annotations = runtimeVisibleAnnotationsAttribute.getAnnotations(); + for (int i = 0, max = annotations.length; i < max; i++) { + disassemble(annotations[i], buffer, lineSeparator, tabNumber + 1, mode); + } + } + + private void disassemble(RuntimeVisibleParameterAnnotationsAttribute runtimeVisibleParameterAnnotationsAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + writeNewLine(buffer, lineSeparator, tabNumber + 1); + buffer.append(Messages.disassembler_runtimevisibleparameterannotationsattributeheader); + ParameterAnnotation[] parameterAnnotations = runtimeVisibleParameterAnnotationsAttribute.getParameterAnnotations(); + for (int i = 0, max = parameterAnnotations.length; i < max; i++) { + disassemble(i, parameterAnnotations[i], buffer, lineSeparator, tabNumber + 1, mode); + } + } + + private void disassembleAsModifier(Annotation annotation, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + final char[] typeName = CharOperation.replaceOnCopy(annotation.getTypeName(), '/', '.'); + buffer.append('@').append(returnClassName(Signature.toCharArray(typeName), '.', mode)); + final AnnotationComponent[] components = annotation.getComponents(); + final int length = components.length; + if (length != 0) { + buffer.append('('); + for (int i = 0; i < length; i++) { + if (i > 0) { + buffer.append(','); + writeNewLine(buffer, lineSeparator, tabNumber); + } + disassembleAsModifier(components[i], buffer, lineSeparator, tabNumber + 1, mode); + } + buffer.append(')'); + } + } + + private void disassembleAsModifier(AnnotationComponent annotationComponent, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + buffer.append(annotationComponent.getComponentName()).append('='); + disassembleAsModifier(annotationComponent.getComponentValue(), buffer, lineSeparator, tabNumber + 1, mode); + } + + private void disassembleAsModifier(AnnotationComponentValue annotationComponentValue, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + switch (annotationComponentValue.getTag()) { + case AnnotationComponentValue.BYTE_TAG : + case AnnotationComponentValue.CHAR_TAG : + case AnnotationComponentValue.DOUBLE_TAG : + case AnnotationComponentValue.FLOAT_TAG : + case AnnotationComponentValue.INTEGER_TAG : + case AnnotationComponentValue.LONG_TAG : + case AnnotationComponentValue.SHORT_TAG : + case AnnotationComponentValue.BOOLEAN_TAG : + case AnnotationComponentValue.STRING_TAG : + ConstantPoolEntry constantPoolEntry = annotationComponentValue.getConstantValue(); + String value = null; + switch (constantPoolEntry.getKind()) { + case ConstantPoolConstant.CONSTANT_Long : + value = constantPoolEntry.getLongValue() + "L"; //$NON-NLS-1$ + break; + case ConstantPoolConstant.CONSTANT_Float : + value = constantPoolEntry.getFloatValue() + "f"; //$NON-NLS-1$ + break; + case ConstantPoolConstant.CONSTANT_Double : + value = Double.toString(constantPoolEntry.getDoubleValue()); + break; + case ConstantPoolConstant.CONSTANT_Integer : + switch (annotationComponentValue.getTag()) { + case AnnotationComponentValue.CHAR_TAG : + value = "'" + (char) constantPoolEntry.getIntegerValue() + "'"; //$NON-NLS-1$//$NON-NLS-2$ + break; + case AnnotationComponentValue.BOOLEAN_TAG : + value = constantPoolEntry.getIntegerValue() == 1 ? "true" : "false";//$NON-NLS-1$//$NON-NLS-2$ + break; + case AnnotationComponentValue.BYTE_TAG : + value = "(byte) " + constantPoolEntry.getIntegerValue(); //$NON-NLS-1$ + break; + case AnnotationComponentValue.SHORT_TAG : + value = "(short) " + constantPoolEntry.getIntegerValue(); //$NON-NLS-1$ + break; + case AnnotationComponentValue.INTEGER_TAG : + value = "(int) " + constantPoolEntry.getIntegerValue(); //$NON-NLS-1$ + } + break; + case ConstantPoolConstant.CONSTANT_Utf8 : + value = "\"" + decodeStringValue(constantPoolEntry.getUtf8Value()) + "\"";//$NON-NLS-1$//$NON-NLS-2$ + } + buffer.append(value); + break; + case AnnotationComponentValue.ENUM_TAG : + final char[] typeName = CharOperation.replaceOnCopy(annotationComponentValue.getEnumConstantTypeName(), '/', '.'); + final char[] constantName = annotationComponentValue.getEnumConstantName(); + buffer.append(returnClassName(Signature.toCharArray(typeName), '.', mode)).append('.').append(constantName); + break; + case AnnotationComponentValue.CLASS_TAG : + constantPoolEntry = annotationComponentValue.getClassInfo(); + final char[] className = CharOperation.replaceOnCopy(constantPoolEntry.getUtf8Value(), '/', '.'); + buffer.append(returnClassName(Signature.toCharArray(className), '.', mode)); + break; + case AnnotationComponentValue.ANNOTATION_TAG : + Annotation annotation = annotationComponentValue.getAnnotationValue(); + disassembleAsModifier(annotation, buffer, lineSeparator, tabNumber + 1, mode); + break; + case AnnotationComponentValue.ARRAY_TAG : + final AnnotationComponentValue[] annotationComponentValues = annotationComponentValue.getAnnotationComponentValues(); + buffer.append('{'); + for (int i = 0, max = annotationComponentValues.length; i < max; i++) { + if (i > 0) { + buffer.append(','); + } + disassembleAsModifier(annotationComponentValues[i], buffer, lineSeparator, tabNumber + 1, mode); + } + buffer.append('}'); + } + } + + private void disassembleAsModifier(AnnotationDefaultAttribute annotationDefaultAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + AnnotationComponentValue componentValue = annotationDefaultAttribute.getMemberValue(); + disassembleAsModifier(componentValue, buffer, lineSeparator, tabNumber + 1, mode); + } + + private void disassembleAsModifier(RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + Annotation[] annotations = runtimeInvisibleAnnotationsAttribute.getAnnotations(); + for (int i = 0, max = annotations.length; i < max; i++) { + disassembleAsModifier(annotations[i], buffer, lineSeparator, tabNumber + 1, mode); + } + } + + private void disassembleAsModifier(RuntimeInvisibleParameterAnnotationsAttribute runtimeInvisibleParameterAnnotationsAttribute, StringBuffer buffer, int index, String lineSeparator, int tabNumber, int mode) { + ParameterAnnotation[] parameterAnnotations = runtimeInvisibleParameterAnnotationsAttribute.getParameterAnnotations(); + if (parameterAnnotations.length > index) { + disassembleAsModifier(parameterAnnotations[index], buffer, lineSeparator, tabNumber + 1, mode); + } + } + + private void disassembleAsModifier(RuntimeVisibleParameterAnnotationsAttribute runtimeVisibleParameterAnnotationsAttribute, StringBuffer buffer, int index, String lineSeparator, int tabNumber, int mode) { + ParameterAnnotation[] parameterAnnotations = runtimeVisibleParameterAnnotationsAttribute.getParameterAnnotations(); + if (parameterAnnotations.length > index) { + disassembleAsModifier(parameterAnnotations[index], buffer, lineSeparator, tabNumber + 1, mode); + } + } + + private void disassembleAsModifier(ParameterAnnotation parameterAnnotation, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + Annotation[] annotations = parameterAnnotation.getAnnotations(); + for (int i = 0, max = annotations.length; i < max; i++) { + if (i > 0) { + buffer.append(' '); + } + disassembleAsModifier(annotations[i], buffer, lineSeparator, tabNumber + 1, mode); + } + } + + private void disassembleAsModifier(RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute, StringBuffer buffer, String lineSeparator, int tabNumber, int mode) { + Annotation[] annotations = runtimeVisibleAnnotationsAttribute.getAnnotations(); + for (int i = 0, max = annotations.length; i < max; i++) { + if (i > 0) { + writeNewLine(buffer, lineSeparator, tabNumber); + } + disassembleAsModifier(annotations[i], buffer, lineSeparator, tabNumber + 1, mode); + } + } + + private void disassembleTypeMembers(ClassFileReader classFileReader, char[] className, StringBuffer buffer, String lineSeparator, int tabNumber, int mode, boolean isEnum) { + FieldInfo[] fields = classFileReader.getFieldInfos(); + // sort fields + Arrays.sort(fields, new Comparator() { + public int compare(FieldInfo fieldInfo1, FieldInfo fieldInfo2) { + int compare = new String(fieldInfo1.getName()).compareTo(new String(fieldInfo2.getName())); + if (compare == 0) { + return new String(fieldInfo1.getDescriptor()).compareTo(new String(fieldInfo2.getDescriptor())); + } + return compare; + } + }); + for (int i = 0, max = fields.length; i < max; i++) { + writeNewLine(buffer, lineSeparator, tabNumber); + disassemble(fields[i], buffer, lineSeparator, tabNumber, mode); + } + MethodInfo[] methods = classFileReader.getMethodInfos(); + // sort methods + Arrays.sort(methods, new Comparator() { + public int compare(MethodInfo methodInfo1, MethodInfo methodInfo2) { + int compare = new String(methodInfo1.getName()).compareTo(new String(methodInfo2.getName())); + if (compare == 0) { + return new String(methodInfo1.getDescriptor()).compareTo(new String(methodInfo2.getDescriptor())); + } + return compare; + } + }); + for (int i = 0, max = methods.length; i < max; i++) { + writeNewLine(buffer, lineSeparator, tabNumber); + disassemble(classFileReader, className, methods[i], buffer, lineSeparator, tabNumber, mode); + } + } + + private final void dumpTab(int tabNumber, StringBuffer buffer) { + for (int i = 0; i < tabNumber; i++) { + buffer.append(Messages.disassembler_indentation); + } + } + + private EnclosingMethodAttribute getEnclosingMethodAttribute(ClassFileReader classFileReader) { + ClassFileAttribute[] attributes = classFileReader.getAttributes(); + for (int i = 0, max = attributes.length; i < max; i++) { + if (Arrays.equals(attributes[i].getAttributeName(), AttributeNamesConstants.ENCLOSING_METHOD)) { + return (EnclosingMethodAttribute) attributes[i]; + } + } + return null; + } + + private char[] getSignatureForField(char[] fieldDescriptor) { + char[] newFieldDescriptor = CharOperation.replaceOnCopy(fieldDescriptor, '/', '.'); + newFieldDescriptor = CharOperation.replaceOnCopy(newFieldDescriptor, '$', '%'); + char[] fieldDescriptorSignature = Signature.toCharArray(newFieldDescriptor); + CharOperation.replace(fieldDescriptorSignature, '%', '$'); + return fieldDescriptorSignature; + } + + private boolean isDeprecated(ClassFileReader classFileReader) { + ClassFileAttribute[] attributes = classFileReader.getAttributes(); + for (int i = 0, max = attributes.length; i < max; i++) { + if (Arrays.equals(attributes[i].getAttributeName(), AttributeNamesConstants.DEPRECATED)) { + return true; + } + } + return false; + } + + private boolean isSynthetic(ClassFileReader classFileReader) { + int flags = classFileReader.getAccessFlags(); + if ((flags & IModifierConstants.ACC_SYNTHETIC) != 0) { + return true; + } + ClassFileAttribute[] attributes = classFileReader.getAttributes(); + for (int i = 0, max = attributes.length; i < max; i++) { + if (Arrays.equals(attributes[i].getAttributeName(), AttributeNamesConstants.SYNTHETIC)) { + return true; + } + } + return false; + } + + private boolean checkMode(int mode, int flag) { + return (mode & flag) != 0; + } + + private boolean isCompact(int mode) { + return (mode & Disassembler.COMPACT) != 0; + } + + private char[] returnClassName(char[] classInfoName, char separator, int mode) { + if (classInfoName.length == 0) { + return CharOperation.NO_CHAR; + } else if (isCompact(mode)) { + int lastIndexOfSlash = CharOperation.lastIndexOf(separator, classInfoName); + if (lastIndexOfSlash != -1) { + return CharOperation.subarray(classInfoName, lastIndexOfSlash + 1, classInfoName.length); + } + } + return classInfoName; + } + + private void writeNewLine(StringBuffer buffer, String lineSeparator, int tabNumber) { + buffer.append(lineSeparator); + dumpTab(tabNumber, buffer); + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/EnclosingMethodAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/EnclosingMethodAttribute.java new file mode 100644 index 000000000..a7daac77d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/EnclosingMethodAttribute.java @@ -0,0 +1,101 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class EnclosingMethodAttribute extends ClassFileAttribute { + + private int enclosingClassIndex; + private char[] enclosingClassName; + private int methodDescriptorIndex; + private char[] methodDescriptor; + private int methodNameIndex; + private char[] methodName; + private int methodNameAndTypeIndex; + + EnclosingMethodAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + super(classFileBytes, constantPool, offset); + int index = u2At(classFileBytes, 6, offset); + this.enclosingClassIndex = index; + ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.enclosingClassName = constantPoolEntry.getClassInfoName(); + this.methodNameAndTypeIndex = u2At(classFileBytes, 8, offset); + if (this.methodNameAndTypeIndex != 0) { + constantPoolEntry = constantPool.decodeEntry(this.methodNameAndTypeIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_NameAndType) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.methodDescriptorIndex = constantPoolEntry.getNameAndTypeInfoDescriptorIndex(); + this.methodNameIndex = constantPoolEntry.getNameAndTypeInfoNameIndex(); + constantPoolEntry = constantPool.decodeEntry(this.methodDescriptorIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.methodDescriptor = constantPoolEntry.getUtf8Value(); + constantPoolEntry = constantPool.decodeEntry(this.methodNameIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.methodName = constantPoolEntry.getUtf8Value(); + } + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IEnclosingMethodAttribute#getEnclosingClass() + */ + public char[] getEnclosingClass() { + return this.enclosingClassName; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IEnclosingMethodAttribute#getMethodDeclaringClassDescriptorIndex() + */ + public int getEnclosingClassIndex() { + return this.enclosingClassIndex; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IEnclosingMethodAttribute#getMethodDescriptor() + */ + public char[] getMethodDescriptor() { + return this.methodDescriptor; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IEnclosingMethodAttribute#getMethodDescriptorIndex() + */ + public int getMethodDescriptorIndex() { + return this.methodDescriptorIndex; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IEnclosingMethodAttribute#getMethodName() + */ + public char[] getMethodName() { + return this.methodName; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IEnclosingMethodAttribute#getMethodNameIndex() + */ + public int getMethodNameIndex() { + return this.methodNameIndex; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IEnclosingMethodAttribute#getMethodNameAndTypeIndex() + */ + public int getMethodNameAndTypeIndex() { + return this.methodNameAndTypeIndex; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ExceptionAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ExceptionAttribute.java new file mode 100644 index 000000000..7883c093a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ExceptionAttribute.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class ExceptionAttribute extends ClassFileAttribute { + private int exceptionsNumber; + private char[][] exceptionNames; + private int[] exceptionIndexes; + + ExceptionAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + super(classFileBytes, constantPool, offset); + this.exceptionsNumber = u2At(classFileBytes, 6, offset); + int exceptionLength = this.exceptionsNumber; + this.exceptionNames = CharOperation.NO_CHAR_CHAR; + this.exceptionIndexes = Utility.EMPTY_INT_ARRAY; + if (exceptionLength != 0) { + this.exceptionNames = new char[exceptionLength][]; + this.exceptionIndexes = new int[exceptionLength]; + } + int readOffset = 8; + ConstantPoolEntry constantPoolEntry; + for (int i = 0; i < exceptionLength; i++) { + this.exceptionIndexes[i] = u2At(classFileBytes, readOffset, offset); + constantPoolEntry = constantPool.decodeEntry(this.exceptionIndexes[i]); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.exceptionNames[i] = constantPoolEntry.getClassInfoName(); + readOffset += 2; + } + } + + /* + * @see IExceptionAttribute#getExceptionIndexes() + */ + public int[] getExceptionIndexes() { + return this.exceptionIndexes; + } + + /* + * @see IExceptionAttribute#getExceptionNames() + */ + public char[][] getExceptionNames() { + return this.exceptionNames; + } + + /* + * @see IExceptionAttribute#getExceptionsNumber() + */ + public int getExceptionsNumber() { + return this.exceptionsNumber; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ExceptionTableEntry.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ExceptionTableEntry.java new file mode 100644 index 000000000..0598acf2a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ExceptionTableEntry.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class ExceptionTableEntry extends ClassFileStruct { + + private int startPC; + private int endPC; + private int handlerPC; + private int catchTypeIndex; + private char[] catchType; + + ExceptionTableEntry(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + this.startPC = u2At(classFileBytes, 0, offset); + this.endPC = u2At(classFileBytes, 2, offset); + this.handlerPC = u2At(classFileBytes, 4, offset); + this.catchTypeIndex = u2At(classFileBytes, 6, offset); + if (this.catchTypeIndex != 0) { + ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(this.catchTypeIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.catchType = constantPoolEntry.getClassInfoName(); + } + } + + /* + * @see IExceptionTableEntry#getStartPC() + */ + public int getStartPC() { + return this.startPC; + } + + /* + * @see IExceptionTableEntry#getEndPC() + */ + public int getEndPC() { + return this.endPC; + } + + /* + * @see IExceptionTableEntry#getHandlerPC() + */ + public int getHandlerPC() { + return this.handlerPC; + } + + /* + * @see IExceptionTableEntry#getCatchTypeIndex() + */ + public int getCatchTypeIndex() { + return this.catchTypeIndex; + } + + /* + * @see IExceptionTableEntry#getCatchType() + */ + public char[] getCatchType() { + return this.catchType; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/FieldInfo.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/FieldInfo.java new file mode 100644 index 000000000..46b79c64d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/FieldInfo.java @@ -0,0 +1,170 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +import java.util.Arrays; + +public class FieldInfo extends ClassFileStruct { + private int accessFlags; + private int attributeBytes; + private ClassFileAttribute[] attributes; + private int attributesCount; + private ConstantValueAttribute constantValueAttribute; + private char[] descriptor; + private int descriptorIndex; + private boolean isDeprecated; + private boolean isSynthetic; + private char[] name; + private int nameIndex; + + /* + * @param classFileBytes byte[] + * @param constantPool IConstantPool + * @param offset int + */ + public FieldInfo(byte classFileBytes[], ConstantPool constantPool, int offset) throws ClassFormatException { + final int flags = u2At(classFileBytes, 0, offset); + this.accessFlags = flags; + if ((flags & IModifierConstants.ACC_SYNTHETIC) != 0) { + this.isSynthetic = true; + } + this.nameIndex = u2At(classFileBytes, 2, offset); + ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(this.nameIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.name = constantPoolEntry.getUtf8Value(); + + this.descriptorIndex = u2At(classFileBytes, 4, offset); + constantPoolEntry = constantPool.decodeEntry(this.descriptorIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.descriptor = constantPoolEntry.getUtf8Value(); + + this.attributesCount = u2At(classFileBytes, 6, offset); + this.attributes = ClassFileAttribute.NO_ATTRIBUTES; + int readOffset = 8; + if (this.attributesCount != 0) { + this.attributes = new ClassFileAttribute[this.attributesCount]; + } + int attributesIndex = 0; + for (int i = 0; i < this.attributesCount; i++) { + constantPoolEntry = constantPool.decodeEntry(u2At(classFileBytes, readOffset, offset)); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + char[] attributeName = constantPoolEntry.getUtf8Value(); + if (Arrays.equals(attributeName, AttributeNamesConstants.DEPRECATED)) { + this.isDeprecated = true; + this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, constantPool, offset + readOffset); + } else if (Arrays.equals(attributeName, AttributeNamesConstants.SYNTHETIC)) { + this.isSynthetic = true; + this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, constantPool, offset + readOffset); + } else if (Arrays.equals(attributeName, AttributeNamesConstants.CONSTANT_VALUE)) { + this.constantValueAttribute = new ConstantValueAttribute(classFileBytes, constantPool, offset + readOffset); + this.attributes[attributesIndex++] = this.constantValueAttribute; + } else if (Arrays.equals(attributeName, AttributeNamesConstants.SIGNATURE)) { + this.attributes[attributesIndex++] = new SignatureAttribute(classFileBytes, constantPool, offset + readOffset); + } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_VISIBLE_ANNOTATIONS)) { + this.attributes[attributesIndex++] = new RuntimeVisibleAnnotationsAttribute(classFileBytes, constantPool, offset + readOffset); + } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS)) { + this.attributes[attributesIndex++] = new RuntimeInvisibleAnnotationsAttribute(classFileBytes, constantPool, offset + readOffset); + } else { + this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, constantPool, offset + readOffset); + } + readOffset += (6 + u4At(classFileBytes, readOffset + 2, offset)); + } + + this.attributeBytes = readOffset; + } + + /* + * @see IFieldInfo#getAccessFlags() + */ + public int getAccessFlags() { + return this.accessFlags; + } + + /* + * @see IFieldInfo#getAttributeCount() + */ + public int getAttributeCount() { + return this.attributesCount; + } + + /* + * @see IFieldInfo#getAttributes() + */ + public ClassFileAttribute[] getAttributes() { + return this.attributes; + } + + /* + * @see IFieldInfo#getConstantValueAttribute() + */ + public ConstantValueAttribute getConstantValueAttribute() { + return this.constantValueAttribute; + } + + /* + * @see IFieldInfo#getDescriptor() + */ + public char[] getDescriptor() { + return this.descriptor; + } + + /* + * @see IFieldInfo#getDescriptorIndex() + */ + public int getDescriptorIndex() { + return this.descriptorIndex; + } + + /* + * @see IFieldInfo#getName() + */ + public char[] getName() { + return this.name; + } + + /* + * @see IFieldInfo#getNameIndex() + */ + public int getNameIndex() { + return this.nameIndex; + } + + /* + * @see IFieldInfo#hasConstantValueAttribute() + */ + public boolean hasConstantValueAttribute() { + return this.constantValueAttribute != null; + } + + /* + * @see IFieldInfo#isDeprecated() + */ + public boolean isDeprecated() { + return this.isDeprecated; + } + + /* + * @see IFieldInfo#isSynthetic() + */ + public boolean isSynthetic() { + return this.isSynthetic; + } + + int sizeInBytes() { + return this.attributeBytes; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/IModifierConstants.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/IModifierConstants.java new file mode 100644 index 000000000..b869fdbc1 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/IModifierConstants.java @@ -0,0 +1,104 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public interface IModifierConstants { + + int ACC_PUBLIC = 0x0001; + int ACC_PRIVATE = 0x0002; + int ACC_PROTECTED = 0x0004; + int ACC_STATIC = 0x0008; + int ACC_FINAL = 0x0010; + int ACC_SUPER = 0x0020; + int ACC_SYNCHRONIZED = 0x0020; + int ACC_VOLATILE = 0x0040; + + /** + * Indicates a bridge method (added in J2SE 1.5). + * @since 3.0 + */ + int ACC_BRIDGE = 0x0040; + int ACC_TRANSIENT = 0x0080; + + /** + * Indicates a variable arity method (added in J2SE 1.5). + * @since 3.0 + */ + int ACC_VARARGS = 0x0080; + int ACC_NATIVE = 0x0100; + int ACC_INTERFACE = 0x0200; + int ACC_ABSTRACT = 0x0400; + int ACC_STRICT = 0x0800; + /** + * Indicates a synthetic member. + * @since 3.0 + */ + int ACC_SYNTHETIC = 0x1000; + + /** + * Indicates an annotation (added in J2SE 1.5). + * @since 3.0 + */ + int ACC_ANNOTATION = 0x2000; + + /** + * Indicates an enum (added in J2SE 1.5). + * @since 3.0 + */ + int ACC_ENUM = 0x4000; + + /** + * Configurable option value: {@value}. + * @category OptionValue + */ + public static final String VERSION_1_1 = "1.1"; //$NON-NLS-1$ + /** + * Configurable option value: {@value}. + * @category OptionValue + */ + public static final String VERSION_1_2 = "1.2"; //$NON-NLS-1$ + /** + * Configurable option value: {@value}. + * @since 2.0 + * @category OptionValue + */ + public static final String VERSION_1_3 = "1.3"; //$NON-NLS-1$ + /** + * Configurable option value: {@value}. + * @since 2.0 + * @category OptionValue + */ + public static final String VERSION_1_4 = "1.4"; //$NON-NLS-1$ + /** + * Configurable option value: {@value}. + * @since 3.0 + * @category OptionValue + */ + public static final String VERSION_1_5 = "1.5"; //$NON-NLS-1$ + /** + * Configurable option value: {@value}. + * @since 3.2 + * @category OptionValue + */ + public static final String VERSION_1_6 = "1.6"; //$NON-NLS-1$ + /** + * Configurable option value: {@value}. + * @since 3.3 + * @category OptionValue + */ + public static final String VERSION_1_7 = "1.7"; //$NON-NLS-1$ + /** + * Configurable option value: {@value}. + * @since 3.4 + * @category OptionValue + */ + public static final String VERSION_CLDC_1_1 = "cldc1.1"; //$NON-NLS-1$ +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/IOpcodeMnemonics.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/IOpcodeMnemonics.java new file mode 100644 index 000000000..a6de65d6b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/IOpcodeMnemonics.java @@ -0,0 +1,220 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public interface IOpcodeMnemonics { + + int NOP = 0x00; + int ACONST_NULL = 0x01; + int ICONST_M1 = 0x02; + int ICONST_0 = 0x03; + int ICONST_1 = 0x04; + int ICONST_2 = 0x05; + int ICONST_3 = 0x06; + int ICONST_4 = 0x07; + int ICONST_5 = 0x08; + int LCONST_0 = 0x09; + int LCONST_1 = 0x0A; + int FCONST_0 = 0x0B; + int FCONST_1 = 0x0C; + int FCONST_2 = 0x0D; + int DCONST_0 = 0x0E; + int DCONST_1 = 0x0F; + int BIPUSH = 0x10; + int SIPUSH = 0x11; + int LDC = 0x12; + int LDC_W = 0x13; + int LDC2_W = 0x14; + int ILOAD = 0x15; + int LLOAD = 0x16; + int FLOAD = 0x17; + int DLOAD = 0x18; + int ALOAD = 0x19; + int ILOAD_0 = 0x1A; + int ILOAD_1 = 0x1B; + int ILOAD_2 = 0x1C; + int ILOAD_3 = 0x1D; + int LLOAD_0 = 0x1E; + int LLOAD_1 = 0x1F; + int LLOAD_2 = 0x20; + int LLOAD_3 = 0x21; + int FLOAD_0 = 0x22; + int FLOAD_1 = 0x23; + int FLOAD_2 = 0x24; + int FLOAD_3 = 0x25; + int DLOAD_0 = 0x26; + int DLOAD_1 = 0x27; + int DLOAD_2 = 0x28; + int DLOAD_3 = 0x29; + int ALOAD_0 = 0x2A; + int ALOAD_1 = 0x2B; + int ALOAD_2 = 0x2C; + int ALOAD_3 = 0x2D; + int IALOAD = 0x2E; + int LALOAD = 0x2F; + int FALOAD = 0x30; + int DALOAD = 0x31; + int AALOAD = 0x32; + int BALOAD = 0x33; + int CALOAD = 0x34; + int SALOAD = 0x35; + int ISTORE = 0x36; + int LSTORE = 0x37; + int FSTORE = 0x38; + int DSTORE = 0x39; + int ASTORE = 0x3A; + int ISTORE_0 = 0x3B; + int ISTORE_1 = 0x3C; + int ISTORE_2 = 0x3D; + int ISTORE_3 = 0x3E; + int LSTORE_0 = 0x3F; + int LSTORE_1 = 0x40; + int LSTORE_2 = 0x41; + int LSTORE_3 = 0x42; + int FSTORE_0 = 0x43; + int FSTORE_1 = 0x44; + int FSTORE_2 = 0x45; + int FSTORE_3 = 0x46; + int DSTORE_0 = 0x47; + int DSTORE_1 = 0x48; + int DSTORE_2 = 0x49; + int DSTORE_3 = 0x4A; + int ASTORE_0 = 0x4B; + int ASTORE_1 = 0x4C; + int ASTORE_2 = 0x4D; + int ASTORE_3 = 0x4E; + int IASTORE = 0x4F; + int LASTORE = 0x50; + int FASTORE = 0x51; + int DASTORE = 0x52; + int AASTORE = 0x53; + int BASTORE = 0x54; + int CASTORE = 0x55; + int SASTORE = 0x56; + int POP = 0x57; + int POP2 = 0x58; + int DUP = 0x59; + int DUP_X1 = 0x5A; + int DUP_X2 = 0x5B; + int DUP2 = 0x5C; + int DUP2_X1 = 0x5D; + int DUP2_X2 = 0x5E; + int SWAP = 0x5F; + int IADD = 0x60; + int LADD = 0x61; + int FADD = 0x62; + int DADD = 0x63; + int ISUB = 0x64; + int LSUB = 0x65; + int FSUB = 0x66; + int DSUB = 0x67; + int IMUL = 0x68; + int LMUL = 0x69; + int FMUL = 0x6A; + int DMUL = 0x6B; + int IDIV = 0x6C; + int LDIV = 0x6D; + int FDIV = 0x6E; + int DDIV = 0x6F; + int IREM = 0x70; + int LREM = 0x71; + int FREM = 0x72; + int DREM = 0x73; + int INEG = 0x74; + int LNEG = 0x75; + int FNEG = 0x76; + int DNEG = 0x77; + int ISHL = 0x78; + int LSHL = 0x79; + int ISHR = 0x7A; + int LSHR = 0x7B; + int IUSHR = 0x7C; + int LUSHR = 0x7D; + int IAND = 0x7E; + int LAND = 0x7F; + int IOR = 0x80; + int LOR = 0x81; + int IXOR = 0x82; + int LXOR = 0x83; + int IINC = 0x84; + int I2L = 0x85; + int I2F = 0x86; + int I2D = 0x87; + int L2I = 0x88; + int L2F = 0x89; + int L2D = 0x8A; + int F2I = 0x8B; + int F2L = 0x8C; + int F2D = 0x8D; + int D2I = 0x8E; + int D2L = 0x8F; + int D2F = 0x90; + int I2B = 0x91; + int I2C = 0x92; + int I2S = 0x93; + int LCMP = 0x94; + int FCMPL = 0x95; + int FCMPG = 0x96; + int DCMPL = 0x97; + int DCMPG = 0x98; + int IFEQ = 0x99; + int IFNE = 0x9A; + int IFLT = 0x9B; + int IFGE = 0x9C; + int IFGT = 0x9D; + int IFLE = 0x9E; + int IF_ICMPEQ = 0x9F; + int IF_ICMPNE = 0xA0; + int IF_ICMPLT = 0xA1; + int IF_ICMPGE = 0xA2; + int IF_ICMPGT = 0xA3; + int IF_ICMPLE = 0xA4; + int IF_ACMPEQ = 0xA5; + int IF_ACMPNE = 0xA6; + int GOTO = 0xA7; + int JSR = 0xA8; + int RET = 0xA9; + int TABLESWITCH = 0xAA; + int LOOKUPSWITCH = 0xAB; + int IRETURN = 0xAC; + int LRETURN = 0xAD; + int FRETURN = 0xAE; + int DRETURN = 0xAF; + int ARETURN = 0xB0; + int RETURN = 0xB1; + int GETSTATIC = 0xB2; + int PUTSTATIC = 0xB3; + int GETFIELD = 0xB4; + int PUTFIELD = 0xB5; + int INVOKEVIRTUAL = 0xB6; + int INVOKESPECIAL = 0xB7; + int INVOKESTATIC = 0xB8; + int INVOKEINTERFACE = 0xB9; + int NEW = 0xBB; + int NEWARRAY = 0xBC; + int ANEWARRAY = 0xBD; + int ARRAYLENGTH = 0xBE; + int ATHROW = 0xBF; + int CHECKCAST = 0xC0; + int INSTANCEOF = 0xC1; + int MONITORENTER = 0xC2; + int MONITOREXIT = 0xC3; + int WIDE = 0xC4; + int MULTIANEWARRAY = 0xC5; + int IFNULL = 0xC6; + int IFNONNULL = 0xC7; + int GOTO_W = 0xC8; + int JSR_W = 0xC9; + + int BREAKPOINT = 0xCA; + int IMPDEP1 = 0xFE; + int IMPDEP2 = 0xFF; +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/InnerClassesAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/InnerClassesAttribute.java new file mode 100644 index 000000000..a9202fe72 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/InnerClassesAttribute.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class InnerClassesAttribute extends ClassFileAttribute { + private static final InnerClassesAttributeEntry[] NO_ENTRIES = new InnerClassesAttributeEntry[0]; + + private int numberOfClasses; + private InnerClassesAttributeEntry[] entries; + + /** + * Constructor for InnerClassesAttribute. + * @param classFileBytes + * @param constantPool + * @param offset + * @throws ClassFormatException + */ + public InnerClassesAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + super(classFileBytes, constantPool, offset); + this.numberOfClasses = u2At(classFileBytes, 6, offset); + final int length = this.numberOfClasses; + if (length != 0) { + int readOffset = 8; + this.entries = new InnerClassesAttributeEntry[length]; + for (int i = 0; i < length; i++) { + this.entries[i] = new InnerClassesAttributeEntry(classFileBytes, constantPool, offset + readOffset); + readOffset += 8; + } + } else { + this.entries = NO_ENTRIES; + } + } + + /* + * @see IInnerClassesAttribute#getInnerClassAttributesEntries() + */ + public InnerClassesAttributeEntry[] getInnerClassAttributesEntries() { + return this.entries; + } + + /* + * @see IInnerClassesAttribute#getNumberOfClasses() + */ + public int getNumberOfClasses() { + return this.numberOfClasses; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/InnerClassesAttributeEntry.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/InnerClassesAttributeEntry.java new file mode 100644 index 000000000..2c63c8a44 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/InnerClassesAttributeEntry.java @@ -0,0 +1,100 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class InnerClassesAttributeEntry extends ClassFileStruct { + + private int innerClassNameIndex; + private int outerClassNameIndex; + private int innerNameIndex; + private char[] innerClassName; + private char[] outerClassName; + private char[] innerName; + private int accessFlags; + + public InnerClassesAttributeEntry(byte classFileBytes[], ConstantPool constantPool, int offset) throws ClassFormatException { + this.innerClassNameIndex = u2At(classFileBytes, 0, offset); + this.outerClassNameIndex = u2At(classFileBytes, 2, offset); + this.innerNameIndex = u2At(classFileBytes, 4, offset); + this.accessFlags = u2At(classFileBytes, 6, offset); + ConstantPoolEntry constantPoolEntry; + if (this.innerClassNameIndex != 0) { + constantPoolEntry = constantPool.decodeEntry(this.innerClassNameIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.innerClassName = constantPoolEntry.getClassInfoName(); + } + if (this.outerClassNameIndex != 0) { + constantPoolEntry = constantPool.decodeEntry(this.outerClassNameIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Class) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.outerClassName = constantPoolEntry.getClassInfoName(); + } + if (this.innerNameIndex != 0) { + constantPoolEntry = constantPool.decodeEntry(this.innerNameIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.innerName = constantPoolEntry.getUtf8Value(); + } + } + + /* + * @see IInnerClassesAttributeEntry#getAccessFlags() + */ + public int getAccessFlags() { + return this.accessFlags; + } + + /* + * @see IInnerClassesAttributeEntry#getInnerClassName() + */ + public char[] getInnerClassName() { + return this.innerClassName; + } + + /* + * @see IInnerClassesAttributeEntry#getInnerClassNameIndex() + */ + public int getInnerClassNameIndex() { + return this.innerClassNameIndex; + } + + /* + * @see IInnerClassesAttributeEntry#getInnerName() + */ + public char[] getInnerName() { + return this.innerName; + } + + /* + * @see IInnerClassesAttributeEntry#getInnerNameIndex() + */ + public int getInnerNameIndex() { + return this.innerNameIndex; + } + + /* + * @see IInnerClassesAttributeEntry#getOuterClassName() + */ + public char[] getOuterClassName() { + return this.outerClassName; + } + + /* + * @see IInnerClassesAttributeEntry#getOuterClassNameIndex() + */ + public int getOuterClassNameIndex() { + return this.outerClassNameIndex; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Messages.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Messages.java new file mode 100644 index 000000000..8c2076f23 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Messages.java @@ -0,0 +1,107 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +import org.eclipse.osgi.util.NLS; + +public class Messages extends NLS { + private static final String BUNDLE_NAME = "org.eclipse.equinox.p2.internal.repository.comparator.messages"; //$NON-NLS-1$ + public static String differentNumberOfEntries; + public static String differentEntry; + public static String missingEntry; + public static String ioexception; + public static String disassembler_opentypedeclaration; + public static String disassembler_closetypedeclaration; + public static String disassembler_endofmethodheader; + public static String disassembler_begincommentline; + public static String disassembler_fieldhasconstant; + public static String disassembler_endoffieldheader; + public static String disassembler_sourceattributeheader; + public static String disassembler_enclosingmethodheader; + public static String disassembler_exceptiontableheader; + public static String disassembler_innerattributesheader; + public static String disassembler_inner_class_info_name; + public static String disassembler_outer_class_info_name; + public static String disassembler_inner_name; + public static String disassembler_inner_accessflags; + public static String disassembler_signatureattributeheader; + public static String disassembler_indentation; + public static String disassembler_space; + public static String disassembler_comma; + public static String disassembler_openinnerclassentry; + public static String disassembler_closeinnerclassentry; + public static String disassembler_deprecated; + public static String disassembler_annotationdefaultheader; + public static String disassembler_annotationdefaultvalue; + public static String disassembler_annotationenumvalue; + public static String disassembler_annotationclassvalue; + public static String disassembler_annotationannotationvalue; + public static String disassembler_annotationarrayvaluestart; + public static String disassembler_annotationarrayvalueend; + public static String disassembler_annotationentrystart; + public static String disassembler_annotationentryend; + public static String disassembler_annotationcomponent; + public static String disassembler_runtimevisibleannotationsattributeheader; + public static String disassembler_runtimeinvisibleannotationsattributeheader; + public static String disassembler_runtimevisibleparameterannotationsattributeheader; + public static String disassembler_runtimeinvisibleparameterannotationsattributeheader; + public static String disassembler_parameterannotationentrystart; + public static String classfileformat_versiondetails; + public static String classfileformat_methoddescriptor; + public static String classfileformat_fieldddescriptor; + public static String classfileformat_stacksAndLocals; + public static String classfileformat_superflagisnotset; + public static String classfileformat_superflagisset; + public static String classfileformat_clinitname; + public static String classformat_classformatexception; + public static String classformat_anewarray; + public static String classformat_checkcast; + public static String classformat_instanceof; + public static String classformat_ldc_w_class; + public static String classformat_ldc_w_float; + public static String classformat_ldc_w_integer; + public static String classformat_ldc_w_string; + public static String classformat_ldc2_w_long; + public static String classformat_ldc2_w_double; + public static String classformat_multianewarray; + public static String classformat_new; + public static String classformat_iinc; + public static String classformat_invokespecial; + public static String classformat_invokeinterface; + public static String classformat_invokestatic; + public static String classformat_invokevirtual; + public static String classformat_getfield; + public static String classformat_getstatic; + public static String classformat_putstatic; + public static String classformat_putfield; + public static String classformat_newarray_boolean; + public static String classformat_newarray_char; + public static String classformat_newarray_float; + public static String classformat_newarray_double; + public static String classformat_newarray_byte; + public static String classformat_newarray_short; + public static String classformat_newarray_int; + public static String classformat_newarray_long; + public static String classformat_store; + public static String classformat_load; + public static String classfileformat_anyexceptionhandler; + public static String classfileformat_exceptiontableentry; + public static String classfileformat_versionUnknown; + + static { + // initialize resource bundle + NLS.initializeMessages(BUNDLE_NAME, Messages.class); + } + + private Messages() { + // prevent instantiation + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/MethodInfo.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/MethodInfo.java new file mode 100644 index 000000000..14d57c21b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/MethodInfo.java @@ -0,0 +1,213 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +import java.util.Arrays; + +public class MethodInfo extends ClassFileStruct { + private int accessFlags; + private int attributeBytes; + private ClassFileAttribute[] attributes; + private int attributesCount; + private CodeAttribute codeAttribute; + private char[] descriptor; + private int descriptorIndex; + private ExceptionAttribute exceptionAttribute; + private boolean isDeprecated; + private boolean isSynthetic; + private char[] name; + private int nameIndex; + + /* + * @param classFileBytes byte[] + * @param constantPool IConstantPool + * @param offset int + * @param decodingFlags int + */ + public MethodInfo(byte classFileBytes[], ConstantPool constantPool, int offset, int decodingFlags) throws ClassFormatException { + + boolean no_code_attribute = (decodingFlags & ClassFileReader.METHOD_BODIES) == 0; + final int flags = u2At(classFileBytes, 0, offset); + this.accessFlags = flags; + if ((flags & IModifierConstants.ACC_SYNTHETIC) != 0) { + this.isSynthetic = true; + } + + this.nameIndex = u2At(classFileBytes, 2, offset); + ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(this.nameIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.name = constantPoolEntry.getUtf8Value(); + + this.descriptorIndex = u2At(classFileBytes, 4, offset); + constantPoolEntry = constantPool.decodeEntry(this.descriptorIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.descriptor = constantPoolEntry.getUtf8Value(); + + this.attributesCount = u2At(classFileBytes, 6, offset); + this.attributes = ClassFileAttribute.NO_ATTRIBUTES; + if (this.attributesCount != 0) { + if (no_code_attribute && !isAbstract() && !isNative()) { + if (this.attributesCount != 1) { + this.attributes = new ClassFileAttribute[this.attributesCount - 1]; + } + } else { + this.attributes = new ClassFileAttribute[this.attributesCount]; + } + } + int attributesIndex = 0; + int readOffset = 8; + for (int i = 0; i < this.attributesCount; i++) { + constantPoolEntry = constantPool.decodeEntry(u2At(classFileBytes, readOffset, offset)); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + char[] attributeName = constantPoolEntry.getUtf8Value(); + if (Arrays.equals(attributeName, AttributeNamesConstants.DEPRECATED)) { + this.isDeprecated = true; + this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, constantPool, offset + readOffset); + } else if (Arrays.equals(attributeName, AttributeNamesConstants.SYNTHETIC)) { + this.isSynthetic = true; + this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, constantPool, offset + readOffset); + } else if (Arrays.equals(attributeName, AttributeNamesConstants.CODE)) { + if (!no_code_attribute) { + this.codeAttribute = new CodeAttribute(classFileBytes, constantPool, offset + readOffset); + this.attributes[attributesIndex++] = this.codeAttribute; + } + } else if (Arrays.equals(attributeName, AttributeNamesConstants.EXCEPTIONS)) { + this.exceptionAttribute = new ExceptionAttribute(classFileBytes, constantPool, offset + readOffset); + this.attributes[attributesIndex++] = this.exceptionAttribute; + } else if (Arrays.equals(attributeName, AttributeNamesConstants.SIGNATURE)) { + this.attributes[attributesIndex++] = new SignatureAttribute(classFileBytes, constantPool, offset + readOffset); + } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_VISIBLE_ANNOTATIONS)) { + this.attributes[attributesIndex++] = new RuntimeVisibleAnnotationsAttribute(classFileBytes, constantPool, offset + readOffset); + } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_INVISIBLE_ANNOTATIONS)) { + this.attributes[attributesIndex++] = new RuntimeInvisibleAnnotationsAttribute(classFileBytes, constantPool, offset + readOffset); + } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS)) { + this.attributes[attributesIndex++] = new RuntimeVisibleParameterAnnotationsAttribute(classFileBytes, constantPool, offset + readOffset); + } else if (Arrays.equals(attributeName, AttributeNamesConstants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS)) { + this.attributes[attributesIndex++] = new RuntimeInvisibleParameterAnnotationsAttribute(classFileBytes, constantPool, offset + readOffset); + } else if (Arrays.equals(attributeName, AttributeNamesConstants.ANNOTATION_DEFAULT)) { + this.attributes[attributesIndex++] = new AnnotationDefaultAttribute(classFileBytes, constantPool, offset + readOffset); + } else { + this.attributes[attributesIndex++] = new ClassFileAttribute(classFileBytes, constantPool, offset + readOffset); + } + readOffset += (6 + u4At(classFileBytes, readOffset + 2, offset)); + } + this.attributeBytes = readOffset; + } + + /* + * @see IMethodInfo#getAccessFlags() + */ + public int getAccessFlags() { + return this.accessFlags; + } + + /* + * @see IMethodInfo#getAttributeCount() + */ + public int getAttributeCount() { + return this.attributesCount; + } + + /* + * @see IMethodInfo#getAttributes() + */ + public ClassFileAttribute[] getAttributes() { + return this.attributes; + } + + /* + * @see IMethodInfo#getCodeAttribute() + */ + public CodeAttribute getCodeAttribute() { + return this.codeAttribute; + } + + /* + * @see IMethodInfo#getDescriptor() + */ + public char[] getDescriptor() { + return this.descriptor; + } + + /* + * @see IMethodInfo#getDescriptorIndex() + */ + public int getDescriptorIndex() { + return this.descriptorIndex; + } + + /* + * @see IMethodInfo#getExceptionAttribute() + */ + public ExceptionAttribute getExceptionAttribute() { + return this.exceptionAttribute; + } + + /* + * @see IMethodInfo#getName() + */ + public char[] getName() { + return this.name; + } + + /* + * @see IMethodInfo#getNameIndex() + */ + public int getNameIndex() { + return this.nameIndex; + } + + private boolean isAbstract() { + return (this.accessFlags & IModifierConstants.ACC_ABSTRACT) != 0; + } + + /* + * @see IMethodInfo#isClinit() + */ + public boolean isClinit() { + return this.name[0] == '<' && this.name.length == 8; // Can only match + } + + /* + * @see IMethodInfo#isConstructor() + */ + public boolean isConstructor() { + return this.name[0] == '<' && this.name.length == 6; // Can only match + } + + /* + * @see IMethodInfo#isDeprecated() + */ + public boolean isDeprecated() { + return this.isDeprecated; + } + + private boolean isNative() { + return (this.accessFlags & IModifierConstants.ACC_NATIVE) != 0; + } + + /* + * @see IMethodInfo#isSynthetic() + */ + public boolean isSynthetic() { + return this.isSynthetic; + } + + int sizeInBytes() { + return this.attributeBytes; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/OpcodeStringValues.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/OpcodeStringValues.java new file mode 100644 index 000000000..dbc879e9b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/OpcodeStringValues.java @@ -0,0 +1,222 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class OpcodeStringValues implements IOpcodeMnemonics { + + public static final String[] BYTECODE_NAMES = new String[256]; + static { + BYTECODE_NAMES[NOP] = "nop"; //$NON-NLS-1$ + BYTECODE_NAMES[ACONST_NULL] = "aconst_null"; //$NON-NLS-1$ + BYTECODE_NAMES[ICONST_M1] = "iconst_m1"; //$NON-NLS-1$ + BYTECODE_NAMES[ICONST_0] = "iconst_0"; //$NON-NLS-1$ + BYTECODE_NAMES[ICONST_1] = "iconst_1"; //$NON-NLS-1$ + BYTECODE_NAMES[ICONST_2] = "iconst_2"; //$NON-NLS-1$ + BYTECODE_NAMES[ICONST_3] = "iconst_3"; //$NON-NLS-1$ + BYTECODE_NAMES[ICONST_4] = "iconst_4"; //$NON-NLS-1$ + BYTECODE_NAMES[ICONST_5] = "iconst_5"; //$NON-NLS-1$ + BYTECODE_NAMES[LCONST_0] = "lconst_0"; //$NON-NLS-1$ + BYTECODE_NAMES[LCONST_1] = "lconst_1"; //$NON-NLS-1$ + BYTECODE_NAMES[FCONST_0] = "fconst_0"; //$NON-NLS-1$ + BYTECODE_NAMES[FCONST_1] = "fconst_1"; //$NON-NLS-1$ + BYTECODE_NAMES[FCONST_2] = "fconst_2"; //$NON-NLS-1$ + BYTECODE_NAMES[DCONST_0] = "dconst_0"; //$NON-NLS-1$ + BYTECODE_NAMES[DCONST_1] = "dconst_1"; //$NON-NLS-1$ + BYTECODE_NAMES[BIPUSH] = "bipush"; //$NON-NLS-1$ + BYTECODE_NAMES[SIPUSH] = "sipush"; //$NON-NLS-1$ + BYTECODE_NAMES[LDC] = "ldc"; //$NON-NLS-1$ + BYTECODE_NAMES[LDC_W] = "ldc_w"; //$NON-NLS-1$ + BYTECODE_NAMES[LDC2_W] = "ldc2_w"; //$NON-NLS-1$ + BYTECODE_NAMES[ILOAD] = "iload"; //$NON-NLS-1$ + BYTECODE_NAMES[LLOAD] = "lload"; //$NON-NLS-1$ + BYTECODE_NAMES[FLOAD] = "fload"; //$NON-NLS-1$ + BYTECODE_NAMES[DLOAD] = "dload"; //$NON-NLS-1$ + BYTECODE_NAMES[ALOAD] = "aload"; //$NON-NLS-1$ + BYTECODE_NAMES[ILOAD_0] = "iload_0"; //$NON-NLS-1$ + BYTECODE_NAMES[ILOAD_1] = "iload_1"; //$NON-NLS-1$ + BYTECODE_NAMES[ILOAD_2] = "iload_2"; //$NON-NLS-1$ + BYTECODE_NAMES[ILOAD_3] = "iload_3"; //$NON-NLS-1$ + BYTECODE_NAMES[LLOAD_0] = "lload_0"; //$NON-NLS-1$ + BYTECODE_NAMES[LLOAD_1] = "lload_1"; //$NON-NLS-1$ + BYTECODE_NAMES[LLOAD_2] = "lload_2"; //$NON-NLS-1$ + BYTECODE_NAMES[LLOAD_3] = "lload_3"; //$NON-NLS-1$ + BYTECODE_NAMES[FLOAD_0] = "fload_0"; //$NON-NLS-1$ + BYTECODE_NAMES[FLOAD_1] = "fload_1"; //$NON-NLS-1$ + BYTECODE_NAMES[FLOAD_2] = "fload_2"; //$NON-NLS-1$ + BYTECODE_NAMES[FLOAD_3] = "fload_3"; //$NON-NLS-1$ + BYTECODE_NAMES[DLOAD_0] = "dload_0"; //$NON-NLS-1$ + BYTECODE_NAMES[DLOAD_1] = "dload_1"; //$NON-NLS-1$ + BYTECODE_NAMES[DLOAD_2] = "dload_2"; //$NON-NLS-1$ + BYTECODE_NAMES[DLOAD_3] = "dload_3"; //$NON-NLS-1$ + BYTECODE_NAMES[ALOAD_0] = "aload_0"; //$NON-NLS-1$ + BYTECODE_NAMES[ALOAD_1] = "aload_1"; //$NON-NLS-1$ + BYTECODE_NAMES[ALOAD_2] = "aload_2"; //$NON-NLS-1$ + BYTECODE_NAMES[ALOAD_3] = "aload_3"; //$NON-NLS-1$ + BYTECODE_NAMES[IALOAD] = "iaload"; //$NON-NLS-1$ + BYTECODE_NAMES[LALOAD] = "laload"; //$NON-NLS-1$ + BYTECODE_NAMES[FALOAD] = "faload"; //$NON-NLS-1$ + BYTECODE_NAMES[DALOAD] = "daload"; //$NON-NLS-1$ + BYTECODE_NAMES[AALOAD] = "aaload"; //$NON-NLS-1$ + BYTECODE_NAMES[BALOAD] = "baload"; //$NON-NLS-1$ + BYTECODE_NAMES[CALOAD] = "caload"; //$NON-NLS-1$ + BYTECODE_NAMES[SALOAD] = "saload"; //$NON-NLS-1$ + BYTECODE_NAMES[ISTORE] = "istore"; //$NON-NLS-1$ + BYTECODE_NAMES[LSTORE] = "lstore"; //$NON-NLS-1$ + BYTECODE_NAMES[FSTORE] = "fstore"; //$NON-NLS-1$ + BYTECODE_NAMES[DSTORE] = "dstore"; //$NON-NLS-1$ + BYTECODE_NAMES[ASTORE] = "astore"; //$NON-NLS-1$ + BYTECODE_NAMES[ISTORE_0] = "istore_0"; //$NON-NLS-1$ + BYTECODE_NAMES[ISTORE_1] = "istore_1"; //$NON-NLS-1$ + BYTECODE_NAMES[ISTORE_2] = "istore_2"; //$NON-NLS-1$ + BYTECODE_NAMES[ISTORE_3] = "istore_3"; //$NON-NLS-1$ + BYTECODE_NAMES[LSTORE_0] = "lstore_0"; //$NON-NLS-1$ + BYTECODE_NAMES[LSTORE_1] = "lstore_1"; //$NON-NLS-1$ + BYTECODE_NAMES[LSTORE_2] = "lstore_2"; //$NON-NLS-1$ + BYTECODE_NAMES[LSTORE_3] = "lstore_3"; //$NON-NLS-1$ + BYTECODE_NAMES[FSTORE_0] = "fstore_0"; //$NON-NLS-1$ + BYTECODE_NAMES[FSTORE_1] = "fstore_1"; //$NON-NLS-1$ + BYTECODE_NAMES[FSTORE_2] = "fstore_2"; //$NON-NLS-1$ + BYTECODE_NAMES[FSTORE_3] = "fstore_3"; //$NON-NLS-1$ + BYTECODE_NAMES[DSTORE_0] = "dstore_0"; //$NON-NLS-1$ + BYTECODE_NAMES[DSTORE_1] = "dstore_1"; //$NON-NLS-1$ + BYTECODE_NAMES[DSTORE_2] = "dstore_2"; //$NON-NLS-1$ + BYTECODE_NAMES[DSTORE_3] = "dstore_3"; //$NON-NLS-1$ + BYTECODE_NAMES[ASTORE_0] = "astore_0"; //$NON-NLS-1$ + BYTECODE_NAMES[ASTORE_1] = "astore_1"; //$NON-NLS-1$ + BYTECODE_NAMES[ASTORE_2] = "astore_2"; //$NON-NLS-1$ + BYTECODE_NAMES[ASTORE_3] = "astore_3"; //$NON-NLS-1$ + BYTECODE_NAMES[IASTORE] = "iastore"; //$NON-NLS-1$ + BYTECODE_NAMES[LASTORE] = "lastore"; //$NON-NLS-1$ + BYTECODE_NAMES[FASTORE] = "fastore"; //$NON-NLS-1$ + BYTECODE_NAMES[DASTORE] = "dastore"; //$NON-NLS-1$ + BYTECODE_NAMES[AASTORE] = "aastore"; //$NON-NLS-1$ + BYTECODE_NAMES[BASTORE] = "bastore"; //$NON-NLS-1$ + BYTECODE_NAMES[CASTORE] = "castore"; //$NON-NLS-1$ + BYTECODE_NAMES[SASTORE] = "sastore"; //$NON-NLS-1$ + BYTECODE_NAMES[POP] = "pop"; //$NON-NLS-1$ + BYTECODE_NAMES[POP2] = "pop2"; //$NON-NLS-1$ + BYTECODE_NAMES[DUP] = "dup"; //$NON-NLS-1$ + BYTECODE_NAMES[DUP_X1] = "dup_x1"; //$NON-NLS-1$ + BYTECODE_NAMES[DUP_X2] = "dup_x2"; //$NON-NLS-1$ + BYTECODE_NAMES[DUP2] = "dup2"; //$NON-NLS-1$ + BYTECODE_NAMES[DUP2_X1] = "dup2_x1"; //$NON-NLS-1$ + BYTECODE_NAMES[DUP2_X2] = "dup2_x2"; //$NON-NLS-1$ + BYTECODE_NAMES[SWAP] = "swap"; //$NON-NLS-1$ + BYTECODE_NAMES[IADD] = "iadd"; //$NON-NLS-1$ + BYTECODE_NAMES[LADD] = "ladd"; //$NON-NLS-1$ + BYTECODE_NAMES[FADD] = "fadd"; //$NON-NLS-1$ + BYTECODE_NAMES[DADD] = "dadd"; //$NON-NLS-1$ + BYTECODE_NAMES[ISUB] = "isub"; //$NON-NLS-1$ + BYTECODE_NAMES[LSUB] = "lsub"; //$NON-NLS-1$ + BYTECODE_NAMES[FSUB] = "fsub"; //$NON-NLS-1$ + BYTECODE_NAMES[DSUB] = "dsub"; //$NON-NLS-1$ + BYTECODE_NAMES[IMUL] = "imul"; //$NON-NLS-1$ + BYTECODE_NAMES[LMUL] = "lmul"; //$NON-NLS-1$ + BYTECODE_NAMES[FMUL] = "fmul"; //$NON-NLS-1$ + BYTECODE_NAMES[DMUL] = "dmul"; //$NON-NLS-1$ + BYTECODE_NAMES[IDIV] = "idiv"; //$NON-NLS-1$ + BYTECODE_NAMES[LDIV] = "ldiv"; //$NON-NLS-1$ + BYTECODE_NAMES[FDIV] = "fdiv"; //$NON-NLS-1$ + BYTECODE_NAMES[DDIV] = "ddiv"; //$NON-NLS-1$ + BYTECODE_NAMES[IREM] = "irem"; //$NON-NLS-1$ + BYTECODE_NAMES[LREM] = "lrem"; //$NON-NLS-1$ + BYTECODE_NAMES[FREM] = "frem"; //$NON-NLS-1$ + BYTECODE_NAMES[DREM] = "drem"; //$NON-NLS-1$ + BYTECODE_NAMES[INEG] = "ineg"; //$NON-NLS-1$ + BYTECODE_NAMES[LNEG] = "lneg"; //$NON-NLS-1$ + BYTECODE_NAMES[FNEG] = "fneg"; //$NON-NLS-1$ + BYTECODE_NAMES[DNEG] = "dneg"; //$NON-NLS-1$ + BYTECODE_NAMES[ISHL] = "ishl"; //$NON-NLS-1$ + BYTECODE_NAMES[LSHL] = "lshl"; //$NON-NLS-1$ + BYTECODE_NAMES[ISHR] = "ishr"; //$NON-NLS-1$ + BYTECODE_NAMES[LSHR] = "lshr"; //$NON-NLS-1$ + BYTECODE_NAMES[IUSHR] = "iushr"; //$NON-NLS-1$ + BYTECODE_NAMES[LUSHR] = "lushr"; //$NON-NLS-1$ + BYTECODE_NAMES[IAND] = "iand"; //$NON-NLS-1$ + BYTECODE_NAMES[LAND] = "land"; //$NON-NLS-1$ + BYTECODE_NAMES[IOR] = "ior"; //$NON-NLS-1$ + BYTECODE_NAMES[LOR] = "lor"; //$NON-NLS-1$ + BYTECODE_NAMES[IXOR] = "ixor"; //$NON-NLS-1$ + BYTECODE_NAMES[LXOR] = "lxor"; //$NON-NLS-1$ + BYTECODE_NAMES[IINC] = "iinc"; //$NON-NLS-1$ + BYTECODE_NAMES[I2L] = "i2l"; //$NON-NLS-1$ + BYTECODE_NAMES[I2F] = "i2f"; //$NON-NLS-1$ + BYTECODE_NAMES[I2D] = "i2d"; //$NON-NLS-1$ + BYTECODE_NAMES[L2I] = "l2i"; //$NON-NLS-1$ + BYTECODE_NAMES[L2F] = "l2f"; //$NON-NLS-1$ + BYTECODE_NAMES[L2D] = "l2d"; //$NON-NLS-1$ + BYTECODE_NAMES[F2I] = "f2i"; //$NON-NLS-1$ + BYTECODE_NAMES[F2L] = "f2l"; //$NON-NLS-1$ + BYTECODE_NAMES[F2D] = "f2d"; //$NON-NLS-1$ + BYTECODE_NAMES[D2I] = "d2i"; //$NON-NLS-1$ + BYTECODE_NAMES[D2L] = "d2l"; //$NON-NLS-1$ + BYTECODE_NAMES[D2F] = "d2f"; //$NON-NLS-1$ + BYTECODE_NAMES[I2B] = "i2b"; //$NON-NLS-1$ + BYTECODE_NAMES[I2C] = "i2c"; //$NON-NLS-1$ + BYTECODE_NAMES[I2S] = "i2s"; //$NON-NLS-1$ + BYTECODE_NAMES[LCMP] = "lcmp"; //$NON-NLS-1$ + BYTECODE_NAMES[FCMPL] = "fcmpl"; //$NON-NLS-1$ + BYTECODE_NAMES[FCMPG] = "fcmpg"; //$NON-NLS-1$ + BYTECODE_NAMES[DCMPL] = "dcmpl"; //$NON-NLS-1$ + BYTECODE_NAMES[DCMPG] = "dcmpg"; //$NON-NLS-1$ + BYTECODE_NAMES[IFEQ] = "ifeq"; //$NON-NLS-1$ + BYTECODE_NAMES[IFNE] = "ifne"; //$NON-NLS-1$ + BYTECODE_NAMES[IFLT] = "iflt"; //$NON-NLS-1$ + BYTECODE_NAMES[IFGE] = "ifge"; //$NON-NLS-1$ + BYTECODE_NAMES[IFGT] = "ifgt"; //$NON-NLS-1$ + BYTECODE_NAMES[IFLE] = "ifle"; //$NON-NLS-1$ + BYTECODE_NAMES[IF_ICMPEQ] = "if_icmpeq"; //$NON-NLS-1$ + BYTECODE_NAMES[IF_ICMPNE] = "if_icmpne"; //$NON-NLS-1$ + BYTECODE_NAMES[IF_ICMPLT] = "if_icmplt"; //$NON-NLS-1$ + BYTECODE_NAMES[IF_ICMPGE] = "if_icmpge"; //$NON-NLS-1$ + BYTECODE_NAMES[IF_ICMPGT] = "if_icmpgt"; //$NON-NLS-1$ + BYTECODE_NAMES[IF_ICMPLE] = "if_icmple"; //$NON-NLS-1$ + BYTECODE_NAMES[IF_ACMPEQ] = "if_acmpeq"; //$NON-NLS-1$ + BYTECODE_NAMES[IF_ACMPNE] = "if_acmpne"; //$NON-NLS-1$ + BYTECODE_NAMES[GOTO] = "goto"; //$NON-NLS-1$ + BYTECODE_NAMES[JSR] = "jsr"; //$NON-NLS-1$ + BYTECODE_NAMES[RET] = "ret"; //$NON-NLS-1$ + BYTECODE_NAMES[TABLESWITCH] = "tableswitch"; //$NON-NLS-1$ + BYTECODE_NAMES[LOOKUPSWITCH] = "lookupswitch"; //$NON-NLS-1$ + BYTECODE_NAMES[IRETURN] = "ireturn"; //$NON-NLS-1$ + BYTECODE_NAMES[LRETURN] = "lreturn"; //$NON-NLS-1$ + BYTECODE_NAMES[FRETURN] = "freturn"; //$NON-NLS-1$ + BYTECODE_NAMES[DRETURN] = "dreturn"; //$NON-NLS-1$ + BYTECODE_NAMES[ARETURN] = "areturn"; //$NON-NLS-1$ + BYTECODE_NAMES[RETURN] = "return"; //$NON-NLS-1$ + BYTECODE_NAMES[GETSTATIC] = "getstatic"; //$NON-NLS-1$ + BYTECODE_NAMES[PUTSTATIC] = "putstatic"; //$NON-NLS-1$ + BYTECODE_NAMES[GETFIELD] = "getfield"; //$NON-NLS-1$ + BYTECODE_NAMES[PUTFIELD] = "putfield"; //$NON-NLS-1$ + BYTECODE_NAMES[INVOKEVIRTUAL] = "invokevirtual"; //$NON-NLS-1$ + BYTECODE_NAMES[INVOKESPECIAL] = "invokespecial"; //$NON-NLS-1$ + BYTECODE_NAMES[INVOKESTATIC] = "invokestatic"; //$NON-NLS-1$ + BYTECODE_NAMES[INVOKEINTERFACE] = "invokeinterface"; //$NON-NLS-1$ + BYTECODE_NAMES[NEW] = "new"; //$NON-NLS-1$ + BYTECODE_NAMES[NEWARRAY] = "newarray"; //$NON-NLS-1$ + BYTECODE_NAMES[ANEWARRAY] = "anewarray"; //$NON-NLS-1$ + BYTECODE_NAMES[ARRAYLENGTH] = "arraylength"; //$NON-NLS-1$ + BYTECODE_NAMES[ATHROW] = "athrow"; //$NON-NLS-1$ + BYTECODE_NAMES[CHECKCAST] = "checkcast"; //$NON-NLS-1$ + BYTECODE_NAMES[INSTANCEOF] = "instanceof"; //$NON-NLS-1$ + BYTECODE_NAMES[MONITORENTER] = "monitorenter"; //$NON-NLS-1$ + BYTECODE_NAMES[MONITOREXIT] = "monitorexit"; //$NON-NLS-1$ + BYTECODE_NAMES[WIDE] = "wide"; //$NON-NLS-1$ + BYTECODE_NAMES[MULTIANEWARRAY] = "multianewarray"; //$NON-NLS-1$ + BYTECODE_NAMES[IFNULL] = "ifnull"; //$NON-NLS-1$ + BYTECODE_NAMES[IFNONNULL] = "ifnonnull"; //$NON-NLS-1$ + BYTECODE_NAMES[GOTO_W] = "goto_w"; //$NON-NLS-1$ + BYTECODE_NAMES[JSR_W] = "jsr_w"; //$NON-NLS-1$ + BYTECODE_NAMES[BREAKPOINT] = "breakpoint"; //$NON-NLS-1$ + BYTECODE_NAMES[IMPDEP1] = "impdep1"; //$NON-NLS-1$ + BYTECODE_NAMES[IMPDEP2] = "impdep2"; //$NON-NLS-1$ + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ParameterAnnotation.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ParameterAnnotation.java new file mode 100644 index 000000000..8f08991c1 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/ParameterAnnotation.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class ParameterAnnotation extends ClassFileStruct { + + private static final Annotation[] NO_ENTRIES = new Annotation[0]; + + private int annotationsNumber; + private Annotation[] annotations; + private int readOffset; + + /** + * Constructor for Annotation. + * + * @param classFileBytes + * @param constantPool + * @param offset + * @throws ClassFormatException + */ + public ParameterAnnotation(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + + final int length = u2At(classFileBytes, 0, offset); + this.readOffset = 2; + this.annotationsNumber = length; + if (length != 0) { + this.annotations = new Annotation[length]; + for (int i = 0; i < length; i++) { + Annotation annotation = new Annotation(classFileBytes, constantPool, offset + this.readOffset); + this.annotations[i] = annotation; + this.readOffset += annotation.sizeInBytes(); + } + } else { + this.annotations = NO_ENTRIES; + } + } + + int sizeInBytes() { + return this.readOffset; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IParameterAnnotation#getAnnotations() + */ + public Annotation[] getAnnotations() { + return this.annotations; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IParameterAnnotation#getAnnotationsNumber() + */ + public int getAnnotationsNumber() { + return this.annotationsNumber; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeInvisibleAnnotationsAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeInvisibleAnnotationsAttribute.java new file mode 100644 index 000000000..ef3244b5d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeInvisibleAnnotationsAttribute.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class RuntimeInvisibleAnnotationsAttribute extends ClassFileAttribute { + + private static final Annotation[] NO_ENTRIES = new Annotation[0]; + private int annotationsNumber; + private Annotation[] annotations; + + /** + * Constructor for RuntimeInvisibleAnnotations. + * @param classFileBytes + * @param constantPool + * @param offset + * @throws ClassFormatException + */ + public RuntimeInvisibleAnnotationsAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + super(classFileBytes, constantPool, offset); + final int length = u2At(classFileBytes, 6, offset); + this.annotationsNumber = length; + if (length != 0) { + int readOffset = 8; + this.annotations = new Annotation[length]; + for (int i = 0; i < length; i++) { + Annotation annotation = new Annotation(classFileBytes, constantPool, offset + readOffset); + this.annotations[i] = annotation; + readOffset += annotation.sizeInBytes(); + } + } else { + this.annotations = NO_ENTRIES; + } + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IRuntimeInvisibleAnnotations#getAnnotations() + */ + public Annotation[] getAnnotations() { + return this.annotations; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IRuntimeInvisibleAnnotations#getAnnotationsNumber() + */ + public int getAnnotationsNumber() { + return this.annotationsNumber; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeInvisibleParameterAnnotationsAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeInvisibleParameterAnnotationsAttribute.java new file mode 100644 index 000000000..b9f489153 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeInvisibleParameterAnnotationsAttribute.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class RuntimeInvisibleParameterAnnotationsAttribute extends ClassFileAttribute { + + private static final ParameterAnnotation[] NO_ENTRIES = new ParameterAnnotation[0]; + private ParameterAnnotation[] parameterAnnotations; + private int parametersNumber; + + /** + * Constructor for RuntimeVisibleParameterAnnotations. + * @param classFileBytes + * @param constantPool + * @param offset + * @throws ClassFormatException + */ + public RuntimeInvisibleParameterAnnotationsAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + super(classFileBytes, constantPool, offset); + final int length = u1At(classFileBytes, 6, offset); + this.parametersNumber = length; + if (length != 0) { + int readOffset = 7; + this.parameterAnnotations = new ParameterAnnotation[length]; + for (int i = 0; i < length; i++) { + ParameterAnnotation parameterAnnotation = new ParameterAnnotation(classFileBytes, constantPool, offset + readOffset); + this.parameterAnnotations[i] = parameterAnnotation; + readOffset += parameterAnnotation.sizeInBytes(); + } + } else { + this.parameterAnnotations = NO_ENTRIES; + } + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IRuntimeInvisibleParameterAnnotations#getAnnotations() + */ + public ParameterAnnotation[] getParameterAnnotations() { + return this.parameterAnnotations; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IRuntimeInvisibleParameterAnnotations#getParametersNumber() + */ + public int getParametersNumber() { + return this.parametersNumber; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeVisibleAnnotationsAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeVisibleAnnotationsAttribute.java new file mode 100644 index 000000000..00306e271 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeVisibleAnnotationsAttribute.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class RuntimeVisibleAnnotationsAttribute extends ClassFileAttribute { + + private static final Annotation[] NO_ENTRIES = new Annotation[0]; + private int annotationsNumber; + private Annotation[] annotations; + + /** + * Constructor for RuntimeVisibleAnnotations. + * @param classFileBytes + * @param constantPool + * @param offset + * @throws ClassFormatException + */ + public RuntimeVisibleAnnotationsAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + super(classFileBytes, constantPool, offset); + final int length = u2At(classFileBytes, 6, offset); + this.annotationsNumber = length; + if (length != 0) { + int readOffset = 8; + this.annotations = new Annotation[length]; + for (int i = 0; i < length; i++) { + Annotation annotation = new Annotation(classFileBytes, constantPool, offset + readOffset); + this.annotations[i] = annotation; + readOffset += annotation.sizeInBytes(); + } + } else { + this.annotations = NO_ENTRIES; + } + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IRuntimeVisibleAnnotations#getAnnotations() + */ + public Annotation[] getAnnotations() { + return this.annotations; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IRuntimeVisibleAnnotations#getAnnotationsNumber() + */ + public int getAnnotationsNumber() { + return this.annotationsNumber; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeVisibleParameterAnnotationsAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeVisibleParameterAnnotationsAttribute.java new file mode 100644 index 000000000..1f2b84011 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/RuntimeVisibleParameterAnnotationsAttribute.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class RuntimeVisibleParameterAnnotationsAttribute extends ClassFileAttribute { + + private static final ParameterAnnotation[] NO_ENTRIES = new ParameterAnnotation[0]; + private int parametersNumber; + private ParameterAnnotation[] parameterAnnotations; + + /** + * Constructor for RuntimeVisibleParameterAnnotations. + * @param classFileBytes + * @param constantPool + * @param offset + * @throws ClassFormatException + */ + public RuntimeVisibleParameterAnnotationsAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + super(classFileBytes, constantPool, offset); + final int length = u1At(classFileBytes, 6, offset); + this.parametersNumber = length; + if (length != 0) { + int readOffset = 7; + this.parameterAnnotations = new ParameterAnnotation[length]; + for (int i = 0; i < length; i++) { + ParameterAnnotation parameterAnnotation = new ParameterAnnotation(classFileBytes, constantPool, offset + readOffset); + this.parameterAnnotations[i] = parameterAnnotation; + readOffset += parameterAnnotation.sizeInBytes(); + } + } else { + this.parameterAnnotations = NO_ENTRIES; + } + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IRuntimeVisibleParameterAnnotations#getAnnotations() + */ + public ParameterAnnotation[] getParameterAnnotations() { + return this.parameterAnnotations; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.IRuntimeVisibleParameterAnnotations#getParametersNumber() + */ + public int getParametersNumber() { + return this.parametersNumber; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Signature.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Signature.java new file mode 100644 index 000000000..7b855bb25 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Signature.java @@ -0,0 +1,1163 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +import java.util.ArrayList; + +/* + * Provides methods for encoding and decoding type and method signature strings. + *

    + * Signatures obtained from parsing source files (i.e. files with one of the + * {@link JavaCore#getJavaLikeExtensions() Java-like extensions}) differ subtly + * from ones obtained from pre-compiled binary (".class") files in class names are + * usually left unresolved in the former. For example, the normal resolved form + * of the type "String" embeds the class's package name ("Ljava.lang.String;" + * or "Ljava/lang/String;"), whereas the unresolved form contains only what is + * written "QString;". + *

    + *

    + * Generic types introduce to the Java language in J2SE 1.5 add three new + * facets to signatures: type variables, parameterized types with type arguments, + * and formal type parameters. Rich signatures containing these facets + * only occur when dealing with code that makes overt use of the new language + * features. All other code, and certainly all Java code written or compiled + * with J2SE 1.4 or earlier, involved only simple signatures. + *

    + *

    + * Note that the "Q" and "!" formats are specific to Eclipse; the remainder + * are specified in the JVM spec. + *

    + *

    + * The syntax for a type signature is: + *

    + * TypeSignature ::=
    + *     "B"  // byte
    + *   | "C"  // char
    + *   | "D"  // double
    + *   | "F"  // float
    + *   | "I"  // int
    + *   | "J"  // long
    + *   | "S"  // short
    + *   | "V"  // void
    + *   | "Z"  // boolean
    + *   | "T" + Identifier + ";" // type variable
    + *   | "[" + TypeSignature  // array X[]
    + *   | "!" + TypeSignature  // capture-of ?
    + *   | ResolvedClassTypeSignature
    + *   | UnresolvedClassTypeSignature
    + *
    + * ResolvedClassTypeSignature ::= // resolved named type (in compiled code)
    + *     "L" + Identifier + OptionalTypeArguments
    + *           ( ( "." | "/" ) + Identifier + OptionalTypeArguments )* + ";"
    + *     | OptionalTypeParameters + "L" + Identifier +
    + *           ( ( "." | "/" ) + Identifier )* + ";"
    + *
    + * UnresolvedClassTypeSignature ::= // unresolved named type (in source code)
    + *     "Q" + Identifier + OptionalTypeArguments
    + *           ( ( "." | "/" ) + Identifier + OptionalTypeArguments )* + ";"
    + *     | OptionalTypeParameters "Q" + Identifier +
    + *           ( ( "." | "/" ) + Identifier )* + ";"
    + *
    + * OptionalTypeArguments ::=
    + *     "<" + TypeArgument+ + ">"
    + *   |
    + *
    + * TypeArgument ::=
    + *   | TypeSignature
    + *   | "*" // wildcard ?
    + *   | "+" TypeSignature // wildcard ? extends X
    + *   | "-" TypeSignature // wildcard ? super X
    + *
    + * OptionalTypeParameters ::=
    + *     "<" + FormalTypeParameterSignature+ + ">"
    + *   |
    + * 
    + *

    + *

    + * Examples: + *

      + *
    • "[[I" denotes int[][]
    • + *
    • "Ljava.lang.String;" denotes java.lang.String in compiled code
    • + *
    • "QString;" denotes String in source code
    • + *
    • "Qjava.lang.String;" denotes java.lang.String in source code
    • + *
    • "[QString;" denotes String[] in source code
    • + *
    • "QMap<QString;*>;" denotes Map<String,?> in source code
    • + *
    • "Qjava.util.List<TV;>;" denotes java.util.List<V> in source code
    • + *
    • "<E;>Ljava.util.List;" denotes <E>java.util.List in source code
    • + *
    + *

    + *

    + * The syntax for a method signature is: + *

    + * MethodSignature ::= OptionalTypeParameters + "(" + ParamTypeSignature* + ")" + ReturnTypeSignature
    + * ParamTypeSignature ::= TypeSignature
    + * ReturnTypeSignature ::= TypeSignature
    + * 
    + *

    + * Examples: + *

      + *
    • "()I" denotes int foo()
    • + *
    • "([Ljava.lang.String;)V" denotes void foo(java.lang.String[]) in compiled code
    • + *
    • "(QString;)QObject;" denotes Object foo(String) in source code
    • + *
    + *

    + *

    + * The syntax for a formal type parameter signature is: + *

    + * FormalTypeParameterSignature ::=
    + *     TypeVariableName + OptionalClassBound + InterfaceBound*
    + * TypeVariableName ::= Identifier
    + * OptionalClassBound ::=
    + *     ":"
    + *   | ":" + TypeSignature
    + * InterfaceBound ::=
    + *     ":" + TypeSignature
    + * 
    + *

    + * Examples: + *

      + *
    • "X:" denotes X
    • + *
    • "X:QReader;" denotes X extends Reader in source code
    • + *
    • "X:QReader;:QSerializable;" denotes X extends Reader & Serializable in source code
    • + *
    + *

    + *

    + * This class provides static methods and constants only. + *

    + * @noinstantiate This class is not intended to be instantiated by clients. + */ +public final class Signature { + /* + * Character constant indicating the primitive type boolean in a signature. + * Value is 'Z'. + */ + public static final char C_BOOLEAN = 'Z'; + + /* + * Character constant indicating the primitive type byte in a signature. + * Value is 'B'. + */ + public static final char C_BYTE = 'B'; + + /* + * Character constant indicating the primitive type char in a signature. + * Value is 'C'. + */ + public static final char C_CHAR = 'C'; + + /* + * Character constant indicating the primitive type double in a signature. + * Value is 'D'. + */ + public static final char C_DOUBLE = 'D'; + + /* + * Character constant indicating the primitive type float in a signature. + * Value is 'F'. + */ + public static final char C_FLOAT = 'F'; + + /* + * Character constant indicating the primitive type int in a signature. + * Value is 'I'. + */ + public static final char C_INT = 'I'; + + /* + * Character constant indicating the semicolon in a signature. + * Value is ';'. + */ + public static final char C_SEMICOLON = ';'; + + /* + * Character constant indicating the colon in a signature. + * Value is ':'. + * @since 3.0 + */ + public static final char C_COLON = ':'; + + /* + * Character constant indicating the primitive type long in a signature. + * Value is 'J'. + */ + public static final char C_LONG = 'J'; + + /* + * Character constant indicating the primitive type short in a signature. + * Value is 'S'. + */ + public static final char C_SHORT = 'S'; + + /* + * Character constant indicating result type void in a signature. + * Value is 'V'. + */ + public static final char C_VOID = 'V'; + + /* + * Character constant indicating the start of a resolved type variable in a + * signature. Value is 'T'. + * @since 3.0 + */ + public static final char C_TYPE_VARIABLE = 'T'; + + /* + * Character constant indicating an unbound wildcard type argument + * in a signature. + * Value is '*'. + * @since 3.0 + */ + public static final char C_STAR = '*'; + + /* + * Character constant indicating an exception in a signature. + * Value is '^'. + * @since 3.1 + */ + public static final char C_EXCEPTION_START = '^'; + + /* + * Character constant indicating a bound wildcard type argument + * in a signature with extends clause. + * Value is '+'. + * @since 3.1 + */ + public static final char C_EXTENDS = '+'; + + /* + * Character constant indicating a bound wildcard type argument + * in a signature with super clause. + * Value is '-'. + * @since 3.1 + */ + public static final char C_SUPER = '-'; + + /* + * Character constant indicating the dot in a signature. + * Value is '.'. + */ + public static final char C_DOT = '.'; + + /* + * Character constant indicating the dollar in a signature. + * Value is '$'. + */ + public static final char C_DOLLAR = '$'; + + /* + * Character constant indicating an array type in a signature. + * Value is '['. + */ + public static final char C_ARRAY = '['; + + /* + * Character constant indicating the start of a resolved, named type in a + * signature. Value is 'L'. + */ + public static final char C_RESOLVED = 'L'; + + /* + * Character constant indicating the start of an unresolved, named type in a + * signature. Value is 'Q'. + */ + public static final char C_UNRESOLVED = 'Q'; + + /* + * Character constant indicating the end of a named type in a signature. + * Value is ';'. + */ + public static final char C_NAME_END = ';'; + + /* + * Character constant indicating the start of a parameter type list in a + * signature. Value is '('. + */ + public static final char C_PARAM_START = '('; + + /* + * Character constant indicating the end of a parameter type list in a + * signature. Value is ')'. + */ + public static final char C_PARAM_END = ')'; + + /* + * Character constant indicating the start of a formal type parameter + * (or type argument) list in a signature. Value is '<'. + * @since 3.0 + */ + public static final char C_GENERIC_START = '<'; + + /* + * Character constant indicating the end of a generic type list in a + * signature. Value is '>'. + * @since 3.0 + */ + public static final char C_GENERIC_END = '>'; + + /* + * Character constant indicating a capture of a wildcard type in a + * signature. Value is '!'. + * @since 3.1 + */ + public static final char C_CAPTURE = '!'; + + /* + * String constant for the signature of the primitive type boolean. + * Value is "Z". + */ + public static final String SIG_BOOLEAN = "Z"; //$NON-NLS-1$ + + /* + * String constant for the signature of the primitive type byte. + * Value is "B". + */ + public static final String SIG_BYTE = "B"; //$NON-NLS-1$ + + /* + * String constant for the signature of the primitive type char. + * Value is "C". + */ + public static final String SIG_CHAR = "C"; //$NON-NLS-1$ + + /* + * String constant for the signature of the primitive type double. + * Value is "D". + */ + public static final String SIG_DOUBLE = "D"; //$NON-NLS-1$ + + /* + * String constant for the signature of the primitive type float. + * Value is "F". + */ + public static final String SIG_FLOAT = "F"; //$NON-NLS-1$ + + /* + * String constant for the signature of the primitive type int. + * Value is "I". + */ + public static final String SIG_INT = "I"; //$NON-NLS-1$ + + /* + * String constant for the signature of the primitive type long. + * Value is "J". + */ + public static final String SIG_LONG = "J"; //$NON-NLS-1$ + + /* + * String constant for the signature of the primitive type short. + * Value is "S". + */ + public static final String SIG_SHORT = "S"; //$NON-NLS-1$ + + /* String constant for the signature of result type void. + * Value is "V". + */ + public static final String SIG_VOID = "V"; //$NON-NLS-1$ + + /* + * Kind constant for a class type signature. + * @see #getTypeSignatureKind(String) + * @since 3.0 + */ + public static final int CLASS_TYPE_SIGNATURE = 1; + + /* + * Kind constant for a base (primitive or void) type signature. + * @see #getTypeSignatureKind(String) + * @since 3.0 + */ + public static final int BASE_TYPE_SIGNATURE = 2; + + /* + * Kind constant for a type variable signature. + * @see #getTypeSignatureKind(String) + * @since 3.0 + */ + public static final int TYPE_VARIABLE_SIGNATURE = 3; + + /* + * Kind constant for an array type signature. + * @see #getTypeSignatureKind(String) + * @since 3.0 + */ + public static final int ARRAY_TYPE_SIGNATURE = 4; + + /* + * Kind constant for a wildcard type signature. + * @see #getTypeSignatureKind(String) + * @since 3.1 + */ + public static final int WILDCARD_TYPE_SIGNATURE = 5; + + /* + * Kind constant for the capture of a wildcard type signature. + * @see #getTypeSignatureKind(String) + * @since 3.1 + */ + public static final int CAPTURE_TYPE_SIGNATURE = 6; + + private static final char[] BOOLEAN = "boolean".toCharArray(); //$NON-NLS-1$ + private static final char[] BYTE = "byte".toCharArray(); //$NON-NLS-1$ + private static final char[] CHAR = "char".toCharArray(); //$NON-NLS-1$ + private static final char[] DOUBLE = "double".toCharArray(); //$NON-NLS-1$ + private static final char[] FLOAT = "float".toCharArray(); //$NON-NLS-1$ + private static final char[] INT = "int".toCharArray(); //$NON-NLS-1$ + private static final char[] LONG = "long".toCharArray(); //$NON-NLS-1$ + private static final char[] SHORT = "short".toCharArray(); //$NON-NLS-1$ + private static final char[] VOID = "void".toCharArray(); //$NON-NLS-1$ + // private static final char[] EXTENDS = "extends".toCharArray(); //$NON-NLS-1$ + // private static final char[] SUPER = "super".toCharArray(); //$NON-NLS-1$ + private static final char[] CAPTURE = "capture-of".toCharArray(); //$NON-NLS-1$ + + /* + * Returns the number of parameter types in the given method signature. + * + * @param methodSignature the method signature + * @return the number of parameters + * @exception IllegalArgumentException if the signature is not syntactically + * correct + * @since 2.0 + */ + public static int getParameterCount(char[] methodSignature) throws IllegalArgumentException { + try { + int count = 0; + int i = CharOperation.indexOf(C_PARAM_START, methodSignature); + if (i < 0) { + throw new IllegalArgumentException(); + } + i++; + for (;;) { + if (methodSignature[i] == C_PARAM_END) { + return count; + } + int e = Utility.scanTypeSignature(methodSignature, i); + if (e < 0) { + throw new IllegalArgumentException(); + } + i = e + 1; + count++; + } + } catch (ArrayIndexOutOfBoundsException e) { + throw new IllegalArgumentException(); + } + } + + /* + * Extracts the parameter type signatures from the given method signature. + * The method signature is expected to be dot-based. + * + * @param methodSignature the method signature + * @return the list of parameter type signatures + * @exception IllegalArgumentException if the signature is syntactically + * incorrect + * + * @since 2.0 + */ + public static char[][] getParameterTypes(char[] methodSignature) throws IllegalArgumentException { + try { + int count = getParameterCount(methodSignature); + char[][] result = new char[count][]; + if (count == 0) { + return result; + } + int i = CharOperation.indexOf(C_PARAM_START, methodSignature); + if (i < 0) { + throw new IllegalArgumentException(); + } + i++; + int t = 0; + for (;;) { + if (methodSignature[i] == C_PARAM_END) { + return result; + } + int e = Utility.scanTypeSignature(methodSignature, i); + if (e < 0) { + throw new IllegalArgumentException(); + } + result[t] = CharOperation.subarray(methodSignature, i, e + 1); + t++; + i = e + 1; + } + } catch (ArrayIndexOutOfBoundsException e) { + throw new IllegalArgumentException(); + } + } + + /* + * Extracts the return type from the given method signature. The method signature is + * expected to be dot-based. + * + * @param methodSignature the method signature + * @return the type signature of the return type + * @exception IllegalArgumentException if the signature is syntactically + * incorrect + * + * @since 2.0 + */ + public static char[] getReturnType(char[] methodSignature) throws IllegalArgumentException { + // skip type parameters + int paren = CharOperation.lastIndexOf(C_PARAM_END, methodSignature); + if (paren == -1) { + throw new IllegalArgumentException(); + } + // there could be thrown exceptions behind, thus scan one type exactly + int last = Utility.scanTypeSignature(methodSignature, paren + 1); + return CharOperation.subarray(methodSignature, paren + 1, last + 1); + } + + /* + * Extracts the class and interface bounds from the given formal type + * parameter signature. The class bound, if present, is listed before + * the interface bounds. The signature is expected to be dot-based. + * + * @param formalTypeParameterSignature the formal type parameter signature + * @return the (possibly empty) list of type signatures for the bounds + * @exception IllegalArgumentException if the signature is syntactically + * incorrect + * @since 3.0 + */ + public static char[][] getTypeParameterBounds(char[] formalTypeParameterSignature) throws IllegalArgumentException { + int p1 = CharOperation.indexOf(C_COLON, formalTypeParameterSignature); + if (p1 < 0) { + // no ":" means can't be a formal type parameter signature + throw new IllegalArgumentException(); + } + if (p1 == formalTypeParameterSignature.length - 1) { + // no class or interface bounds + return CharOperation.NO_CHAR_CHAR; + } + int p2 = CharOperation.indexOf(C_COLON, formalTypeParameterSignature, p1 + 1); + char[] classBound; + if (p2 < 0) { + // no interface bounds + classBound = CharOperation.subarray(formalTypeParameterSignature, p1 + 1, formalTypeParameterSignature.length); + return new char[][] {classBound}; + } + if (p2 == p1 + 1) { + // no class bound, but 1 or more interface bounds + classBound = null; + } else { + classBound = CharOperation.subarray(formalTypeParameterSignature, p1 + 1, p2); + } + char[][] interfaceBounds = CharOperation.splitOn(C_COLON, formalTypeParameterSignature, p2 + 1, formalTypeParameterSignature.length); + if (classBound == null) { + return interfaceBounds; + } + int resultLength = interfaceBounds.length + 1; + char[][] result = new char[resultLength][]; + result[0] = classBound; + System.arraycopy(interfaceBounds, 0, result, 1, interfaceBounds.length); + return result; + } + + /* + * Extracts the type parameter signatures from the given method or type signature. + * The method or type signature is expected to be dot-based. + * + * @param methodOrTypeSignature the method or type signature + * @return the list of type parameter signatures + * @exception IllegalArgumentException if the signature is syntactically + * incorrect + * + * @since 3.1 + */ + public static char[][] getTypeParameters(char[] methodOrTypeSignature) throws IllegalArgumentException { + try { + int length = methodOrTypeSignature.length; + if (length == 0) + return CharOperation.NO_CHAR_CHAR; + if (methodOrTypeSignature[0] != C_GENERIC_START) + return CharOperation.NO_CHAR_CHAR; + + ArrayList paramList = new ArrayList(1); + int paramStart = 1, i = 1; // start after leading '<' + while (i < length) { + if (methodOrTypeSignature[i] == C_GENERIC_END) { + int size = paramList.size(); + if (size == 0) + throw new IllegalArgumentException(); + char[][] result; + paramList.toArray(result = new char[size][]); + return result; + } + i = CharOperation.indexOf(C_COLON, methodOrTypeSignature, i); + if (i < 0 || i >= length) + throw new IllegalArgumentException(); + // iterate over bounds + while (methodOrTypeSignature[i] == ':') { + i++; // skip colon + switch (methodOrTypeSignature[i]) { + case ':' : + // no class bound + break; + case C_GENERIC_END : + break; + case C_RESOLVED : + try { + i = Utility.scanClassTypeSignature(methodOrTypeSignature, i); + i++; // position at start of next param if any + } catch (IllegalArgumentException e) { + // not a class type signature -> it is a new type parameter + } + break; + case C_ARRAY : + try { + i = Utility.scanArrayTypeSignature(methodOrTypeSignature, i); + i++; // position at start of next param if any + } catch (IllegalArgumentException e) { + // not an array type signature -> it is a new type parameter + } + break; + case C_TYPE_VARIABLE : + try { + i = Utility.scanTypeVariableSignature(methodOrTypeSignature, i); + i++; // position at start of next param if any + } catch (IllegalArgumentException e) { + // not a type variable signature -> it is a new type parameter + } + break; + // default: another type parameter is starting + } + } + paramList.add(CharOperation.subarray(methodOrTypeSignature, paramStart, i)); + paramStart = i; // next param start from here + } + } catch (ArrayIndexOutOfBoundsException e) { + // invalid signature, fall through + } + throw new IllegalArgumentException(); + } + + /* + * Converts the given type signature to a readable string. The signature is expected to + * be dot-based. + * + *

    + * For example: + *

    +	 * 
    +	 * toString({'[', 'L', 'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', ';'}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', '[', ']'}
    +	 * toString({'I'}) -> {'i', 'n', 't'}
    +	 * toString({'+', 'L', 'O', 'b', 'j', 'e', 'c', 't', ';'}) -> {'?', ' ', 'e', 'x', 't', 'e', 'n', 'd', 's', ' ', 'O', 'b', 'j', 'e', 'c', 't'}
    +	 * 
    +	 * 
    + *

    + *

    + * Note: This method assumes that a type signature containing a '$' + * is an inner type signature. While this is correct in most cases, someone could + * define a non-inner type name containing a '$'. Handling this + * correctly in all cases would have required resolving the signature, which + * generally not feasible. + *

    + * + * @param signature the type signature + * @return the string representation of the type + * @exception IllegalArgumentException if the signature is not syntactically + * correct + * + * @since 2.0 + */ + public static char[] toCharArray(char[] signature) throws IllegalArgumentException { + int sigLength = signature.length; + if (sigLength == 0 || signature[0] == C_PARAM_START || signature[0] == C_GENERIC_START) { + return toCharArray(signature, CharOperation.NO_CHAR, null, true, true); + } + + StringBuffer buffer = new StringBuffer(signature.length + 10); + appendTypeSignature(signature, 0, true, buffer); + char[] result = new char[buffer.length()]; + buffer.getChars(0, buffer.length(), result, 0); + return result; + } + + /* + * Converts the given method signature to a readable form. The method signature is expected to + * be dot-based. + *

    + * For example: + *

    +	 * 
    +	 * toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
    +	 * 
    +	 * 
    + *

    + * + * @param methodSignature the method signature to convert + * @param methodName the name of the method to insert in the result, or + * null if no method name is to be included + * @param parameterNames the parameter names to insert in the result, or + * null if no parameter names are to be included; if supplied, + * the number of parameter names must match that of the method signature + * @param fullyQualifyTypeNames true if type names should be fully + * qualified, and false to use only simple names + * @param includeReturnType true if the return type is to be + * included + * @param isVargArgs true if the last argument should be displayed as a + * variable argument, false otherwise. + * @return the char array representation of the method signature + * + * @since 3.1 + */ + public static char[] toCharArray(char[] methodSignature, char[] methodName, char[][] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType, boolean isVargArgs) { + int firstParen = CharOperation.indexOf(C_PARAM_START, methodSignature); + if (firstParen == -1) { + throw new IllegalArgumentException(); + } + + StringBuffer buffer = new StringBuffer(methodSignature.length + 10); + + // return type + if (includeReturnType) { + char[] rts = getReturnType(methodSignature); + appendTypeSignature(rts, 0, fullyQualifyTypeNames, buffer); + buffer.append(' '); + } + + // selector + if (methodName != null) { + buffer.append(methodName); + } + + // parameters + buffer.append('('); + char[][] pts = getParameterTypes(methodSignature); + for (int i = 0, max = pts.length; i < max; i++) { + if (i == max - 1) { + appendTypeSignature(pts[i], 0, fullyQualifyTypeNames, buffer, isVargArgs); + } else { + appendTypeSignature(pts[i], 0, fullyQualifyTypeNames, buffer); + } + if (parameterNames != null) { + buffer.append(' '); + buffer.append(parameterNames[i]); + } + if (i != pts.length - 1) { + buffer.append(','); + buffer.append(' '); + } + } + buffer.append(')'); + char[] result = new char[buffer.length()]; + buffer.getChars(0, buffer.length(), result, 0); + return result; + } + + /* + * Scans the given string for a type signature starting at the given + * index and appends it to the given buffer, and returns the index of the last + * character. + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @param fullyQualifyTypeNames true if type names should be fully + * qualified, and false to use only simple names + * @param buffer the string buffer to append to + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not a type signature + * @see Utility#scanTypeSignature(char[], int) + */ + private static int appendTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { + return appendTypeSignature(string, start, fullyQualifyTypeNames, buffer, false); + } + + /* + * Scans the given string for a type signature starting at the given + * index and appends it to the given buffer, and returns the index of the last + * character. + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @param fullyQualifyTypeNames true if type names should be fully + * qualified, and false to use only simple names + * @param buffer the string buffer to append to + * @param isVarArgs true if the type must be displayed as a + * variable argument, false otherwise. In this case, the type must be an array type + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not a type signature, or if isVarArgs is true, + * and the type is not an array type signature. + * @see Utility#scanTypeSignature(char[], int) + */ + private static int appendTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer, boolean isVarArgs) { + // need a minimum 1 char + if (start >= string.length) { + throw new IllegalArgumentException(); + } + char c = string[start]; + if (isVarArgs) { + switch (c) { + case C_ARRAY : + return appendArrayTypeSignature(string, start, fullyQualifyTypeNames, buffer, true); + case C_RESOLVED : + case C_UNRESOLVED : + case C_TYPE_VARIABLE : + case C_BOOLEAN : + case C_BYTE : + case C_CHAR : + case C_DOUBLE : + case C_FLOAT : + case C_INT : + case C_LONG : + case C_SHORT : + case C_VOID : + case C_STAR : + case C_EXTENDS : + case C_SUPER : + case C_CAPTURE : + default : + throw new IllegalArgumentException(); // a var args is an array type + } + } + switch (c) { + case C_ARRAY : + return appendArrayTypeSignature(string, start, fullyQualifyTypeNames, buffer); + case C_RESOLVED : + case C_UNRESOLVED : + return appendClassTypeSignature(string, start, fullyQualifyTypeNames, buffer); + case C_TYPE_VARIABLE : + int e = Utility.scanTypeVariableSignature(string, start); + buffer.append(string, start + 1, e - start - 1); + return e; + case C_BOOLEAN : + buffer.append(BOOLEAN); + return start; + case C_BYTE : + buffer.append(BYTE); + return start; + case C_CHAR : + buffer.append(CHAR); + return start; + case C_DOUBLE : + buffer.append(DOUBLE); + return start; + case C_FLOAT : + buffer.append(FLOAT); + return start; + case C_INT : + buffer.append(INT); + return start; + case C_LONG : + buffer.append(LONG); + return start; + case C_SHORT : + buffer.append(SHORT); + return start; + case C_VOID : + buffer.append(VOID); + return start; + case C_CAPTURE : + return appendCaptureTypeSignature(string, start, fullyQualifyTypeNames, buffer); + case C_STAR : + case C_EXTENDS : + case C_SUPER : + return appendTypeArgumentSignature(string, start, fullyQualifyTypeNames, buffer); + default : + throw new IllegalArgumentException(); + } + } + + /* + * Scans the given string for an array type signature starting at the given + * index and appends it to the given buffer, and returns the index of the last + * character. + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @param fullyQualifyTypeNames true if type names should be fully + * qualified, and false to use only simple names + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not an array type signature + * @see Utility#scanArrayTypeSignature(char[], int) + */ + private static int appendArrayTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { + return appendArrayTypeSignature(string, start, fullyQualifyTypeNames, buffer, false); + } + + /* + * Scans the given string for an array type signature starting at the given + * index and appends it to the given buffer, and returns the index of the last + * character. + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @param fullyQualifyTypeNames true if type names should be fully + * qualified, and false to use only simple names + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not an array type signature + * @see Utility#scanArrayTypeSignature(char[], int) + */ + private static int appendCaptureTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { + // need a minimum 2 char + if (start >= string.length - 1) { + throw new IllegalArgumentException(); + } + char c = string[start]; + if (c != C_CAPTURE) { + throw new IllegalArgumentException(); + } + buffer.append(CAPTURE).append(' '); + return appendTypeArgumentSignature(string, start + 1, fullyQualifyTypeNames, buffer); + } + + /* + * Scans the given string for an array type signature starting at the given + * index and appends it to the given buffer, and returns the index of the last + * character. + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @param fullyQualifyTypeNames true if type names should be fully + * qualified, and false to use only simple names + * @param isVarArgs true if the array type must be displayed as a + * variable argument, false otherwise + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not an array type signature + * @see Utility#scanArrayTypeSignature(char[], int) + */ + private static int appendArrayTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer, boolean isVarArgs) { + int length = string.length; + // need a minimum 2 char + if (start >= length - 1) { + throw new IllegalArgumentException(); + } + char c = string[start]; + if (c != C_ARRAY) { + throw new IllegalArgumentException(); + } + + int index = start; + c = string[++index]; + while (c == C_ARRAY) { + // need a minimum 2 char + if (index >= length - 1) { + throw new IllegalArgumentException(); + } + c = string[++index]; + } + + int e = appendTypeSignature(string, index, fullyQualifyTypeNames, buffer); + + for (int i = 1, dims = index - start; i < dims; i++) { + buffer.append('[').append(']'); + } + + if (isVarArgs) { + buffer.append('.').append('.').append('.'); + } else { + buffer.append('[').append(']'); + } + return e; + } + + /* + * Scans the given string for a class type signature starting at the given + * index and appends it to the given buffer, and returns the index of the last + * character. + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @param fullyQualifyTypeNames true if type names should be fully + * qualified, and false to use only simple names + * @param buffer the string buffer to append to + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not a class type signature + * @see Utility#scanClassTypeSignature(char[], int) + */ + private static int appendClassTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { + // need a minimum 3 chars "Lx;" + if (start >= string.length - 2) { + throw new IllegalArgumentException(); + } + // must start in "L" or "Q" + char c = string[start]; + if (c != C_RESOLVED && c != C_UNRESOLVED) { + throw new IllegalArgumentException(); + } + boolean resolved = (c == C_RESOLVED); + boolean removePackageQualifiers = !fullyQualifyTypeNames; + if (!resolved) { + // keep everything in an unresolved name + removePackageQualifiers = false; + } + int p = start + 1; + int checkpoint = buffer.length(); + int innerTypeStart = -1; + boolean inAnonymousType = false; + while (true) { + if (p >= string.length) { + throw new IllegalArgumentException(); + } + c = string[p]; + switch (c) { + case C_SEMICOLON : + // all done + return p; + case C_GENERIC_START : + int e = appendTypeArgumentSignatures(string, p, fullyQualifyTypeNames, buffer); + // once we hit type arguments there are no more package prefixes + removePackageQualifiers = false; + p = e; + break; + case C_DOT : + if (removePackageQualifiers) { + // erase package prefix + buffer.setLength(checkpoint); + } else { + buffer.append('.'); + } + break; + case '/' : + if (removePackageQualifiers) { + // erase package prefix + buffer.setLength(checkpoint); + } else { + buffer.append('/'); + } + break; + case C_DOLLAR : + innerTypeStart = buffer.length(); + inAnonymousType = false; + if (resolved) { + // once we hit "$" there are no more package prefixes + removePackageQualifiers = false; + /* + * Convert '$' in resolved type signatures into '.'. + * NOTE: This assumes that the type signature is an inner type + * signature. This is true in most cases, but someone can define a + * non-inner type name containing a '$'. + */ + buffer.append('.'); + } + break; + default : + if (innerTypeStart != -1 && !inAnonymousType && Character.isDigit(c)) { + inAnonymousType = true; + buffer.setLength(innerTypeStart); // remove '.' + buffer.insert(checkpoint, "new "); //$NON-NLS-1$ + buffer.append("(){}"); //$NON-NLS-1$ + } + if (!inAnonymousType) + buffer.append(c); + innerTypeStart = -1; + } + p++; + } + } + + /* + * Scans the given string for a list of type arguments signature starting at the + * given index and appends it to the given buffer, and returns the index of the + * last character. + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @param fullyQualifyTypeNames true if type names should be fully + * qualified, and false to use only simple names + * @param buffer the string buffer to append to + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not a list of type argument + * signatures + * @see Utility#scanTypeArgumentSignatures(char[], int) + */ + private static int appendTypeArgumentSignatures(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { + // need a minimum 2 char "<>" + if (start >= string.length - 1) { + throw new IllegalArgumentException(); + } + char c = string[start]; + if (c != C_GENERIC_START) { + throw new IllegalArgumentException(); + } + buffer.append('<'); + int p = start + 1; + int count = 0; + while (true) { + if (p >= string.length) { + throw new IllegalArgumentException(); + } + c = string[p]; + if (c == C_GENERIC_END) { + buffer.append('>'); + return p; + } + if (count != 0) { + buffer.append(','); + } + int e = appendTypeArgumentSignature(string, p, fullyQualifyTypeNames, buffer); + count++; + p = e + 1; + } + } + + /* + * Scans the given string for a type argument signature starting at the given + * index and appends it to the given buffer, and returns the index of the last + * character. + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @param fullyQualifyTypeNames true if type names should be fully + * qualified, and false to use only simple names + * @param buffer the string buffer to append to + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not a type argument signature + * @see Utility#scanTypeArgumentSignature(char[], int) + */ + private static int appendTypeArgumentSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { + // need a minimum 1 char + if (start >= string.length) { + throw new IllegalArgumentException(); + } + char c = string[start]; + switch (c) { + case C_STAR : + buffer.append('?'); + return start; + case C_EXTENDS : + buffer.append("? extends "); //$NON-NLS-1$ + return appendTypeSignature(string, start + 1, fullyQualifyTypeNames, buffer); + case C_SUPER : + buffer.append("? super "); //$NON-NLS-1$ + return appendTypeSignature(string, start + 1, fullyQualifyTypeNames, buffer); + default : + return appendTypeSignature(string, start, fullyQualifyTypeNames, buffer); + } + } + + /* + * Converts the given method signature to a readable form. The method signature is expected to + * be dot-based. + *

    + * For example: + *

    +	 * 
    +	 * toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
    +	 * 
    +	 * 
    + *

    + * + * @param methodSignature the method signature to convert + * @param methodName the name of the method to insert in the result, or + * null if no method name is to be included + * @param parameterNames the parameter names to insert in the result, or + * null if no parameter names are to be included; if supplied, + * the number of parameter names must match that of the method signature + * @param fullyQualifyTypeNames true if type names should be fully + * qualified, and false to use only simple names + * @param includeReturnType true if the return type is to be + * included + * @return the char array representation of the method signature + * + * @since 2.0 + */ + public static char[] toCharArray(char[] methodSignature, char[] methodName, char[][] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType) { + return toCharArray(methodSignature, methodName, parameterNames, fullyQualifyTypeNames, includeReturnType, false); + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/SignatureAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/SignatureAttribute.java new file mode 100644 index 000000000..f186ca661 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/SignatureAttribute.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class SignatureAttribute extends ClassFileAttribute { + + private int signatureIndex; + private char[] signature; + + SignatureAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + super(classFileBytes, constantPool, offset); + final int index = u2At(classFileBytes, 6, offset); + this.signatureIndex = index; + ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(index); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.signature = constantPoolEntry.getUtf8Value(); + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.ISignatureAttribute#getSignatureIndex() + */ + public int getSignatureIndex() { + return this.signatureIndex; + } + + /* (non-Javadoc) + * @see org.eclipse.jdt.core.util.ISignatureAttribute#getSignature() + */ + public char[] getSignature() { + return this.signature; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/SourceFileAttribute.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/SourceFileAttribute.java new file mode 100644 index 000000000..1d51be982 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/SourceFileAttribute.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public class SourceFileAttribute extends ClassFileAttribute { + + private int sourceFileIndex; + private char[] sourceFileName; + + /** + * Constructor for SourceFileAttribute. + * @param classFileBytes + * @param constantPool + * @param offset + * @throws ClassFormatException + */ + public SourceFileAttribute(byte[] classFileBytes, ConstantPool constantPool, int offset) throws ClassFormatException { + super(classFileBytes, constantPool, offset); + this.sourceFileIndex = u2At(classFileBytes, 6, offset); + ConstantPoolEntry constantPoolEntry = constantPool.decodeEntry(this.sourceFileIndex); + if (constantPoolEntry.getKind() != ConstantPoolConstant.CONSTANT_Utf8) { + throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); + } + this.sourceFileName = constantPoolEntry.getUtf8Value(); + } + + /* + * @see ISourceAttribute#getSourceFileIndex() + */ + public int getSourceFileIndex() { + return this.sourceFileIndex; + } + + /* + * @see ISourceAttribute#getSourceFileName() + */ + public char[] getSourceFileName() { + return this.sourceFileName; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/TypeConstants.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/TypeConstants.java new file mode 100644 index 000000000..99e3e7841 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/TypeConstants.java @@ -0,0 +1,153 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +public interface TypeConstants { + + char[] JAVA = "java".toCharArray(); //$NON-NLS-1$ + char[] LANG = "lang".toCharArray(); //$NON-NLS-1$ + char[] IO = "io".toCharArray(); //$NON-NLS-1$ + char[] UTIL = "util".toCharArray(); //$NON-NLS-1$ + char[] ANNOTATION = "annotation".toCharArray(); //$NON-NLS-1$ + char[] REFLECT = "reflect".toCharArray(); //$NON-NLS-1$ + char[] LENGTH = "length".toCharArray(); //$NON-NLS-1$ + char[] CLONE = "clone".toCharArray(); //$NON-NLS-1$ + char[] EQUALS = "equals".toCharArray(); //$NON-NLS-1$ + char[] GETCLASS = "getClass".toCharArray(); //$NON-NLS-1$ + char[] HASHCODE = "hashCode".toCharArray(); //$NON-NLS-1$ + char[] OBJECT = "Object".toCharArray(); //$NON-NLS-1$ + char[] MAIN = "main".toCharArray(); //$NON-NLS-1$ + char[] SERIALVERSIONUID = "serialVersionUID".toCharArray(); //$NON-NLS-1$ + char[] SERIALPERSISTENTFIELDS = "serialPersistentFields".toCharArray(); //$NON-NLS-1$ + char[] READRESOLVE = "readResolve".toCharArray(); //$NON-NLS-1$ + char[] WRITEREPLACE = "writeReplace".toCharArray(); //$NON-NLS-1$ + char[] READOBJECT = "readObject".toCharArray(); //$NON-NLS-1$ + char[] WRITEOBJECT = "writeObject".toCharArray(); //$NON-NLS-1$ + char[] CharArray_JAVA_LANG_OBJECT = "java.lang.Object".toCharArray(); //$NON-NLS-1$ + char[] CharArray_JAVA_LANG_ENUM = "java.lang.Enum".toCharArray(); //$NON-NLS-1$ + char[] CharArray_JAVA_LANG_ANNOTATION_ANNOTATION = "java.lang.annotation.Annotation".toCharArray(); //$NON-NLS-1$ + char[] CharArray_JAVA_IO_OBJECTINPUTSTREAM = "java.io.ObjectInputStream".toCharArray(); //$NON-NLS-1$ + char[] CharArray_JAVA_IO_OBJECTOUTPUTSTREAM = "java.io.ObjectOutputStream".toCharArray(); //$NON-NLS-1$ + char[] CharArray_JAVA_IO_OBJECTSTREAMFIELD = "java.io.ObjectStreamField".toCharArray(); //$NON-NLS-1$ + char[] ANONYM_PREFIX = "new ".toCharArray(); //$NON-NLS-1$ + char[] ANONYM_SUFFIX = "(){}".toCharArray(); //$NON-NLS-1$ + char[] WILDCARD_NAME = {'?'}; + char[] WILDCARD_SUPER = " super ".toCharArray(); //$NON-NLS-1$ + char[] WILDCARD_EXTENDS = " extends ".toCharArray(); //$NON-NLS-1$ + char[] WILDCARD_MINUS = {'-'}; + char[] WILDCARD_STAR = {'*'}; + char[] WILDCARD_PLUS = {'+'}; + char[] WILDCARD_CAPTURE_NAME_PREFIX = "capture#".toCharArray(); //$NON-NLS-1$ + char[] WILDCARD_CAPTURE_NAME_SUFFIX = "-of ".toCharArray(); //$NON-NLS-1$ + char[] WILDCARD_CAPTURE = {'!'}; + char[] BYTE = "byte".toCharArray(); //$NON-NLS-1$ + char[] SHORT = "short".toCharArray(); //$NON-NLS-1$ + char[] INT = "int".toCharArray(); //$NON-NLS-1$ + char[] LONG = "long".toCharArray(); //$NON-NLS-1$ + char[] FLOAT = "float".toCharArray(); //$NON-NLS-1$ + char[] DOUBLE = "double".toCharArray(); //$NON-NLS-1$ + char[] CHAR = "char".toCharArray(); //$NON-NLS-1$ + char[] BOOLEAN = "boolean".toCharArray(); //$NON-NLS-1$ + char[] NULL = "null".toCharArray(); //$NON-NLS-1$ + char[] VOID = "void".toCharArray(); //$NON-NLS-1$ + char[] VALUE = "value".toCharArray(); //$NON-NLS-1$ + char[] VALUES = "values".toCharArray(); //$NON-NLS-1$ + char[] VALUEOF = "valueOf".toCharArray(); //$NON-NLS-1$ + char[] UPPER_SOURCE = "SOURCE".toCharArray(); //$NON-NLS-1$ + char[] UPPER_CLASS = "CLASS".toCharArray(); //$NON-NLS-1$ + char[] UPPER_RUNTIME = "RUNTIME".toCharArray(); //$NON-NLS-1$ + char[] ANNOTATION_PREFIX = "@".toCharArray(); //$NON-NLS-1$ + char[] ANNOTATION_SUFFIX = "()".toCharArray(); //$NON-NLS-1$ + char[] TYPE = "TYPE".toCharArray(); //$NON-NLS-1$ + char[] UPPER_FIELD = "FIELD".toCharArray(); //$NON-NLS-1$ + char[] UPPER_METHOD = "METHOD".toCharArray(); //$NON-NLS-1$ + char[] UPPER_PARAMETER = "PARAMETER".toCharArray(); //$NON-NLS-1$ + char[] UPPER_CONSTRUCTOR = "CONSTRUCTOR".toCharArray(); //$NON-NLS-1$ + char[] UPPER_LOCAL_VARIABLE = "LOCAL_VARIABLE".toCharArray(); //$NON-NLS-1$ + char[] UPPER_ANNOTATION_TYPE = "ANNOTATION_TYPE".toCharArray(); //$NON-NLS-1$ + char[] UPPER_PACKAGE = "PACKAGE".toCharArray(); //$NON-NLS-1$ + + // Constant compound names + char[][] JAVA_LANG = {JAVA, LANG}; + char[][] JAVA_IO = {JAVA, IO}; + char[][] JAVA_LANG_ANNOTATION_ANNOTATION = {JAVA, LANG, ANNOTATION, "Annotation".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_ASSERTIONERROR = {JAVA, LANG, "AssertionError".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_CLASS = {JAVA, LANG, "Class".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_CLASSNOTFOUNDEXCEPTION = {JAVA, LANG, "ClassNotFoundException".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_CLONEABLE = {JAVA, LANG, "Cloneable".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_ENUM = {JAVA, LANG, "Enum".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_EXCEPTION = {JAVA, LANG, "Exception".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_ERROR = {JAVA, LANG, "Error".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_ILLEGALARGUMENTEXCEPTION = {JAVA, LANG, "IllegalArgumentException".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_ITERABLE = {JAVA, LANG, "Iterable".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_NOCLASSDEFERROR = {JAVA, LANG, "NoClassDefError".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_OBJECT = {JAVA, LANG, OBJECT}; + char[][] JAVA_LANG_STRING = {JAVA, LANG, "String".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_STRINGBUFFER = {JAVA, LANG, "StringBuffer".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_STRINGBUILDER = {JAVA, LANG, "StringBuilder".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_SYSTEM = {JAVA, LANG, "System".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_RUNTIMEEXCEPTION = {JAVA, LANG, "RuntimeException".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_THROWABLE = {JAVA, LANG, "Throwable".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_REFLECT_CONSTRUCTOR = {JAVA, LANG, REFLECT, "Constructor".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_IO_PRINTSTREAM = {JAVA, IO, "PrintStream".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_IO_SERIALIZABLE = {JAVA, IO, "Serializable".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_BYTE = {JAVA, LANG, "Byte".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_SHORT = {JAVA, LANG, "Short".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_CHARACTER = {JAVA, LANG, "Character".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_INTEGER = {JAVA, LANG, "Integer".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_LONG = {JAVA, LANG, "Long".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_FLOAT = {JAVA, LANG, "Float".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_DOUBLE = {JAVA, LANG, "Double".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_BOOLEAN = {JAVA, LANG, "Boolean".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_VOID = {JAVA, LANG, "Void".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_UTIL_COLLECTION = {JAVA, UTIL, "Collection".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_UTIL_ITERATOR = {JAVA, UTIL, "Iterator".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_DEPRECATED = {JAVA, LANG, "Deprecated".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_ANNOTATION_DOCUMENTED = {JAVA, LANG, ANNOTATION, "Documented".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_ANNOTATION_INHERITED = {JAVA, LANG, ANNOTATION, "Inherited".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_OVERRIDE = {JAVA, LANG, "Override".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_ANNOTATION_RETENTION = {JAVA, LANG, ANNOTATION, "Retention".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_SUPPRESSWARNINGS = {JAVA, LANG, "SuppressWarnings".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_ANNOTATION_TARGET = {JAVA, LANG, ANNOTATION, "Target".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_ANNOTATION_RETENTIONPOLICY = {JAVA, LANG, ANNOTATION, "RetentionPolicy".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_ANNOTATION_ELEMENTTYPE = {JAVA, LANG, ANNOTATION, "ElementType".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_REFLECT_FIELD = new char[][] {JAVA, LANG, REFLECT, "Field".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_LANG_REFLECT_METHOD = new char[][] {JAVA, LANG, REFLECT, "Method".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_IO_OBJECTSTREAMEXCEPTION = new char[][] {JAVA, IO, "ObjectStreamException".toCharArray()};//$NON-NLS-1$ + char[][] JAVA_IO_EXTERNALIZABLE = {JAVA, IO, "Externalizable".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_IO_IOEXCEPTION = new char[][] {JAVA, IO, "IOException".toCharArray()};//$NON-NLS-1$ + char[][] JAVA_IO_OBJECTOUTPUTSTREAM = new char[][] {JAVA, IO, "ObjectOutputStream".toCharArray()}; //$NON-NLS-1$ + char[][] JAVA_IO_OBJECTINPUTSTREAM = new char[][] {JAVA, IO, "ObjectInputStream".toCharArray()}; //$NON-NLS-1$ + + // Constraints for generic type argument inference + int CONSTRAINT_EQUAL = 0; // Actual = Formal + int CONSTRAINT_EXTENDS = 1; // Actual << Formal + int CONSTRAINT_SUPER = 2; // Actual >> Formal + + // Constants used to perform bound checks + int OK = 0; + int UNCHECKED = 1; + int MISMATCH = 2; + + // Synthetics + char[] INIT = "".toCharArray(); //$NON-NLS-1$ + char[] CLINIT = "".toCharArray(); //$NON-NLS-1$ + char[] SYNTHETIC_SWITCH_ENUM_TABLE = "$SWITCH_TABLE$".toCharArray(); //$NON-NLS-1$ + char[] SYNTHETIC_ENUM_VALUES = "ENUM$VALUES".toCharArray(); //$NON-NLS-1$ + char[] SYNTHETIC_ASSERT_DISABLED = "$assertionsDisabled".toCharArray(); //$NON-NLS-1$ + char[] SYNTHETIC_CLASS = "class$".toCharArray(); //$NON-NLS-1$ + char[] SYNTHETIC_OUTER_LOCAL_PREFIX = "val$".toCharArray(); //$NON-NLS-1$ + char[] SYNTHETIC_ENCLOSING_INSTANCE_PREFIX = "this$".toCharArray(); //$NON-NLS-1$ + char[] SYNTHETIC_ACCESS_METHOD_PREFIX = "access$".toCharArray(); //$NON-NLS-1$ + + // synthetic package-info name + public static final char[] PACKAGE_INFO_NAME = "package-info".toCharArray(); //$NON-NLS-1$ +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Utility.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Utility.java new file mode 100644 index 000000000..4a982deb4 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/Utility.java @@ -0,0 +1,689 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.comparator.java; + +import java.io.*; +import java.util.Arrays; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +public class Utility { + public static final int[] EMPTY_INT_ARRAY = new int[0]; + public static final String EMPTY_STRING = ""; //$NON-NLS-1$ + private static final int DEFAULT_READING_SIZE = 8192; + private static final char[] BOOLEAN = "boolean".toCharArray(); //$NON-NLS-1$ + private static final char[] BYTE = "byte".toCharArray(); //$NON-NLS-1$ + private static final char[] CHAR = "char".toCharArray(); //$NON-NLS-1$ + private static final char[] DOUBLE = "double".toCharArray(); //$NON-NLS-1$ + private static final char[] FLOAT = "float".toCharArray(); //$NON-NLS-1$ + private static final char[] INT = "int".toCharArray(); //$NON-NLS-1$ + private static final char[] LONG = "long".toCharArray(); //$NON-NLS-1$ + private static final char[] SHORT = "short".toCharArray(); //$NON-NLS-1$ + private static final char[] VOID = "void".toCharArray(); //$NON-NLS-1$ + private static final char[] INIT = "".toCharArray(); //$NON-NLS-1$ + + /** + * Returns the contents of the given zip entry as a byte array. + * @throws IOException if a problem occured reading the zip entry. + */ + public static byte[] getZipEntryByteContent(ZipEntry ze, ZipFile zip) throws IOException { + + InputStream stream = null; + try { + stream = zip.getInputStream(ze); + if (stream == null) + throw new IOException("Invalid zip entry name : " + ze.getName()); //$NON-NLS-1$ + return getInputStreamAsByteArray(stream, (int) ze.getSize()); + } finally { + close(stream); + } + } + + public static void close(Object object) { + if (object == null) + return; + try { + if (object instanceof InputStream) + ((InputStream) object).close(); + else if (object instanceof OutputStream) + ((OutputStream) object).close(); + else if (object instanceof ZipFile) + ((ZipFile) object).close(); + } catch (IOException e) { + //ignore + } + } + + /** + * Returns the given input stream's contents as a byte array. + * If a length is specified (ie. if length != -1), only length bytes + * are returned. Otherwise all bytes in the stream are returned. + * Note this doesn't close the stream. + * @throws IOException if a problem occured reading the stream. + */ + public static byte[] getInputStreamAsByteArray(InputStream stream, int length) throws IOException { + byte[] contents; + if (length == -1) { + contents = new byte[0]; + int contentsLength = 0; + int amountRead = -1; + do { + int amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K + + // resize contents if needed + if (contentsLength + amountRequested > contents.length) { + System.arraycopy(contents, 0, contents = new byte[contentsLength + amountRequested], 0, contentsLength); + } + + // read as many bytes as possible + amountRead = stream.read(contents, contentsLength, amountRequested); + + if (amountRead > 0) { + // remember length of contents + contentsLength += amountRead; + } + } while (amountRead != -1); + + // resize contents if necessary + if (contentsLength < contents.length) { + System.arraycopy(contents, 0, contents = new byte[contentsLength], 0, contentsLength); + } + } else { + contents = new byte[length]; + int len = 0; + int readSize = 0; + while ((readSize != -1) && (len != length)) { + // See PR 1FMS89U + // We record first the read size. In this case len is the actual read size. + len += readSize; + readSize = stream.read(contents, len, length - len); + } + } + + return contents; + } + + public static ClassFileAttribute getAttribute(MethodInfo methodInfo, char[] attributeName) { + ClassFileAttribute[] attributes = methodInfo.getAttributes(); + for (int i = 0, max = attributes.length; i < max; i++) { + if (Arrays.equals(attributes[i].getAttributeName(), attributeName)) { + return attributes[i]; + } + } + return null; + } + + public static ClassFileAttribute getAttribute(FieldInfo fieldInfo, char[] attributeName) { + ClassFileAttribute[] attributes = fieldInfo.getAttributes(); + for (int i = 0, max = attributes.length; i < max; i++) { + if (Arrays.equals(attributes[i].getAttributeName(), attributeName)) { + return attributes[i]; + } + } + return null; + } + + public static ClassFileAttribute getAttribute(ClassFileReader classFileReader, char[] attributeName) { + ClassFileAttribute[] attributes = classFileReader.getAttributes(); + for (int i = 0, max = attributes.length; i < max; i++) { + if (Arrays.equals(attributes[i].getAttributeName(), attributeName)) { + return attributes[i]; + } + } + return null; + } + + /** + * Scans the given string for a type signature starting at the given index + * and returns the index of the last character. + *
    +	 * TypeSignature:
    +	 *  |  BaseTypeSignature
    +	 *  |  ArrayTypeSignature
    +	 *  |  ClassTypeSignature
    +	 *  |  TypeVariableSignature
    +	 * 
    + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not a type signature + */ + public static int scanTypeSignature(char[] string, int start) { + // need a minimum 1 char + if (start >= string.length) { + throw new IllegalArgumentException(); + } + char c = string[start]; + switch (c) { + case Signature.C_ARRAY : + return scanArrayTypeSignature(string, start); + case Signature.C_RESOLVED : + case Signature.C_UNRESOLVED : + return scanClassTypeSignature(string, start); + case Signature.C_TYPE_VARIABLE : + return scanTypeVariableSignature(string, start); + case Signature.C_BOOLEAN : + case Signature.C_BYTE : + case Signature.C_CHAR : + case Signature.C_DOUBLE : + case Signature.C_FLOAT : + case Signature.C_INT : + case Signature.C_LONG : + case Signature.C_SHORT : + case Signature.C_VOID : + return scanBaseTypeSignature(string, start); + case Signature.C_CAPTURE : + return scanCaptureTypeSignature(string, start); + case Signature.C_EXTENDS : + case Signature.C_SUPER : + case Signature.C_STAR : + return scanTypeBoundSignature(string, start); + default : + throw new IllegalArgumentException(); + } + } + + /** + * Scans the given string for a base type signature starting at the given index + * and returns the index of the last character. + *
    +	 * BaseTypeSignature:
    +	 *     B | C | D | F | I
    +	 *   | J | S | V | Z
    +	 * 
    + * Note that although the base type "V" is only allowed in method return types, + * there is no syntactic ambiguity. This method will accept them anywhere + * without complaint. + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not a base type signature + */ + public static int scanBaseTypeSignature(char[] string, int start) { + // need a minimum 1 char + if (start >= string.length) { + throw new IllegalArgumentException(); + } + char c = string[start]; + if ("BCDFIJSVZ".indexOf(c) >= 0) { //$NON-NLS-1$ + return start; + } + throw new IllegalArgumentException(); + } + + /** + * Scans the given string for an array type signature starting at the given + * index and returns the index of the last character. + *
    +	 * ArrayTypeSignature:
    +	 *     [ TypeSignature
    +	 * 
    + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not an array type signature + */ + public static int scanArrayTypeSignature(char[] string, int start) { + int length = string.length; + // need a minimum 2 char + if (start >= length - 1) { + throw new IllegalArgumentException(); + } + char c = string[start]; + if (c != Signature.C_ARRAY) { + throw new IllegalArgumentException(); + } + + c = string[++start]; + while (c == Signature.C_ARRAY) { + // need a minimum 2 char + if (start >= length - 1) { + throw new IllegalArgumentException(); + } + c = string[++start]; + } + return scanTypeSignature(string, start); + } + + /** + * Scans the given string for a capture of a wildcard type signature starting at the given + * index and returns the index of the last character. + *
    +	 * CaptureTypeSignature:
    +	 *     ! TypeBoundSignature
    +	 * 
    + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not a capture type signature + */ + public static int scanCaptureTypeSignature(char[] string, int start) { + // need a minimum 2 char + if (start >= string.length - 1) { + throw new IllegalArgumentException(); + } + char c = string[start]; + if (c != Signature.C_CAPTURE) { + throw new IllegalArgumentException(); + } + return scanTypeBoundSignature(string, start + 1); + } + + /** + * Scans the given string for a type variable signature starting at the given + * index and returns the index of the last character. + *
    +	 * TypeVariableSignature:
    +	 *     T Identifier ;
    +	 * 
    + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not a type variable signature + */ + public static int scanTypeVariableSignature(char[] string, int start) { + // need a minimum 3 chars "Tx;" + if (start >= string.length - 2) { + throw new IllegalArgumentException(); + } + // must start in "T" + char c = string[start]; + if (c != Signature.C_TYPE_VARIABLE) { + throw new IllegalArgumentException(); + } + int id = scanIdentifier(string, start + 1); + c = string[id + 1]; + if (c == Signature.C_SEMICOLON) { + return id + 1; + } + throw new IllegalArgumentException(); + } + + /** + * Scans the given string for an identifier starting at the given + * index and returns the index of the last character. + * Stop characters are: ";", ":", "<", ">", "/", ".". + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not an identifier + */ + public static int scanIdentifier(char[] string, int start) { + // need a minimum 1 char + if (start >= string.length) { + throw new IllegalArgumentException(); + } + int p = start; + while (true) { + char c = string[p]; + if (c == '<' || c == '>' || c == ':' || c == ';' || c == '.' || c == '/') { + return p - 1; + } + p++; + if (p == string.length) { + return p - 1; + } + } + } + + /** + * Scans the given string for a class type signature starting at the given + * index and returns the index of the last character. + *
    +	 * ClassTypeSignature:
    +	 *     { L | Q } Identifier
    +	 *           { { / | . Identifier [ < TypeArgumentSignature* > ] }
    +	 *           ;
    +	 * 
    + * Note that although all "/"-identifiers most come before "."-identifiers, + * there is no syntactic ambiguity. This method will accept them without + * complaint. + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not a class type signature + */ + public static int scanClassTypeSignature(char[] string, int start) { + // need a minimum 3 chars "Lx;" + if (start >= string.length - 2) { + throw new IllegalArgumentException(); + } + // must start in "L" or "Q" + char c = string[start]; + if (c != Signature.C_RESOLVED && c != Signature.C_UNRESOLVED) { + return -1; + } + int p = start + 1; + while (true) { + if (p >= string.length) { + throw new IllegalArgumentException(); + } + c = string[p]; + if (c == Signature.C_SEMICOLON) { + // all done + return p; + } else if (c == Signature.C_GENERIC_START) { + int e = scanTypeArgumentSignatures(string, p); + p = e; + } else if (c == Signature.C_DOT || c == '/') { + int id = scanIdentifier(string, p + 1); + p = id; + } + p++; + } + } + + /** + * Scans the given string for a type bound signature starting at the given + * index and returns the index of the last character. + *
    +	 * TypeBoundSignature:
    +	 *     [-+] TypeSignature ;
    +	 *     *
    +	 * 
    + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not a type variable signature + */ + public static int scanTypeBoundSignature(char[] string, int start) { + // need a minimum 1 char for wildcard + if (start >= string.length) { + throw new IllegalArgumentException(); + } + char c = string[start]; + switch (c) { + case Signature.C_STAR : + return start; + case Signature.C_SUPER : + case Signature.C_EXTENDS : + // need a minimum 3 chars "+[I" + if (start >= string.length - 2) { + throw new IllegalArgumentException(); + } + break; + default : + // must start in "+/-" + throw new IllegalArgumentException(); + + } + c = string[++start]; + switch (c) { + case Signature.C_CAPTURE : + return scanCaptureTypeSignature(string, start); + case Signature.C_SUPER : + case Signature.C_EXTENDS : + return scanTypeBoundSignature(string, start); + case Signature.C_RESOLVED : + case Signature.C_UNRESOLVED : + return scanClassTypeSignature(string, start); + case Signature.C_TYPE_VARIABLE : + return scanTypeVariableSignature(string, start); + case Signature.C_ARRAY : + return scanArrayTypeSignature(string, start); + case Signature.C_STAR : + return start; + default : + throw new IllegalArgumentException(); + } + } + + /** + * Scans the given string for a list of type argument signatures starting at + * the given index and returns the index of the last character. + *
    +	 * TypeArgumentSignatures:
    +	 *     < TypeArgumentSignature* >
    +	 * 
    + * Note that although there is supposed to be at least one type argument, there + * is no syntactic ambiguity if there are none. This method will accept zero + * type argument signatures without complaint. + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not a list of type arguments + * signatures + */ + public static int scanTypeArgumentSignatures(char[] string, int start) { + // need a minimum 2 char "<>" + if (start >= string.length - 1) { + throw new IllegalArgumentException(); + } + char c = string[start]; + if (c != Signature.C_GENERIC_START) { + throw new IllegalArgumentException(); + } + int p = start + 1; + while (true) { + if (p >= string.length) { + throw new IllegalArgumentException(); + } + c = string[p]; + if (c == Signature.C_GENERIC_END) { + return p; + } + int e = scanTypeArgumentSignature(string, p); + p = e + 1; + } + } + + /** + * Scans the given string for a type argument signature starting at the given + * index and returns the index of the last character. + *
    +	 * TypeArgumentSignature:
    +	 *     *
    +	 *  |  + TypeSignature
    +	 *  |  - TypeSignature
    +	 *  |  TypeSignature
    +	 * 
    + * Note that although base types are not allowed in type arguments, there is + * no syntactic ambiguity. This method will accept them without complaint. + * + * @param string the signature string + * @param start the 0-based character index of the first character + * @return the 0-based character index of the last character + * @exception IllegalArgumentException if this is not a type argument signature + */ + public static int scanTypeArgumentSignature(char[] string, int start) { + // need a minimum 1 char + if (start >= string.length) { + throw new IllegalArgumentException(); + } + char c = string[start]; + switch (c) { + case Signature.C_STAR : + return start; + case Signature.C_EXTENDS : + case Signature.C_SUPER : + return scanTypeBoundSignature(string, start); + default : + return scanTypeSignature(string, start); + } + } + + static void appendTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) { + char c = string[start]; + switch (c) { + case Signature.C_ARRAY : + appendArrayTypeSignature(string, start, buffer, compact); + break; + case Signature.C_RESOLVED : + appendClassTypeSignature(string, start, buffer, compact); + break; + case Signature.C_TYPE_VARIABLE : + int e = scanTypeVariableSignature(string, start); + buffer.append(string, start + 1, e - start - 1); + break; + case Signature.C_BOOLEAN : + buffer.append(BOOLEAN); + break; + case Signature.C_BYTE : + buffer.append(BYTE); + break; + case Signature.C_CHAR : + buffer.append(CHAR); + break; + case Signature.C_DOUBLE : + buffer.append(DOUBLE); + break; + case Signature.C_FLOAT : + buffer.append(FLOAT); + break; + case Signature.C_INT : + buffer.append(INT); + break; + case Signature.C_LONG : + buffer.append(LONG); + break; + case Signature.C_SHORT : + buffer.append(SHORT); + break; + case Signature.C_VOID : + buffer.append(VOID); + break; + } + } + + private static void appendArrayTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) { + int length = string.length; + // need a minimum 2 char + if (start >= length - 1) { + throw new IllegalArgumentException(); + } + char c = string[start]; + if (c != Signature.C_ARRAY) { + throw new IllegalArgumentException(); + } + + int index = start; + c = string[++index]; + while (c == Signature.C_ARRAY) { + // need a minimum 2 char + if (index >= length - 1) { + throw new IllegalArgumentException(); + } + c = string[++index]; + } + + appendTypeSignature(string, index, buffer, compact); + + for (int i = 0, dims = index - start; i < dims; i++) { + buffer.append('[').append(']'); + } + } + + private static void appendClassTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) { + char c = string[start]; + if (c != Signature.C_RESOLVED) { + return; + } + int p = start + 1; + int checkpoint = buffer.length(); + while (true) { + c = string[p]; + switch (c) { + case Signature.C_SEMICOLON : + // all done + return; + case Signature.C_DOT : + case '/' : + // erase package prefix + if (compact) { + buffer.setLength(checkpoint); + } else { + buffer.append('.'); + } + break; + case Signature.C_DOLLAR : + /** + * Convert '$' in resolved type signatures into '.'. + * NOTE: This assumes that the type signature is an inner type + * signature. This is true in most cases, but someone can define a + * non-inner type name containing a '$'. + */ + buffer.append('.'); + break; + default : + buffer.append(c); + } + p++; + } + } + + public static String toString(char[] declaringClass, char[] methodName, char[] methodSignature, boolean includeReturnType, boolean compact) { + final boolean isConstructor = Arrays.equals(methodName, INIT); + int firstParen = CharOperation.indexOf(Signature.C_PARAM_START, methodSignature); + if (firstParen == -1) { + return ""; //$NON-NLS-1$ + } + + StringBuffer buffer = new StringBuffer(methodSignature.length + 10); + + // decode declaring class name + // it can be either an array signature or a type signature + if (declaringClass.length > 0) { + char[] declaringClassSignature = null; + if (declaringClass[0] == Signature.C_ARRAY) { + CharOperation.replace(declaringClass, '/', '.'); + declaringClassSignature = Signature.toCharArray(declaringClass); + } else { + CharOperation.replace(declaringClass, '/', '.'); + declaringClassSignature = declaringClass; + } + int lastIndexOfSlash = CharOperation.lastIndexOf('.', declaringClassSignature); + if (compact && lastIndexOfSlash != -1) { + buffer.append(declaringClassSignature, lastIndexOfSlash + 1, declaringClassSignature.length - lastIndexOfSlash - 1); + } else { + buffer.append(declaringClassSignature); + } + } + + // selector + if (!isConstructor) { + buffer.append('.'); + if (methodName != null) { + buffer.append(methodName); + } + } + + // parameters + buffer.append('('); + char[][] pts = Signature.getParameterTypes(methodSignature); + for (int i = 0, max = pts.length; i < max; i++) { + appendTypeSignature(pts[i], 0, buffer, compact); + if (i != pts.length - 1) { + buffer.append(','); + buffer.append(' '); + } + } + buffer.append(')'); + + if (!isConstructor) { + buffer.append(" : "); //$NON-NLS-1$ + // return type + if (includeReturnType) { + char[] rts = Signature.getReturnType(methodSignature); + appendTypeSignature(rts, 0, buffer, compact); + } + } + return String.valueOf(buffer); + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/messages.properties b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/messages.properties new file mode 100644 index 000000000..e8c395639 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/java/messages.properties @@ -0,0 +1,98 @@ +############################################################################### +# Copyright (c) 2009 IBM Corporation and others. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# IBM Corporation - initial API and implementation +############################################################################### +differentNumberOfEntries=Difference in [{0}]: {1} contains {2} files and {3} contains {4} files +differentEntry=Difference found for {0} within [{1}] from {2} +missingEntry=Missing {0} within [{1}] from {2} +ioexception=IOException comparing {0} and {1} + +### Disassembler messages + +### disassembler +disassembler_opentypedeclaration =\ '{' +disassembler_closetypedeclaration = } +disassembler_endofmethodheader = ; +disassembler_begincommentline = //\ +disassembler_fieldhasconstant =\ =\ +disassembler_endoffieldheader = ; +disassembler_sourceattributeheader = Compiled from\ +disassembler_enclosingmethodheader = Enclosing Method: +disassembler_exceptiontableheader = Exception Table: +disassembler_innerattributesheader = Inner classes: +disassembler_inner_class_info_name = inner class info: +disassembler_outer_class_info_name = outer class info: +disassembler_inner_name = inner name: +disassembler_inner_accessflags = accessflags:\ +disassembler_signatureattributeheader = // Signature: {0} +disassembler_indentation = \ +disassembler_space = \ +disassembler_comma = , +disassembler_openinnerclassentry = [ +disassembler_closeinnerclassentry = ] +disassembler_deprecated =\ (deprecated) +disassembler_annotationdefaultheader = Annotation Default:\ +disassembler_annotationdefaultvalue= {0} (constant type) +disassembler_annotationenumvalue = {0}.{1}(enum type) +disassembler_annotationclassvalue = {0} (class type) +disassembler_annotationannotationvalue = annotation value = +disassembler_annotationarrayvaluestart = [ +disassembler_annotationarrayvalueend = ] +disassembler_annotationentrystart = @{0}( +disassembler_annotationentryend = ) +disassembler_annotationcomponent = {0}= +disassembler_runtimevisibleannotationsattributeheader= RuntimeVisibleAnnotations:\ +disassembler_runtimeinvisibleannotationsattributeheader= RuntimeInvisibleAnnotations:\ +disassembler_runtimevisibleparameterannotationsattributeheader= RuntimeVisibleParameterAnnotations:\ +disassembler_runtimeinvisibleparameterannotationsattributeheader= RuntimeInvisibleParameterAnnotations:\ +disassembler_parameterannotationentrystart=Number of annotations for parameter {0}: {1} +### classfileformat decoding +classfileformat_versiondetails =\ (version {0} : {1}.{2}, {3}) +classfileformat_methoddescriptor = // Method descriptor {0} +classfileformat_fieldddescriptor = // Field descriptor {0} +classfileformat_stacksAndLocals= // Stack: {0}, Locals: {1} +classfileformat_superflagisnotset = no super bit +classfileformat_superflagisset = super bit +classfileformat_clinitname = '{'} +classformat_classformatexception = Class Format Exception +classfileformat_versionUnknown = unknown + +### string displayed for each opcode +classformat_anewarray = {0} {1} +classformat_checkcast = {0} {1} +classformat_instanceof = {0} {1} +classformat_ldc_w_class = {0} +classformat_ldc_w_float = {0} +classformat_ldc_w_integer = {0} +classformat_ldc_w_string = {0} +classformat_ldc2_w_long = {0} +classformat_ldc2_w_double = {0} +classformat_multianewarray = {0} {1} +classformat_new = {0} {1} +classformat_iinc = {0} {1} {2}{3} +classformat_invokespecial ={0} {1} +classformat_invokeinterface ={0} {2} [nargs: {1}] +classformat_invokestatic ={0} {1} +classformat_invokevirtual ={0} {1} +classformat_getfield ={0} {1}.{2} : {3} +classformat_getstatic ={0} {1}.{2} : {3} +classformat_putstatic ={0} {1}.{2} : {3} +classformat_putfield ={0} {1}.{2} : {3} +classformat_newarray_boolean = {0} boolean +classformat_newarray_char = {0} char +classformat_newarray_float = {0} float +classformat_newarray_double = {0} double +classformat_newarray_byte = {0} byte +classformat_newarray_short = {0} short +classformat_newarray_int = {0} int +classformat_newarray_long = {0} long +classformat_store = {0}{1} +classformat_load = {0}{1} +classfileformat_anyexceptionhandler=any +classfileformat_exceptiontableentry = [pc: {0}, pc: {1}] -> {2} when : {3} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/messages.properties b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/messages.properties deleted file mode 100644 index e8c395639..000000000 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/comparator/messages.properties +++ /dev/null @@ -1,98 +0,0 @@ -############################################################################### -# Copyright (c) 2009 IBM Corporation and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# IBM Corporation - initial API and implementation -############################################################################### -differentNumberOfEntries=Difference in [{0}]: {1} contains {2} files and {3} contains {4} files -differentEntry=Difference found for {0} within [{1}] from {2} -missingEntry=Missing {0} within [{1}] from {2} -ioexception=IOException comparing {0} and {1} - -### Disassembler messages - -### disassembler -disassembler_opentypedeclaration =\ '{' -disassembler_closetypedeclaration = } -disassembler_endofmethodheader = ; -disassembler_begincommentline = //\ -disassembler_fieldhasconstant =\ =\ -disassembler_endoffieldheader = ; -disassembler_sourceattributeheader = Compiled from\ -disassembler_enclosingmethodheader = Enclosing Method: -disassembler_exceptiontableheader = Exception Table: -disassembler_innerattributesheader = Inner classes: -disassembler_inner_class_info_name = inner class info: -disassembler_outer_class_info_name = outer class info: -disassembler_inner_name = inner name: -disassembler_inner_accessflags = accessflags:\ -disassembler_signatureattributeheader = // Signature: {0} -disassembler_indentation = \ -disassembler_space = \ -disassembler_comma = , -disassembler_openinnerclassentry = [ -disassembler_closeinnerclassentry = ] -disassembler_deprecated =\ (deprecated) -disassembler_annotationdefaultheader = Annotation Default:\ -disassembler_annotationdefaultvalue= {0} (constant type) -disassembler_annotationenumvalue = {0}.{1}(enum type) -disassembler_annotationclassvalue = {0} (class type) -disassembler_annotationannotationvalue = annotation value = -disassembler_annotationarrayvaluestart = [ -disassembler_annotationarrayvalueend = ] -disassembler_annotationentrystart = @{0}( -disassembler_annotationentryend = ) -disassembler_annotationcomponent = {0}= -disassembler_runtimevisibleannotationsattributeheader= RuntimeVisibleAnnotations:\ -disassembler_runtimeinvisibleannotationsattributeheader= RuntimeInvisibleAnnotations:\ -disassembler_runtimevisibleparameterannotationsattributeheader= RuntimeVisibleParameterAnnotations:\ -disassembler_runtimeinvisibleparameterannotationsattributeheader= RuntimeInvisibleParameterAnnotations:\ -disassembler_parameterannotationentrystart=Number of annotations for parameter {0}: {1} -### classfileformat decoding -classfileformat_versiondetails =\ (version {0} : {1}.{2}, {3}) -classfileformat_methoddescriptor = // Method descriptor {0} -classfileformat_fieldddescriptor = // Field descriptor {0} -classfileformat_stacksAndLocals= // Stack: {0}, Locals: {1} -classfileformat_superflagisnotset = no super bit -classfileformat_superflagisset = super bit -classfileformat_clinitname = '{'} -classformat_classformatexception = Class Format Exception -classfileformat_versionUnknown = unknown - -### string displayed for each opcode -classformat_anewarray = {0} {1} -classformat_checkcast = {0} {1} -classformat_instanceof = {0} {1} -classformat_ldc_w_class = {0} -classformat_ldc_w_float = {0} -classformat_ldc_w_integer = {0} -classformat_ldc_w_string = {0} -classformat_ldc2_w_long = {0} -classformat_ldc2_w_double = {0} -classformat_multianewarray = {0} {1} -classformat_new = {0} {1} -classformat_iinc = {0} {1} {2}{3} -classformat_invokespecial ={0} {1} -classformat_invokeinterface ={0} {2} [nargs: {1}] -classformat_invokestatic ={0} {1} -classformat_invokevirtual ={0} {1} -classformat_getfield ={0} {1}.{2} : {3} -classformat_getstatic ={0} {1}.{2} : {3} -classformat_putstatic ={0} {1}.{2} : {3} -classformat_putfield ={0} {1}.{2} : {3} -classformat_newarray_boolean = {0} boolean -classformat_newarray_char = {0} char -classformat_newarray_float = {0} float -classformat_newarray_double = {0} double -classformat_newarray_byte = {0} byte -classformat_newarray_short = {0} short -classformat_newarray_int = {0} int -classformat_newarray_long = {0} long -classformat_store = {0}{1} -classformat_load = {0}{1} -classfileformat_anyexceptionhandler=any -classfileformat_exceptiontableentry = [pc: {0}, pc: {1}] -> {2} when : {3} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/FileMirrorLog.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/FileMirrorLog.java new file mode 100644 index 000000000..8ea5bfa04 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/FileMirrorLog.java @@ -0,0 +1,125 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.mirroring; + +import java.io.*; +import java.util.Date; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.artifact.repository.Messages; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; + +public class FileMirrorLog implements IArtifactMirrorLog { + + private static final String INDENT = "\t"; //$NON-NLS-1$ + private static final String SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$ + private BufferedWriter out; + private boolean consoleMessage = false; + private int minSeverity = IStatus.OK; + private boolean hasRoot = false; + + public FileMirrorLog(String location, int minSeverity, String root) { + this.minSeverity = minSeverity; + try { + File log = new File(location); + if (log.getParentFile().exists() || log.getParentFile().mkdirs()) { + out = new BufferedWriter(new FileWriter(log, true)); + if (root != null) { + log(root + " - " + new Date()); //$NON-NLS-1$ + hasRoot = true; + } + } else + throw new IOException(Messages.exception_unableToCreateParentDir); + } catch (IOException e) { + exceptionOccurred(null, e); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.artifact.mirror.IArtifactMirrorLog#log(org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor, org.eclipse.core.runtime.IStatus) + */ + public void log(IArtifactDescriptor descriptor, IStatus status) { + if (status.getSeverity() >= minSeverity) { + log(descriptor.toString()); + log(status, INDENT); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.artifact.mirror.IArtifactMirrorLog#log(org.eclipse.core.runtime.IStatus) + */ + public void log(IStatus status) { + log(status, ""); //$NON-NLS-1$ + } + + /* + * Write a status to the log, indenting it based on status depth. + * @param status the status to log + * @param depth the depth of the status + */ + private void log(IStatus status, String prefix) { + if (status.getSeverity() >= minSeverity) { + // Write status to log + log(prefix + status.getMessage()); + + // Write exception to log if applicable + String exceptionMessage = status.getException() != null ? status.getException().getMessage() : null; + if (exceptionMessage != null) + log(prefix + exceptionMessage); + + // Write the children of the status to the log + IStatus[] nestedStatus = status.getChildren(); + if (nestedStatus != null) + for (int i = 0; i < nestedStatus.length; i++) + log(nestedStatus[i], prefix + INDENT); + } + } + + /* + * Write a message to the log + * @param message the message to write + */ + private void log(String message) { + try { + out.write((hasRoot ? INDENT : "") + message + SEPARATOR); //$NON-NLS-1$ + } catch (IOException e) { + exceptionOccurred((hasRoot ? INDENT : "") + message, e); //$NON-NLS-1$ + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.artifact.mirror.IArtifactMirrorLog#close() + */ + public void close() { + try { + if (out != null) + out.close(); + } catch (IOException e) { + exceptionOccurred(null, e); + } + } + + /* + * Show an error message if this the first time, and print status messages. + */ + private void exceptionOccurred(String message, Exception e) { + if (!consoleMessage) { + System.err.println(Messages.MirrorLog_Exception_Occurred); + e.printStackTrace(System.err); + System.err.println(Messages.MirrorLog_Console_Log); + consoleMessage = true; + } + if (message != null) + System.out.println(message); + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/IArtifactMirrorLog.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/IArtifactMirrorLog.java new file mode 100644 index 000000000..727929df5 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/IArtifactMirrorLog.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.mirroring; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; + +public interface IArtifactMirrorLog { + + // Log a status associated with a descriptor + public void log(IArtifactDescriptor descriptor, IStatus status); + + // Log a status + public void log(IStatus status); + + // Notify that logging is completed & cleanup resources + public void close(); +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/Mirroring.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/Mirroring.java new file mode 100644 index 000000000..8d2b993ad --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/Mirroring.java @@ -0,0 +1,291 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Compeople AG (Stefan Liebig) - various ongoing maintenance + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.mirroring; + +import org.eclipse.equinox.p2.repository.tools.comparator.ArtifactComparatorFactory; +import org.eclipse.equinox.p2.repository.tools.comparator.IArtifactComparator; + +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.artifact.repository.RawMirrorRequest; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.internal.repository.tools.Activator; +import org.eclipse.equinox.p2.internal.repository.tools.Messages; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; +import org.eclipse.osgi.util.NLS; + +/** + * A utility class that performs mirroring of artifacts between repositories. + */ +public class Mirroring { + private IArtifactRepository source; + private IArtifactRepository destination; + private IArtifactRepository baseline; + private boolean raw; + private boolean compare = false; + private boolean validate = false; + private IArtifactComparator comparator; + private String comparatorID; + private List keysToMirror; + private IArtifactMirrorLog comparatorLog; + + private IArtifactComparator getComparator() { + if (comparator == null) + comparator = ArtifactComparatorFactory.getArtifactComparator(comparatorID); + return comparator; + } + + public Mirroring(IArtifactRepository source, IArtifactRepository destination, boolean raw) { + this.source = source; + this.destination = destination; + this.raw = raw; + } + + public void setCompare(boolean compare) { + this.compare = compare; + } + + public void setComparatorId(String id) { + this.comparatorID = id; + } + + public void setComparatorLog(IArtifactMirrorLog comparatorLog) { + this.comparatorLog = comparatorLog; + } + + public void setBaseline(IArtifactRepository baseline) { + this.baseline = baseline; + } + + public void setValidate(boolean validate) { + this.validate = validate; + } + + public MultiStatus run(boolean failOnError, boolean verbose) { + if (!destination.isModifiable()) + throw new IllegalStateException(NLS.bind(Messages.exception_destinationNotModifiable, destination.getLocation())); + if (compare) + getComparator(); //initialize the comparator. Only needed if we're comparing. Used to force error if comparatorID is invalid. + MultiStatus multiStatus = new MultiStatus(Activator.ID, IStatus.OK, Messages.message_mirroringStatus, null); + Iterator keys = null; + if (keysToMirror != null) + keys = keysToMirror.iterator(); + else { + IQueryResult result = source.query(ArtifactKeyQuery.ALL_KEYS, null); + keys = result.iterator(); + } + while (keys.hasNext()) { + IArtifactKey key = keys.next(); + IArtifactDescriptor[] descriptors = source.getArtifactDescriptors(key); + for (int j = 0; j < descriptors.length; j++) { + IStatus result = mirror(descriptors[j], verbose); + //Only log INFO and WARNING if we want verbose logging. Always log ERRORs + if (!result.isOK() && (verbose || result.getSeverity() == IStatus.ERROR)) + multiStatus.add(result); + //stop mirroring as soon as we have an error + if (failOnError && multiStatus.getSeverity() == IStatus.ERROR) + return multiStatus; + } + } + if (validate) { + // Simple validation of the mirror + IStatus validation = validateMirror(verbose); + if (!validation.isOK() && (verbose || validation.getSeverity() == IStatus.ERROR)) + multiStatus.add(validation); + } + return multiStatus; + } + + private IStatus mirror(IArtifactDescriptor descriptor, boolean verbose) { + IArtifactDescriptor newDescriptor = raw ? descriptor : new ArtifactDescriptor(descriptor); + + if (verbose) + System.out.println("Mirroring: " + descriptor.getArtifactKey() + " (Descriptor: " + descriptor + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + if (compare && baseline != null) + if (baseline.contains(descriptor)) { + // we have to create an output stream based on the descriptor found in the baseline otherwise all + // the properties will be copied over from the wrong descriptor and our repository will be inconsistent. + IArtifactDescriptor baselineDescriptor = getBaselineDescriptor(descriptor); + + // if we found a descriptor in the baseline then we'll use it to copy the artifact + if (baselineDescriptor != null) { + MultiStatus status = new MultiStatus(Activator.ID, IStatus.OK, NLS.bind(Messages.Mirroring_compareAndDownload, descriptor), null); + //Compare source against baseline + IStatus comparison = getComparator().compare(baseline, baselineDescriptor, source, descriptor); + if (comparatorLog != null) + comparatorLog.log(baselineDescriptor, comparison); + status.add(comparison); + if (destination.contains(baselineDescriptor)) + return compareToDestination(baselineDescriptor); + + //download artifact from baseline + status.add(downloadArtifact(baseline, baselineDescriptor, baselineDescriptor)); + return status; + } + } + + // Check if the destination already contains the file. + if (destination.contains(newDescriptor)) { + if (compare) + return compareToDestination(descriptor); + String message = NLS.bind(Messages.mirror_alreadyExists, descriptor, destination); + return new Status(IStatus.INFO, Activator.ID, ProvisionException.ARTIFACT_EXISTS, message, null); + } + + return downloadArtifact(source, newDescriptor, descriptor); + } + + /** + * Takes an IArtifactDescriptor descriptor and the ProvisionException that was thrown when destination.getOutputStream(descriptor) + * and compares descriptor to the duplicate descriptor in the destination. + * + * Callers should verify the ProvisionException was thrown due to the artifact existing in the destination before invoking this method. + * @param descriptor + * @return the status of the compare + */ + private IStatus compareToDestination(IArtifactDescriptor descriptor) { + IArtifactDescriptor[] destDescriptors = destination.getArtifactDescriptors(descriptor.getArtifactKey()); + IArtifactDescriptor destDescriptor = null; + for (int i = 0; destDescriptor == null && i < destDescriptors.length; i++) { + if (destDescriptors[i].equals(descriptor)) + destDescriptor = destDescriptors[i]; + } + if (destDescriptor == null) + return new Status(IStatus.INFO, Activator.ID, ProvisionException.ARTIFACT_EXISTS, Messages.Mirroring_noMatchingDescriptor, null); + return compare(source, descriptor, destination, destDescriptor); + } + + private IStatus compare(IArtifactRepository sourceRepository, IArtifactDescriptor sourceDescriptor, IArtifactRepository destRepository, IArtifactDescriptor destDescriptor) { + IStatus comparison = getComparator().compare(sourceRepository, sourceDescriptor, destRepository, destDescriptor); + if (comparatorLog != null) + comparatorLog.log(sourceDescriptor, comparison); + return comparison; + } + + /* + * Create, and execute a MirrorRequest for a given descriptor. + */ + private IStatus downloadArtifact(IArtifactRepository sourceRepo, IArtifactDescriptor destDescriptor, IArtifactDescriptor srcDescriptor) { + RawMirrorRequest request = new RawMirrorRequest(srcDescriptor, destDescriptor, destination); + request.setSourceRepository(sourceRepo); + + request.perform(new NullProgressMonitor()); + + return request.getResult(); + } + + public void setArtifactKeys(IArtifactKey[] keys) { + this.keysToMirror = Arrays.asList(keys); + } + + /* + * Get the equivalent descriptor from the baseline repository + */ + private IArtifactDescriptor getBaselineDescriptor(IArtifactDescriptor descriptor) { + IArtifactDescriptor[] baselineDescriptors = baseline.getArtifactDescriptors(descriptor.getArtifactKey()); + for (int i = 0; i < baselineDescriptors.length; i++) { + if (baselineDescriptors[i].equals(descriptor)) + return baselineDescriptors[i]; + } + return null; + } + + /* + * Simple validation of a mirror to see if all source descriptors are present in the destination + */ + private IStatus validateMirror(boolean verbose) { + MultiStatus status = new MultiStatus(Activator.ID, 0, Messages.Mirroring_ValidationError, null); + + // The keys that were mirrored in this session + Iterator keys = null; + if (keysToMirror != null) { + keys = keysToMirror.iterator(); + } else { + IQueryResult result = source.query(ArtifactKeyQuery.ALL_KEYS, null); + keys = result.iterator(); + } + while (keys.hasNext()) { + IArtifactKey artifactKey = keys.next(); + IArtifactDescriptor[] srcDescriptors = source.getArtifactDescriptors(artifactKey); + IArtifactDescriptor[] destDescriptors = destination.getArtifactDescriptors(artifactKey); + + Arrays.sort(srcDescriptors, new ArtifactDescriptorComparator()); + Arrays.sort(destDescriptors, new ArtifactDescriptorComparator()); + + int src = 0; + int dest = 0; + while (src < srcDescriptors.length && dest < destDescriptors.length) { + if (!destDescriptors[dest].equals(srcDescriptors[src])) { + if (destDescriptors[dest].toString().compareTo((srcDescriptors[src].toString())) > 0) { + // Missing an artifact + if (verbose) + System.out.println(NLS.bind(Messages.Mirroring_missingDescriptor, srcDescriptors[src])); + status.add(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.Mirroring_missingDescriptor, srcDescriptors[src++]))); + } else { + // Its okay if there are extra descriptors in the destination + dest++; + } + } else { + // check properties for differences + Map destMap = destDescriptors[dest].getProperties(); + Map srcProperties = null; + if (baseline != null) { + IArtifactDescriptor baselineDescriptor = getBaselineDescriptor(destDescriptors[dest]); + if (baselineDescriptor != null) + srcProperties = baselineDescriptor.getProperties(); + } + // Baseline not set, or could not find descriptor so we'll use the source descriptor + if (srcProperties == null) + srcProperties = srcDescriptors[src].getProperties(); + + // Cycle through properties of the originating descriptor & compare + for (String key : srcProperties.keySet()) { + if (!srcProperties.get(key).equals(destMap.get(key))) { + if (verbose) + System.out.println(NLS.bind(Messages.Mirroring_differentDescriptorProperty, new Object[] {destDescriptors[dest], key, srcProperties.get(key), destMap.get(key)})); + status.add(new Status(IStatus.WARNING, Activator.ID, NLS.bind(Messages.Mirroring_differentDescriptorProperty, new Object[] {destDescriptors[dest], key, srcProperties.get(key), destMap.get(key)}))); + } + } + src++; + dest++; + } + } + + // If there are still source descriptors they're missing from the destination repository + while (src < srcDescriptors.length) { + if (verbose) + System.out.println(NLS.bind(Messages.Mirroring_missingDescriptor, srcDescriptors[src])); + status.add(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.Mirroring_missingDescriptor, srcDescriptors[src++]))); + } + } + + return status; + } + + // Simple comparator for ArtifactDescriptors + protected class ArtifactDescriptorComparator implements Comparator { + + public int compare(IArtifactDescriptor arg0, IArtifactDescriptor arg1) { + if (arg0 != null && arg1 != null) + return arg0.toString().compareTo(arg1.toString()); + else if (arg1 == null && arg0 == null) + return 0; + else if (arg1 == null) + return 1; + return -1; + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/XMLMirrorLog.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/XMLMirrorLog.java new file mode 100644 index 000000000..0b488f73a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/mirroring/XMLMirrorLog.java @@ -0,0 +1,166 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.mirroring; + +import java.io.*; +import java.util.Date; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.artifact.repository.Messages; +import org.eclipse.equinox.internal.p2.persistence.XMLWriter; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; + +public class XMLMirrorLog implements IArtifactMirrorLog { + private static final String DEFAULT_FORMAT = "canonical"; //$NON-NLS-1$ + // Constants used in XML tags + private static final String LOG = "log"; //$NON-NLS-1$ + private static final String TIME_ATTRIBUTE = "time"; //$NON-NLS-1$ + private static final String DESCRIPTOR_ELEMENT = "descriptor"; //$NON-NLS-1$ + private static final String DESCRIPTOR_CLASSIFIER_ATTRIBUTE = "classifier"; //$NON-NLS-1$ + private static final String DESCRIPTOR_FORMAT_ATTRIBUTE = "format"; //$NON-NLS-1$ + private static final String DESCRIPTOR_ID_ATTRIBUTE = "id"; //$NON-NLS-1$ + private static final String DESCRIPTOR_VERSION_ATTRIBUTE = "version"; //$NON-NLS-1$ + private static final String STATUS_ELEMENT = "status"; //$NON-NLS-1$ + private static final String STATUS_SEVERITY_ATTRIBUTE = "severity"; //$NON-NLS-1$ + private static final String STATUS_MESSAGE_ATTRIBUTE = "message"; //$NON-NLS-1$ + + private int minStatus = IStatus.OK; + private XMLWriter writer; + private OutputStream outputStream; + private boolean consoleMessage = false; + + public XMLMirrorLog(String location, int minStatus, String root) { + this.minStatus = minStatus; + + try { + outputStream = new FileOutputStream(location); + writer = new XMLWriter(outputStream, null); + if (root != null) + writer.start(root.toLowerCase()); + else + writer.start(LOG); + writer.attribute(TIME_ATTRIBUTE, new Date()); + } catch (UnsupportedEncodingException e) { + exceptionOccurred(e); + } catch (FileNotFoundException e) { + exceptionOccurred(e); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.artifact.mirror.IArtifactMirrorLog#log(org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor, org.eclipse.core.runtime.IStatus) + */ + public void log(IArtifactDescriptor descriptor, IStatus status) { + if (status.getSeverity() < minStatus) + return; + // Start descriptor tag + if (writer != null) { + writer.start(DESCRIPTOR_ELEMENT); + writer.attribute(DESCRIPTOR_ID_ATTRIBUTE, descriptor.getArtifactKey().getId()); + writer.attribute(DESCRIPTOR_CLASSIFIER_ATTRIBUTE, descriptor.getArtifactKey().getClassifier()); + writer.attribute(DESCRIPTOR_VERSION_ATTRIBUTE, descriptor.getArtifactKey().getVersion()); + if (descriptor.getProperties().get(IArtifactDescriptor.FORMAT) != null) + writer.attribute(DESCRIPTOR_FORMAT_ATTRIBUTE, descriptor.getProperties().get(IArtifactDescriptor.FORMAT)); + else + writer.attribute(DESCRIPTOR_FORMAT_ATTRIBUTE, DEFAULT_FORMAT); + } else + // Creation of the XML writer failed, dump results to the console + System.out.println(descriptor); + + log(status); + + // Close descriptor tag + if (writer != null) + writer.end(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.artifact.mirror.IArtifactMirrorLog#log(org.eclipse.core.runtime.IStatus) + */ + public void log(IStatus status) { + if (status.getSeverity() < minStatus) + return; + + if (writer != null) { + // Start status tag + writer.start(STATUS_ELEMENT); + // Set severity attribute + switch (status.getSeverity()) { + case IStatus.OK : + writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "OK"); //$NON-NLS-1$ + break; + case IStatus.INFO : + writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "INFO"); //$NON-NLS-1$ + break; + case IStatus.WARNING : + writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "WARNING"); //$NON-NLS-1$ + break; + case IStatus.ERROR : + writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "ERROR"); //$NON-NLS-1$ + break; + case IStatus.CANCEL : + writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "CANCEL"); //$NON-NLS-1$ + break; + default : + writer.attribute(STATUS_SEVERITY_ATTRIBUTE, status.getSeverity()); + } + // Set message attribute + writer.attribute(STATUS_MESSAGE_ATTRIBUTE, status.getMessage()); + } else + // Creation of the XML writer failed, dump results to the console + System.out.println(status); + + // Log children statuses + IStatus[] nestedStatus = status.getChildren(); + if (nestedStatus != null) + for (int i = 0; i < nestedStatus.length; i++) + log(nestedStatus[i]); + + // Close status tag + if (writer != null) + writer.end(); + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.artifact.mirror.IArtifactMirrorLog#close() + */ + public void close() { + try { + if (writer != null) { + // Close opening tag & flush results + writer.end(); + writer.flush(); + } + } finally { + if (outputStream != null) + try { + // Close output stream + outputStream.close(); + } catch (IOException e) { + exceptionOccurred(e); + } + } + } + + /* + * Show an error message if this the first time + */ + private void exceptionOccurred(Exception e) { + if (!consoleMessage) { + System.err.println(Messages.MirrorLog_Exception_Occurred); + e.printStackTrace(System.err); + System.err.println(Messages.MirrorLog_Console_Log); + consoleMessage = true; + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/AbstractApplication.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/AbstractApplication.java index 0181e06d1..c1d1bb18c 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/AbstractApplication.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/AbstractApplication.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. + * Copyright (c) 2009, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -15,24 +15,29 @@ import java.util.*; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.artifact.repository.CompositeArtifactRepository; +import org.eclipse.equinox.internal.p2.artifact.repository.CompositeArtifactRepositoryFactory; +import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.metadata.repository.CompositeMetadataRepository; +import org.eclipse.equinox.internal.p2.metadata.repository.CompositeMetadataRepositoryFactory; import org.eclipse.equinox.internal.p2.repository.helpers.RepositoryHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.*; +import org.eclipse.equinox.p2.core.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.*; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.util.NLS; +import org.osgi.framework.ServiceReference; public abstract class AbstractApplication { protected boolean removeAddedRepositories = true; - protected List sourceRepositories = new ArrayList(); //List of repository descriptors - protected List artifactReposToRemove = new ArrayList(); - protected List metadataReposToRemove = new ArrayList(); - protected List sourceIUs = new ArrayList(); - private List destinationRepos = new ArrayList(); + protected List sourceRepositories = new ArrayList(); //List of repository descriptors + protected List artifactReposToRemove = new ArrayList(); + protected List metadataReposToRemove = new ArrayList(); + protected List sourceIUs = new ArrayList(); + private List destinationRepos = new ArrayList(); protected IArtifactRepository destinationArtifactRepository = null; protected IMetadataRepository destinationMetadataRepository = null; @@ -40,18 +45,50 @@ public abstract class AbstractApplication { private CompositeMetadataRepository compositeMetadataRepository = null; private CompositeArtifactRepository compositeArtifactRepository = null; - public void setSourceIUs(List ius) { + protected IProvisioningAgent agent; + + public AbstractApplication() { + super(); + try { + setupAgent(); + } catch (ProvisionException e) { + LogHelper.log(e); + } + } + + private void setupAgent() throws ProvisionException { + //note if we ever wanted these applications to act on a different agent than + //the currently running system we would need to set it here + ServiceReference agentRef = Activator.getBundleContext().getServiceReference(IProvisioningAgent.SERVICE_NAME); + if (agentRef != null) { + agent = (IProvisioningAgent) Activator.getBundleContext().getService(agentRef); + if (agent != null) + return; + } + //there is no agent around so we need to create one + ServiceReference providerRef = Activator.getBundleContext().getServiceReference(IProvisioningAgentProvider.SERVICE_NAME); + if (providerRef == null) + throw new RuntimeException("No provisioning agent provider is available"); //$NON-NLS-1$ + IProvisioningAgentProvider provider = (IProvisioningAgentProvider) Activator.getBundleContext().getService(providerRef); + if (provider == null) + throw new RuntimeException("No provisioning agent provider is available"); //$NON-NLS-1$ + //obtain agent for currently running system + agent = provider.createAgent(null); + Activator.getBundleContext().ungetService(providerRef); + } + + public void setSourceIUs(List ius) { sourceIUs = ius; } - protected void finalizeRepositories() throws ProvisionException { + protected void finalizeRepositories() { if (removeAddedRepositories) { - IArtifactRepositoryManager artifactRepositoryManager = Activator.getArtifactRepositoryManager(); - for (Iterator iter = artifactReposToRemove.iterator(); iter.hasNext();) - artifactRepositoryManager.removeRepository((URI) iter.next()); - IMetadataRepositoryManager metadataRepositoryManager = Activator.getMetadataRepositoryManager(); - for (Iterator iter = metadataReposToRemove.iterator(); iter.hasNext();) - metadataRepositoryManager.removeRepository((URI) iter.next()); + IArtifactRepositoryManager artifactRepositoryManager = getArtifactRepositoryManager(); + for (URI uri : artifactReposToRemove) + artifactRepositoryManager.removeRepository(uri); + IMetadataRepositoryManager metadataRepositoryManager = getMetadataRepositoryManager(); + for (URI uri : metadataReposToRemove) + metadataRepositoryManager.removeRepository(uri); } metadataReposToRemove = null; artifactReposToRemove = null; @@ -61,13 +98,20 @@ public abstract class AbstractApplication { destinationMetadataRepository = null; } + protected IMetadataRepositoryManager getMetadataRepositoryManager() { + return (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME); + } + + protected IArtifactRepositoryManager getArtifactRepositoryManager() { + return (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME); + } + public void initializeRepos(IProgressMonitor progress) throws ProvisionException { - IArtifactRepositoryManager artifactRepositoryManager = Activator.getArtifactRepositoryManager(); - IMetadataRepositoryManager metadataRepositoryManager = Activator.getMetadataRepositoryManager(); + IArtifactRepositoryManager artifactRepositoryManager = getArtifactRepositoryManager(); + IMetadataRepositoryManager metadataRepositoryManager = getMetadataRepositoryManager(); URI curLocation = null; try { - for (Iterator iter = sourceRepositories.iterator(); iter.hasNext();) { - RepositoryDescriptor repo = (RepositoryDescriptor) iter.next(); + for (RepositoryDescriptor repo : sourceRepositories) { curLocation = repo.getRepoLocation(); if (repo.isBoth()) { addRepository(artifactRepositoryManager, curLocation, 0, progress); @@ -106,9 +150,9 @@ public abstract class AbstractApplication { RepositoryDescriptor artifactRepoDescriptor = null; RepositoryDescriptor metadataRepoDescriptor = null; - Iterator iter = destinationRepos.iterator(); + Iterator iter = destinationRepos.iterator(); while (iter.hasNext() && (artifactRepoDescriptor == null || metadataRepoDescriptor == null)) { - RepositoryDescriptor repo = (RepositoryDescriptor) iter.next(); + RepositoryDescriptor repo = iter.next(); if (repo.isArtifact() && artifactRepoDescriptor == null) artifactRepoDescriptor = repo; if (repo.isMetadata() && metadataRepoDescriptor == null) @@ -188,12 +232,12 @@ public abstract class AbstractApplication { } } - protected boolean initDestinationRepository(IRepository repository, RepositoryDescriptor descriptor) { + protected boolean initDestinationRepository(IRepository repository, RepositoryDescriptor descriptor) { if (repository != null && repository.isModifiable()) { if (descriptor.getName() != null) repository.setName(descriptor.getName()); - if (repository instanceof ICompositeRepository && !descriptor.isAppend()) - ((ICompositeRepository) repository).removeAllChildren(); + if (repository instanceof ICompositeRepository && !descriptor.isAppend()) + ((ICompositeRepository) repository).removeAllChildren(); else if (repository instanceof IMetadataRepository && !descriptor.isAppend()) ((IMetadataRepository) repository).removeAll(); else if (repository instanceof IArtifactRepository && !descriptor.isAppend()) @@ -206,12 +250,13 @@ public abstract class AbstractApplication { public IMetadataRepository getCompositeMetadataRepository() { if (compositeMetadataRepository == null) { try { - compositeMetadataRepository = new CompositeMetadataRepository(new URI("memory:/composite"), "parent metadata repo", null);//$NON-NLS-1$ //$NON-NLS-2$ + CompositeMetadataRepositoryFactory factory = new CompositeMetadataRepositoryFactory(); + factory.setAgent(agent); + compositeMetadataRepository = (CompositeMetadataRepository) factory.create(new URI("memory:/composite"), "parent metadata repo", CompositeMetadataRepository.REPOSITORY_TYPE, null);//$NON-NLS-1$ //$NON-NLS-2$ } catch (URISyntaxException e) { //Can't happen } - for (Iterator iter = sourceRepositories.iterator(); iter.hasNext();) { - RepositoryDescriptor repo = (RepositoryDescriptor) iter.next(); + for (RepositoryDescriptor repo : sourceRepositories) { if (repo.isMetadata()) compositeMetadataRepository.addChild(repo.getRepoLocation()); } @@ -222,12 +267,13 @@ public abstract class AbstractApplication { public IArtifactRepository getCompositeArtifactRepository() { if (compositeArtifactRepository == null) { try { - compositeArtifactRepository = new CompositeArtifactRepository(new URI("memory:/composite"), "parent artifact repo", null);//$NON-NLS-1$ //$NON-NLS-2$ + CompositeArtifactRepositoryFactory factory = new CompositeArtifactRepositoryFactory(); + factory.setAgent(agent); + compositeArtifactRepository = (CompositeArtifactRepository) factory.create(new URI("memory:/composite"), "parent artifact repo", CompositeArtifactRepository.REPOSITORY_TYPE, null);//$NON-NLS-1$ //$NON-NLS-2$ } catch (URISyntaxException e) { //Can't happen } - for (Iterator iter = sourceRepositories.iterator(); iter.hasNext();) { - RepositoryDescriptor repo = (RepositoryDescriptor) iter.next(); + for (RepositoryDescriptor repo : sourceRepositories) { if (repo.isArtifact()) compositeArtifactRepository.addChild(repo.getRepoLocation()); } diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Activator.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Activator.java index 5c101ea89..b79dc8ce4 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Activator.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Activator.java @@ -10,15 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.internal.repository.tools; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.net.URI; import java.net.URISyntaxException; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.util.NLS; import org.osgi.framework.*; import org.osgi.service.packageadmin.PackageAdmin; @@ -74,7 +75,7 @@ public class Activator implements BundleActivator { * Return the artifact repository manager. Throw an exception if it cannot be obtained. */ public static IArtifactRepositoryManager getArtifactRepositoryManager() throws ProvisionException { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(getBundleContext(), IArtifactRepositoryManager.class.getName()); + IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(getBundleContext(), IArtifactRepositoryManager.SERVICE_NAME); if (manager == null) throw new ProvisionException(Messages.no_artifactRepo_manager); return manager; @@ -84,7 +85,7 @@ public class Activator implements BundleActivator { * Return the profile registry. Throw an exception if it cannot be found. */ static IProfileRegistry getProfileRegistry() throws ProvisionException { - IProfileRegistry registry = (IProfileRegistry) ServiceHelper.getService(getBundleContext(), IProfileRegistry.class.getName()); + IProfileRegistry registry = (IProfileRegistry) ServiceHelper.getService(getBundleContext(), IProfileRegistry.SERVICE_NAME); if (registry == null) throw new ProvisionException(Messages.no_profile_registry); return registry; @@ -112,7 +113,7 @@ public class Activator implements BundleActivator { * Return the metadata repository manager. Throw an exception if it cannot be obtained. */ public static IMetadataRepositoryManager getMetadataRepositoryManager() throws ProvisionException { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(getBundleContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(getBundleContext(), IMetadataRepositoryManager.SERVICE_NAME); if (manager == null) throw new ProvisionException(Messages.no_metadataRepo_manager); return manager; diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/ArtifactRepositoryValidator.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/ArtifactRepositoryValidator.java new file mode 100644 index 000000000..3748fc12f --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/ArtifactRepositoryValidator.java @@ -0,0 +1,85 @@ +package org.eclipse.equinox.p2.internal.repository.tools; + +import org.eclipse.equinox.p2.repository.tools.comparator.ArtifactComparatorFactory; +import org.eclipse.equinox.p2.repository.tools.comparator.IArtifactComparator; + +import java.util.Iterator; +import java.util.List; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.artifact.repository.CompositeArtifactRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.*; + +public class ArtifactRepositoryValidator { + + private IArtifactComparator comparator; + + public ArtifactRepositoryValidator(String comparatorId) throws ProvisionException { + comparator = ArtifactComparatorFactory.getArtifactComparator(comparatorId); + if (comparatorId == null) + throw new ProvisionException(Messages.invalidComparatorId); + + } + + public IStatus validateRepository(IArtifactRepository repository) { + if (repository instanceof CompositeArtifactRepository) + return validateComposite((CompositeArtifactRepository) repository); + + IQueryResult queryResult = repository.query(ArtifactKeyQuery.ALL_KEYS, new NullProgressMonitor()); + for (Iterator iterator = queryResult.iterator(); iterator.hasNext();) { + IArtifactDescriptor[] descriptors = repository.getArtifactDescriptors(iterator.next()); + for (int i = 0; i < descriptors.length - 2; i++) { + IStatus compareResult = comparator.compare(repository, descriptors[i], repository, descriptors[i + 1]); + if (!compareResult.isOK()) { + return compareResult; + } + } + } + return Status.OK_STATUS; + } + + public IStatus validateComposite(CompositeArtifactRepository repository) { + List repos = repository.getLoadedChildren(); + IQueryResult queryResult = repository.query(ArtifactKeyQuery.ALL_KEYS, new NullProgressMonitor()); + for (Iterator iterator = queryResult.iterator(); iterator.hasNext();) { + IArtifactKey key = iterator.next(); + IArtifactRepository firstRepo = null; + for (IArtifactRepository child : repos) { + if (child.contains(key)) { + if (firstRepo == null) { + firstRepo = child; + continue; + } + + IArtifactDescriptor[] d1 = firstRepo.getArtifactDescriptors(key); + IArtifactDescriptor[] d2 = child.getArtifactDescriptors(key); + //If we assume each repo is internally consistant, we only need to compare one descriptor from each repo + IStatus compareResult = comparator.compare(firstRepo, d1[0], child, d2[0]); + if (!compareResult.isOK()) { + //LogHelper.log(compareResult); + return compareResult; + } + } + } + } + return Status.OK_STATUS; + } + + public IStatus validateComposite(CompositeArtifactRepository composite, IArtifactRepository repository) { + IQueryResult queryResult = repository.query(ArtifactKeyQuery.ALL_KEYS, new NullProgressMonitor()); + for (Iterator iterator = queryResult.iterator(); iterator.hasNext();) { + IArtifactKey key = iterator.next(); + if (composite.contains(key)) { + IArtifactDescriptor[] d1 = composite.getArtifactDescriptors(key); + IArtifactDescriptor[] d2 = repository.getArtifactDescriptors(key); + //If we assume each repo is internally consistant, we only need to compare one descriptor from each repo + IStatus compareResult = comparator.compare(composite, d1[0], repository, d2[0]); + if (!compareResult.isOK()) + return compareResult; + } + } + return Status.OK_STATUS; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/CompositeRepositoryApplication.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/CompositeRepositoryApplication.java index 11f73dee6..96de1e39d 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/CompositeRepositoryApplication.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/CompositeRepositoryApplication.java @@ -11,22 +11,25 @@ package org.eclipse.equinox.p2.internal.repository.tools; import java.net.MalformedURLException; -import java.util.*; +import java.util.ArrayList; +import java.util.List; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.artifact.repository.CompositeArtifactRepository; import org.eclipse.equinox.internal.p2.repository.helpers.RepositoryHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.ICompositeRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.ICompositeRepository; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.util.NLS; public class CompositeRepositoryApplication extends AbstractApplication { - private List childrenToAdd = new ArrayList(); - private List childrenToRemove = new ArrayList(); + private List childrenToAdd = new ArrayList(); + private List childrenToRemove = new ArrayList(); + private boolean removeAllChildren = false; private boolean failOnExists = false; private String comparatorID = null; @@ -34,30 +37,36 @@ public class CompositeRepositoryApplication extends AbstractApplication { try { initializeRepos(new NullProgressMonitor()); // load repository - ICompositeRepository metadataRepo = (ICompositeRepository) destinationMetadataRepository; + ICompositeRepository metadataRepo = (ICompositeRepository) destinationMetadataRepository; CompositeArtifactRepository artifactRepo = (CompositeArtifactRepository) destinationArtifactRepository; - // Remove children from the Composite Repositories - for (Iterator iterator = childrenToRemove.iterator(); iterator.hasNext();) { - RepositoryDescriptor child = (RepositoryDescriptor) iterator.next(); - if (child.isArtifact() && artifactRepo != null) - artifactRepo.removeChild(child.getOriginalRepoLocation()); - if (child.isMetadata() && metadataRepo != null) - metadataRepo.removeChild(child.getOriginalRepoLocation()); + if (removeAllChildren) { + if (artifactRepo != null) + artifactRepo.removeAllChildren(); + if (metadataRepo != null) + metadataRepo.removeAllChildren(); + } else { + // Remove children from the Composite Repositories + for (RepositoryDescriptor child : childrenToRemove) { + if (child.isArtifact() && artifactRepo != null) + artifactRepo.removeChild(child.getOriginalRepoLocation()); + if (child.isMetadata() && metadataRepo != null) + metadataRepo.removeChild(child.getOriginalRepoLocation()); + } } // Add children to the Composite Repositories - for (Iterator iterator = childrenToAdd.iterator(); iterator.hasNext();) { - RepositoryDescriptor child = (RepositoryDescriptor) iterator.next(); + for (RepositoryDescriptor child : childrenToAdd) { if (child.isArtifact() && artifactRepo != null) artifactRepo.addChild(child.getOriginalRepoLocation()); if (child.isMetadata() && metadataRepo != null) metadataRepo.addChild(child.getOriginalRepoLocation()); } - if (comparatorID != null) - if (!artifactRepo.validate(comparatorID)) - return new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.CompositeRepositoryApplication_failedComparator, comparatorID)); + if (comparatorID != null) { + ArtifactRepositoryValidator validator = new ArtifactRepositoryValidator(comparatorID); + return validator.validateComposite(artifactRepo); + } return Status.OK_STATUS; } finally { finalizeRepositories(); @@ -72,6 +81,10 @@ public class CompositeRepositoryApplication extends AbstractApplication { childrenToRemove.add(child); } + public void setRemoveAll(boolean all) { + removeAllChildren = all; + } + public void setFailOnExists(boolean value) { failOnExists = value; } @@ -155,8 +168,8 @@ public class CompositeRepositoryApplication extends AbstractApplication { /* * Determine if the repository is valid for this operation */ - private boolean validRepositoryLocation(IRepository repository) throws ProvisionException { - if (repository instanceof ICompositeRepository) { + private boolean validRepositoryLocation(IRepository repository) throws ProvisionException { + if (repository instanceof ICompositeRepository) { // if we have an already existing repository at that location, then throw an error // if the user told us to if (failOnExists) @@ -171,7 +184,7 @@ public class CompositeRepositoryApplication extends AbstractApplication { /* * Initialize a new repository */ - private void initRepository(IRepository repository, RepositoryDescriptor desc) { + private void initRepository(IRepository repository, RepositoryDescriptor desc) { RepositoryHelper.validDestinationRepository(repository); if (desc.isCompressed() && !repository.getProperties().containsKey(IRepository.PROP_COMPRESSED)) repository.setProperty(IRepository.PROP_COMPRESSED, String.valueOf(true)); diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Messages.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Messages.java index 1f4b3c69c..37a7c5d12 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Messages.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Messages.java @@ -18,9 +18,11 @@ public class Messages extends NLS { public static String exception_unableToRemoveRepo; public static String exception_notLocalFileRepo; public static String exception_noEngineService; + public static String exception_noPlannerService; public static String exception_needIUsOrNonEmptyRepo; public static String exception_needDestinationRepo; public static String exception_onlyOneComparator; + public static String exception_loadingRepository; public static String AbstractApplication_no_valid_destinations; @@ -40,11 +42,8 @@ public class Messages extends NLS { public static String MirrorApplication_artifactDestinationNoSource; public static String MirrorApplication_metadataDestinationNoSource; - public static String MirrorApplication_missingIU; - public static String MirrorApplication_missingSourceForIUs; public static String MirrorApplication_no_IUs; public static String MirrorApplication_set_source_repositories; - public static String MirrorApplication_validateAndMirrorProblems; public static String ProcessRepo_location_not_url; public static String ProcessRepo_must_be_local; @@ -58,6 +57,19 @@ public class Messages extends NLS { public static String skippingInvalidFilter; + public static String message_mirroringStatus; + public static String Mirroring_compareAndDownload; + public static String mirror_alreadyExists; + public static String Mirroring_noMatchingDescriptor; + public static String Mirroring_ValidationError; + public static String Mirroring_missingDescriptor; + public static String Mirroring_differentDescriptorProperty; + + public static String invalidComparatorId; + public static String info_noMD5Infomation; + public static String info_noMD5InRepository; + public static String warning_differentMD5; + static { // initialize resource bundles NLS.initializeMessages(BUNDLE_NAME, Messages.class); diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/MirrorApplication.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/MirrorApplication.java index e73283eed..574abd9bc 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/MirrorApplication.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/MirrorApplication.java @@ -10,30 +10,33 @@ *******************************************************************************/ package org.eclipse.equinox.p2.internal.repository.tools; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.io.File; import java.net.URI; -import java.util.ArrayList; -import java.util.Iterator; +import java.net.URISyntaxException; +import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; -import org.eclipse.equinox.internal.p2.artifact.mirror.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.director.PermissiveSlicer; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.LatestIUVersionQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; - -public class MirrorApplication extends AbstractApplication { +import org.eclipse.equinox.internal.p2.metadata.query.LatestIUVersionQuery; +import org.eclipse.equinox.internal.p2.repository.helpers.RepositoryHelper; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.internal.repository.mirroring.*; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.osgi.util.NLS; + +public class MirrorApplication extends AbstractApplication implements IApplication, IExecutableExtension { private static final String LOG_ROOT = "p2.mirror"; //$NON-NLS-1$ + private static final String MIRROR_MODE = "metadataOrArtifacts"; //$NON-NLS-1$ protected SlicingOptions slicingOptions = new SlicingOptions(); @@ -44,17 +47,132 @@ public class MirrorApplication extends AbstractApplication { private boolean raw = true; private boolean verbose = false; private boolean validate = false; + private String metadataOrArtifacts = null; + private String[] rootIUs = null; private File mirrorLogFile; // file to log mirror output to (optional) private File comparatorLogFile; // file to comparator output to (optional) private IArtifactMirrorLog mirrorLog; private IArtifactMirrorLog comparatorLog; + /** + * Convert a list of tokens into an array. The list separator has to be + * specified. + */ + public static String[] getArrayArgsFromString(String list, String separator) { + if (list == null || list.trim().equals("")) //$NON-NLS-1$ + return new String[0]; + List result = new ArrayList(); + for (StringTokenizer tokens = new StringTokenizer(list, separator); tokens.hasMoreTokens();) { + String token = tokens.nextToken().trim(); + if (!token.equals("")) { //$NON-NLS-1$ + if ((token.indexOf('[') >= 0 || token.indexOf('(') >= 0) && tokens.hasMoreTokens()) + result.add(token + separator + tokens.nextToken()); + else + result.add(token); + } + } + return result.toArray(new String[result.size()]); + } + public Object start(IApplicationContext context) throws Exception { + Map args = context.getArguments(); + initializeFromArguments((String[]) args.get(IApplicationContext.APPLICATION_ARGS)); run(null); return IApplication.EXIT_OK; } + public void stop() { + // TODO Auto-generated method stub + + } + + /* + * The old "org.eclipse.equinox.p2.artifact.repository.mirrorApplication" application only does artifacts + * Similary, "org.eclipse.equinox.p2.metadata.repository.mirrorApplication" only does metadata + */ + public void setInitializationData(IConfigurationElement config, String propertyName, Object data) { + if (data instanceof Map && ((Map) data).containsKey(MIRROR_MODE)) { + metadataOrArtifacts = (String) ((Map) data).get(MIRROR_MODE); + } + } + + public void initializeFromArguments(String[] args) throws Exception { + if (args == null) + return; + + File comparatorLogLocation = null; + File mirrorLogLocation = null; + + RepositoryDescriptor destination = new RepositoryDescriptor(); + RepositoryDescriptor sourceRepo = new RepositoryDescriptor(); + if (metadataOrArtifacts != null) { + destination.setKind(metadataOrArtifacts); + sourceRepo.setKind(metadataOrArtifacts); + } + + addDestination(destination); + addSource(sourceRepo); + + for (int i = 0; i < args.length; i++) { + // check for args without parameters (i.e., a flag arg) + if (args[i].equalsIgnoreCase("-raw")) //$NON-NLS-1$ + raw = true; + else if (args[i].equalsIgnoreCase("-ignoreErrors")) //$NON-NLS-1$ + failOnError = false; + else if (args[i].equalsIgnoreCase("-verbose")) //$NON-NLS-1$ + verbose = true; + else if (args[i].equalsIgnoreCase("-compare")) //$NON-NLS-1$ + compare = true; + else if (args[i].equalsIgnoreCase("-validate")) //$NON-NLS-1$ + validate = true; + + // check for args with parameters. If we are at the last argument or + // if the next one has a '-' as the first character, then we can't have + // an arg with a param so continue. + if (i == args.length - 1 || args[i + 1].startsWith("-")) //$NON-NLS-1$ + continue; + + String arg = args[++i]; + + if (args[i - 1].equalsIgnoreCase("-comparator")) //$NON-NLS-1$ + comparatorID = arg; + else if (args[i - 1].equalsIgnoreCase("-comparatorLog")) //$NON-NLS-1$ + comparatorLogLocation = new File(arg); + else if (args[i - 1].equalsIgnoreCase("-destinationName")) //$NON-NLS-1$ + destination.setName(arg); + else if (args[i - 1].equalsIgnoreCase("-writeMode")) { //$NON-NLS-1$ + if (args[i].equalsIgnoreCase("clean")) //$NON-NLS-1$ + destination.setAppend(false); + } else if (args[i - 1].equalsIgnoreCase("-log")) { //$NON-NLS-1$ + mirrorLogLocation = new File(arg); + } else if (args[i - 1].equalsIgnoreCase("-roots")) { //$NON-NLS-1$ + rootIUs = getArrayArgsFromString(arg, ","); //$NON-NLS-1$ + } else { + try { + if (args[i - 1].equalsIgnoreCase("-source")) { //$NON-NLS-1$ + URI uri = RepositoryHelper.localRepoURIHelper(URIUtil.fromString(arg)); + sourceRepo.setLocation(uri); + destination.setFormat(uri); + } else if (args[i - 1].equalsIgnoreCase("-destination")) //$NON-NLS-1$ + destination.setLocation(RepositoryHelper.localRepoURIHelper(URIUtil.fromString(arg))); + else if (args[i - 1].equalsIgnoreCase("-compareAgainst")) { //$NON-NLS-1$ + baseline = RepositoryHelper.localRepoURIHelper(URIUtil.fromString(arg)); + compare = true; + } + } catch (URISyntaxException e) { + throw new IllegalArgumentException(NLS.bind(Messages.ProcessRepo_location_not_url, arg)); + } + } + } + + // Create logs + if (mirrorLogLocation != null) + mirrorLog = getLog(mirrorLogLocation, "p2.artifact.mirror"); //$NON-NLS-1$ + if (comparatorLogLocation != null && comparatorID != null) + comparatorLog = getLog(comparatorLogLocation, comparatorID); + } + public IStatus run(IProgressMonitor monitor) throws ProvisionException { IStatus mirrorStatus = Status.OK_STATUS; try { @@ -62,7 +180,7 @@ public class MirrorApplication extends AbstractApplication { initializeLogs(); validate(); initializeIUs(); - IQueryable slice = slice(new NullProgressMonitor()); + IQueryable slice = slice(new NullProgressMonitor()); if (destinationArtifactRepository != null) { mirrorStatus = mirrorArtifacts(slice, new NullProgressMonitor()); if (mirrorStatus.getSeverity() == IStatus.ERROR) @@ -79,19 +197,16 @@ public class MirrorApplication extends AbstractApplication { return mirrorStatus; } - private IStatus mirrorArtifacts(IQueryable slice, IProgressMonitor monitor) throws ProvisionException { + private IStatus mirrorArtifacts(IQueryable slice, IProgressMonitor monitor) throws ProvisionException { // Obtain ArtifactKeys from IUs - Collector ius = slice.query(InstallableUnitQuery.ANY, new Collector(), monitor); - ArrayList keys = new ArrayList(ius.size()); - for (Iterator iterator = ius.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); - IArtifactKey[] iuKeys = iu.getArtifacts(); - for (int i = 0; i < iuKeys.length; i++) { - keys.add(iuKeys[i]); - } + IQueryResult ius = slice.query(InstallableUnitQuery.ANY, monitor); + ArrayList keys = new ArrayList(); + for (Iterator iterator = ius.iterator(); iterator.hasNext();) { + IInstallableUnit iu = iterator.next(); + keys.addAll(iu.getArtifacts()); } - Mirroring mirror = new Mirroring(getCompositeArtifactRepository(), destinationArtifactRepository, raw); + Mirroring mirror = new Mirroring(getCompositeArtifactRepository(), destinationArtifactRepository, raw); mirror.setCompare(compare); mirror.setComparatorId(comparatorID); mirror.setBaseline(initializeBaseline()); @@ -99,7 +214,7 @@ public class MirrorApplication extends AbstractApplication { // If IUs have been specified then only they should be mirrored, otherwise mirror everything. if (keys.size() > 0) - mirror.setArtifactKeys((IArtifactKey[]) keys.toArray(new IArtifactKey[keys.size()])); + mirror.setArtifactKeys(keys.toArray(new IArtifactKey[keys.size()])); if (comparatorLog != null) mirror.setComparatorLog(comparatorLog); @@ -116,12 +231,12 @@ public class MirrorApplication extends AbstractApplication { private IArtifactRepository initializeBaseline() throws ProvisionException { if (baseline == null) return null; - return addRepository(Activator.getArtifactRepositoryManager(), baseline, 0, null); + return addRepository(getArtifactRepositoryManager(), baseline, 0, null); } - private void mirrorMetadata(IQueryable slice, IProgressMonitor monitor) { - Collector allIUs = slice.query(InstallableUnitQuery.ANY, new Collector(), monitor); - destinationMetadataRepository.addInstallableUnits((IInstallableUnit[]) allIUs.toArray(IInstallableUnit.class)); + private void mirrorMetadata(IQueryable slice, IProgressMonitor monitor) { + IQueryResult allIUs = slice.query(InstallableUnitQuery.ANY, monitor); + destinationMetadataRepository.addInstallableUnits(allIUs.toArray(IInstallableUnit.class)); } /* @@ -143,17 +258,24 @@ public class MirrorApplication extends AbstractApplication { * If no IUs have been specified we want to mirror them all */ private void initializeIUs() throws ProvisionException { - if (sourceIUs == null || sourceIUs.isEmpty()) { - sourceIUs = new ArrayList(); - IMetadataRepository metadataRepo = getCompositeMetadataRepository(); - Collector collector = metadataRepo.query(InstallableUnitQuery.ANY, new Collector(), null); - - for (Iterator iter = collector.iterator(); iter.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iter.next(); - sourceIUs.add(iu); + IMetadataRepository metadataRepo = getCompositeMetadataRepository(); + + if (rootIUs != null) { + sourceIUs = new ArrayList(); + for (int i = 0; i < rootIUs.length; i++) { + String[] segments = getArrayArgsFromString(rootIUs[i], "/"); //$NON-NLS-1$ + VersionRange range = segments.length > 1 ? new VersionRange(segments[i]) : null; + Iterator queryResult = metadataRepo.query(new InstallableUnitQuery(segments[i], range), null).iterator(); + while (queryResult.hasNext()) + sourceIUs.add(queryResult.next()); } - - if (collector.size() == 0 && destinationMetadataRepository != null) + } else if (sourceIUs == null || sourceIUs.isEmpty()) { + sourceIUs = new ArrayList(); + Iterator queryResult = metadataRepo.query(InstallableUnitQuery.ANY, null).iterator(); + while (queryResult.hasNext()) + sourceIUs.add(queryResult.next()); + /* old metadata mirroring app did not throw an exception here */ + if (sourceIUs.size() == 0 && destinationMetadataRepository != null && metadataOrArtifacts == null) throw new ProvisionException(Messages.MirrorApplication_no_IUs); } } @@ -188,16 +310,15 @@ public class MirrorApplication extends AbstractApplication { return new FileMirrorLog(absolutePath, 0, root); } - private IQueryable slice(IProgressMonitor monitor) throws ProvisionException { + private IQueryable slice(IProgressMonitor monitor) throws ProvisionException { if (slicingOptions == null) slicingOptions = new SlicingOptions(); PermissiveSlicer slicer = new PermissiveSlicer(getCompositeMetadataRepository(), slicingOptions.getFilter(), slicingOptions.includeOptionalDependencies(), slicingOptions.isEverythingGreedy(), slicingOptions.forceFilterTo(), slicingOptions.considerStrictDependencyOnly(), slicingOptions.followOnlyFilteredRequirements()); - IQueryable slice = slicer.slice((IInstallableUnit[]) sourceIUs.toArray(new IInstallableUnit[sourceIUs.size()]), monitor); + IQueryable slice = slicer.slice(sourceIUs.toArray(new IInstallableUnit[sourceIUs.size()]), monitor); if (slice != null && slicingOptions.latestVersionOnly()) { - Collector collector = new Collector(); - collector = slice.query(new LatestIUVersionQuery(), collector, monitor); - slice = collector; + IQueryResult queryResult = slice.query(new LatestIUVersionQuery(), monitor); + slice = queryResult; } if (slicer.getStatus().getSeverity() != IStatus.OK && mirrorLog != null) { mirrorLog.log(slicer.getStatus()); diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/RecreateRepositoryApplication.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/RecreateRepositoryApplication.java index adb7535d3..adaa79af6 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/RecreateRepositoryApplication.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/RecreateRepositoryApplication.java @@ -17,31 +17,32 @@ import java.net.URI; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; import org.eclipse.osgi.util.NLS; -public class RecreateRepositoryApplication { +public class RecreateRepositoryApplication extends AbstractApplication { static final private String PUBLISH_PACK_FILES_AS_SIBLINGS = "publishPackFilesAsSiblings"; //$NON-NLS-1$ private RepositoryDescriptor descriptor; private String repoName = null; boolean removeArtifactRepo = true; - private Map repoProperties = null; - private Map repoMap = null; - - public IStatus run(IProgressMonitor monitor) throws ProvisionException, IOException { + private Map repoProperties = null; + private Map repoMap = null; + public IStatus run(IProgressMonitor monitor) throws ProvisionException { try { IArtifactRepository repository = initialize(monitor); removeRepository(repository, monitor); recreateRepository(monitor); } finally { if (removeArtifactRepo) { - IArtifactRepositoryManager repositoryManager = Activator.getArtifactRepositoryManager(); + IArtifactRepositoryManager repositoryManager = getArtifactRepositoryManager(); repositoryManager.removeRepository(descriptor.getRepoLocation()); } } @@ -54,7 +55,7 @@ public class RecreateRepositoryApplication { } private IArtifactRepository initialize(IProgressMonitor monitor) throws ProvisionException { - IArtifactRepositoryManager repositoryManager = Activator.getArtifactRepositoryManager(); + IArtifactRepositoryManager repositoryManager = getArtifactRepositoryManager(); removeArtifactRepo = !repositoryManager.contains(descriptor.getRepoLocation()); IArtifactRepository repository = repositoryManager.loadRepository(descriptor.getRepoLocation(), IRepositoryManager.REPOSITORY_HINT_MODIFIABLE, monitor); @@ -67,46 +68,49 @@ public class RecreateRepositoryApplication { repoName = repository.getName(); repoProperties = repository.getProperties(); - repoMap = new HashMap(); - IArtifactKey[] keys = repository.getArtifactKeys(); - for (int i = 0; i < keys.length; i++) { - IArtifactDescriptor[] descriptors = repository.getArtifactDescriptors(keys[i]); - repoMap.put(keys[i], descriptors); + repoMap = new HashMap(); + IQueryResult keys = repository.query(ArtifactKeyQuery.ALL_KEYS, null); + for (Iterator iterator = keys.iterator(); iterator.hasNext();) { + IArtifactKey key = iterator.next(); + IArtifactDescriptor[] descriptors = repository.getArtifactDescriptors(key); + repoMap.put(key, descriptors); } return repository; } - private void removeRepository(IArtifactRepository repository, IProgressMonitor monitor) throws ProvisionException, IOException { - IArtifactRepositoryManager manager = Activator.getArtifactRepositoryManager(); + private void removeRepository(IArtifactRepository repository, IProgressMonitor monitor) throws ProvisionException { + IArtifactRepositoryManager manager = getArtifactRepositoryManager(); manager.removeRepository(repository.getLocation()); - boolean compressed = Boolean.valueOf((String) repoProperties.get(IRepository.PROP_COMPRESSED)).booleanValue(); - URI realLocation = SimpleArtifactRepository.getActualLocation(repository.getLocation(), compressed); - File realFile = URIUtil.toFile(realLocation); - - if (!realFile.exists() || !realFile.delete()) - throw new ProvisionException(NLS.bind(Messages.exception_unableToRemoveRepo, realFile.toString())); + boolean compressed = Boolean.valueOf(repoProperties.get(IRepository.PROP_COMPRESSED)).booleanValue(); + try { + URI realLocation = SimpleArtifactRepository.getActualLocation(repository.getLocation(), compressed); + File realFile = URIUtil.toFile(realLocation); + if (!realFile.exists() || !realFile.delete()) + throw new ProvisionException(NLS.bind(Messages.exception_unableToRemoveRepo, realFile.toString())); + } catch (IOException e) { + throw new ProvisionException(NLS.bind(Messages.exception_unableToRemoveRepo, repository.getLocation().toString())); + } } private void recreateRepository(IProgressMonitor monitor) throws ProvisionException { - IArtifactRepositoryManager manager = Activator.getArtifactRepositoryManager(); + IArtifactRepositoryManager manager = getArtifactRepositoryManager(); //add pack200 mappings, the existing repoProperties is not modifiable - Map newProperties = new HashMap(repoProperties); + Map newProperties = new HashMap(repoProperties); newProperties.put(PUBLISH_PACK_FILES_AS_SIBLINGS, "true"); //$NON-NLS-1$ IArtifactRepository repository = manager.createRepository(descriptor.getRepoLocation(), repoName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, newProperties); if (!(repository instanceof IFileArtifactRepository)) throw new ProvisionException(NLS.bind(Messages.exception_notLocalFileRepo, repository.getLocation())); IFileArtifactRepository simple = (IFileArtifactRepository) repository; - for (Iterator iterator = repoMap.keySet().iterator(); iterator.hasNext();) { - IArtifactKey key = (IArtifactKey) iterator.next(); - IArtifactDescriptor[] descriptors = (IArtifactDescriptor[]) repoMap.get(key); + for (IArtifactKey key : repoMap.keySet()) { + IArtifactDescriptor[] descriptors = repoMap.get(key); String unpackedSize = null; File packFile = null; - Set files = new HashSet(); + Set files = new HashSet(); for (int i = 0; i < descriptors.length; i++) { File artifactFile = simple.getArtifactFile(descriptors[i]); files.add(artifactFile); @@ -137,15 +141,14 @@ public class RecreateRepositoryApplication { } private ArtifactDescriptor createPack200ArtifactDescriptor(IArtifactKey key, File packFile, String installSize) { - final String PACKED_FORMAT = "packed"; //$NON-NLS-1$ if (packFile != null && packFile.exists()) { ArtifactDescriptor result = new ArtifactDescriptor(key); result.setProperty(IArtifactDescriptor.ARTIFACT_SIZE, installSize); result.setProperty(IArtifactDescriptor.DOWNLOAD_SIZE, Long.toString(packFile.length())); - ProcessingStepDescriptor[] steps = new ProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; //$NON-NLS-1$ + IProcessingStepDescriptor[] steps = new IProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; //$NON-NLS-1$ result.setProcessingSteps(steps); - result.setProperty(IArtifactDescriptor.FORMAT, PACKED_FORMAT); + result.setProperty(IArtifactDescriptor.FORMAT, IArtifactDescriptor.FORMAT_PACKED); return result; } return null; diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Repo2Runnable.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Repo2Runnable.java index 07815f15f..067dc367b 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Repo2Runnable.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Repo2Runnable.java @@ -16,17 +16,21 @@ import org.eclipse.core.runtime.*; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.engine.DownloadManager; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRequest; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.engine.phases.Collect; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.internal.p2.engine.*; +import org.eclipse.equinox.internal.p2.engine.phases.Collect; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRequest; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; /** * The transformer takes an existing p2 repository (local or remote), iterates over @@ -42,31 +46,26 @@ public class Repo2Runnable extends AbstractApplication implements IApplication { private static final String PARM_OPERAND = "operand"; //$NON-NLS-1$ protected class CollectNativesAction extends ProvisioningAction { - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); IInstallableUnit installableUnit = operand.second(); - IArtifactRepositoryManager manager = null; - try { - manager = Activator.getArtifactRepositoryManager(); - } catch (ProvisionException e) { - return e.getStatus(); - } - - IArtifactKey[] toDownload = installableUnit.getArtifacts(); + IArtifactRepositoryManager manager = getArtifactRepositoryManager(); + Collection toDownload = installableUnit.getArtifacts(); if (toDownload == null) return Status.OK_STATUS; - List artifactRequests = (List) parameters.get(NATIVE_ARTIFACTS); + @SuppressWarnings("unchecked") + List artifactRequests = (List) parameters.get(NATIVE_ARTIFACTS); - for (int i = 0; i < toDownload.length; i++) { - IArtifactRequest request = manager.createMirrorRequest(toDownload[i], destinationArtifactRepository, null, null); + for (IArtifactKey keyToDownload : toDownload) { + IArtifactRequest request = manager.createMirrorRequest(keyToDownload, destinationArtifactRepository, null, null); artifactRequests.add(request); } return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { // nothing to do for now return Status.OK_STATUS; } @@ -77,26 +76,28 @@ public class Repo2Runnable extends AbstractApplication implements IApplication { super(NATIVE_ARTIFACTS, weight); } - protected ProvisioningAction[] getActions(InstallableUnitOperand operand) { + protected List getActions(InstallableUnitOperand operand) { IInstallableUnit unit = operand.second(); if (unit.getTouchpointType().getId().equals(NATIVE_TYPE)) { - return new ProvisioningAction[] {new CollectNativesAction()}; + return Collections. singletonList(new CollectNativesAction()); } return null; } - protected IStatus initializePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { + protected IStatus initializePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { parameters.put(NATIVE_ARTIFACTS, new ArrayList()); return null; } - protected IStatus completePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { - List artifactRequests = (List) parameters.get(NATIVE_ARTIFACTS); + protected IStatus completePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { + @SuppressWarnings("unchecked") + List artifactRequests = (List) parameters.get(NATIVE_ARTIFACTS); ProvisioningContext context = (ProvisioningContext) parameters.get(PARM_CONTEXT); - - DownloadManager dm = new DownloadManager(context); - for (Iterator it = artifactRequests.iterator(); it.hasNext();) { - dm.add((IArtifactRequest) it.next()); + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT); + IArtifactRepositoryManager repositoryManager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME); + DownloadManager dm = new DownloadManager(context, repositoryManager); + for (IArtifactRequest request : artifactRequests) { + dm.add(request); } return dm.start(monitor); } @@ -104,7 +105,7 @@ public class Repo2Runnable extends AbstractApplication implements IApplication { // the list of IUs that we actually transformed... could have come from the repo // or have been user-specified. - private Collection processedIUs = new ArrayList(); + private Collection processedIUs = new ArrayList(); /* * Perform the transformation. @@ -120,24 +121,25 @@ public class Repo2Runnable extends AbstractApplication implements IApplication { // figure out which IUs we need to process collectIUs(progress.newChild(1)); - // create the operands from the list of IUs - InstallableUnitOperand[] operands = new InstallableUnitOperand[processedIUs.size()]; - int i = 0; - for (Iterator iter = processedIUs.iterator(); iter.hasNext();) - operands[i++] = new InstallableUnitOperand(null, (IInstallableUnit) iter.next()); - // call the engine with only the "collect" phase so all we do is download IProfile profile = createProfile(); try { + ProfileChangeRequest request = new ProfileChangeRequest(profile); + request.setAbsoluteMode(true); + request.addInstallableUnits(processedIUs.toArray(new IInstallableUnit[processedIUs.size()])); ProvisioningContext context = new ProvisioningContext(); IEngine engine = (IEngine) ServiceHelper.getService(Activator.getBundleContext(), IEngine.SERVICE_NAME); if (engine == null) throw new ProvisionException(Messages.exception_noEngineService); + IPlanner planner = (IPlanner) ServiceHelper.getService(Activator.getBundleContext(), IPlanner.SERVICE_NAME); + if (planner == null) + throw new ProvisionException(Messages.exception_noPlannerService); - IStatus result = engine.perform(profile, getPhaseSet(), operands, context, progress.newChild(1)); + IProvisioningPlan plan = planner.getProvisioningPlan(request, context, monitor); + IStatus result = engine.perform(plan, getPhaseSet(), progress.newChild(1)); PhaseSet nativeSet = getNativePhase(); if (nativeSet != null) - engine.perform(profile, nativeSet, operands, context, progress.newChild(1)); + engine.perform(plan, nativeSet, progress.newChild(1)); // publish the metadata to a destination - if requested publishMetadata(progress.newChild(1)); @@ -172,7 +174,9 @@ public class Repo2Runnable extends AbstractApplication implements IApplication { if (!hasMetadataSources()) throw new ProvisionException(Messages.exception_needIUsOrNonEmptyRepo); - processedIUs.addAll(getAllIUs(getCompositeMetadataRepository(), monitor).toCollection()); + Iterator itor = getAllIUs(getCompositeMetadataRepository(), monitor).iterator(); + while (itor.hasNext()) + processedIUs.add(itor.next()); if (processedIUs.isEmpty()) throw new ProvisionException(Messages.exception_needIUsOrNonEmptyRepo); @@ -186,16 +190,16 @@ public class Repo2Runnable extends AbstractApplication implements IApplication { // publishing the metadata is optional if (destinationMetadataRepository == null) return; - destinationMetadataRepository.addInstallableUnits((IInstallableUnit[]) processedIUs.toArray(new IInstallableUnit[processedIUs.size()])); + destinationMetadataRepository.addInstallableUnits(processedIUs.toArray(new IInstallableUnit[processedIUs.size()])); } /* * Return a collector over all the IUs contained in the given repository. */ - private Collector getAllIUs(IMetadataRepository repository, IProgressMonitor monitor) { + private IQueryResult getAllIUs(IMetadataRepository repository, IProgressMonitor monitor) { SubMonitor progress = SubMonitor.convert(monitor, 2); try { - return repository.query(InstallableUnitQuery.ANY, new Collector(), progress.newChild(1)); + return repository.query(InstallableUnitQuery.ANY, progress.newChild(1)); } finally { progress.done(); } @@ -213,7 +217,7 @@ public class Repo2Runnable extends AbstractApplication implements IApplication { * Create and return a new profile. */ private IProfile createProfile() throws ProvisionException { - Map properties = new Properties(); + Map properties = new HashMap(); properties.put(IProfile.PROP_CACHE, URIUtil.toFile(destinationArtifactRepository.getLocation()).getAbsolutePath()); properties.put(IProfile.PROP_INSTALL_FOLDER, URIUtil.toFile(destinationArtifactRepository.getLocation()).getAbsolutePath()); IProfileRegistry registry = Activator.getProfileRegistry(); diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/RepositoryAnalyzerApplication.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/RepositoryAnalyzerApplication.java new file mode 100644 index 000000000..8a8503cca --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/RepositoryAnalyzerApplication.java @@ -0,0 +1,68 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.tools; + +import java.net.URI; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.app.IApplication; +import org.eclipse.equinox.app.IApplicationContext; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.repository.tools.analyzer.RepositoryAnalyzer; + +/** + * + */ +public class RepositoryAnalyzerApplication implements IApplication { + + /* (non-Javadoc) + * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext) + */ + public Object start(IApplicationContext context) throws Exception { + + long start = System.currentTimeMillis(); + URI uri = new URI("http://download.eclipse.org/releases/galileo"); + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getBundleContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepository repository = manager.loadRepository(uri, new NullProgressMonitor()); + RepositoryAnalyzer repositoryAnalyzer = new RepositoryAnalyzer(new IMetadataRepository[] {repository}); + IStatus status = repositoryAnalyzer.analyze(new NullProgressMonitor()); + IStatus[] children = status.getChildren(); + long time = (System.currentTimeMillis()) - start; + if (status.isOK()) + System.out.println("Repository Analyzer Finished succesfuly in " + time + " ms."); + else + System.out.println("Repository Analyzer Finished in " + time + " ms with status with errors."); + for (int i = 0; i < children.length; i++) { + if (children[i].isOK()) + System.out.print("[OK] "); + else + System.out.print("[Error] "); + System.out.println(children[i].getMessage()); + if (children[i].isMultiStatus() && children[i].getChildren() != null && children[i].getChildren().length > 0) { + IStatus[] subChildren = children[i].getChildren(); + for (int j = 0; j < subChildren.length; j++) { + System.out.println(" " + subChildren[j].getMessage()); + } + } + } + return IApplication.EXIT_OK; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.app.IApplication#stop() + */ + public void stop() { + // TODO Auto-generated method stub + + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/RepositoryDescriptor.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/RepositoryDescriptor.java index 478f7fe10..f8c2ae76d 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/RepositoryDescriptor.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/RepositoryDescriptor.java @@ -12,7 +12,7 @@ package org.eclipse.equinox.p2.internal.repository.tools; import java.net.URI; import org.eclipse.equinox.internal.p2.repository.helpers.RepositoryHelper; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepository; import org.eclipse.osgi.util.NLS; public class RepositoryDescriptor { diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/SlicingOptions.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/SlicingOptions.java index 6531d3696..639279ba6 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/SlicingOptions.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/SlicingOptions.java @@ -11,7 +11,7 @@ package org.eclipse.equinox.p2.internal.repository.tools; import java.util.Dictionary; -import java.util.Properties; +import java.util.Hashtable; public class SlicingOptions { private boolean includeOptionalDependencies = true; @@ -20,7 +20,7 @@ public class SlicingOptions { private boolean considerStrictDependencyOnly = false; private boolean followOnlyFilteredRequirements = false; private boolean latestVersion = false; - private Dictionary filter = null; + private Dictionary filter = null; public boolean includeOptionalDependencies() { return includeOptionalDependencies; @@ -54,13 +54,13 @@ public class SlicingOptions { this.considerStrictDependencyOnly = strict; } - public Dictionary getFilter() { + public Dictionary getFilter() { if (filter == null) - filter = new Properties(); + filter = new Hashtable(); return filter; } - public void setFilter(Dictionary filter) { + public void setFilter(Dictionary filter) { this.filter = filter; } diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/CopyrightAnalyzer.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/CopyrightAnalyzer.java new file mode 100644 index 000000000..ea1c42bcc --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/CopyrightAnalyzer.java @@ -0,0 +1,43 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.tools.analyzer; + +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.tools.analyzer.IUAnalyzer; + +/** + * This service checks that all Group IUs have a copyright. + */ +public class CopyrightAnalyzer extends IUAnalyzer { + + public void analyzeIU(IInstallableUnit iu) { + if (Boolean.valueOf(iu.getProperty(InstallableUnitDescription.PROP_TYPE_GROUP)).booleanValue()) { + if (iu.getCopyright() == null || iu.getCopyright().getBody().length() == 0) { + // If there is no copyright at all, this is an error + error(iu, "[ERROR] " + iu.getId() + " has no copyright"); + return; + } + if (iu.getCopyright() != null && iu.getCopyright().getBody().startsWith("%")) { + // If there is a copyright, but it starts with %, then check the default + // language for a copyright + String copyrightProperty = iu.getCopyright().getBody().substring(1); + if (iu.getProperty("df_LT." + copyrightProperty) == null) + error(iu, "[ERROR] " + iu.getId() + " has no copyright"); + } + } + } + + public void preAnalysis(IMetadataRepository repository) { + // do nothing + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/HostCheckAnalyzer.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/HostCheckAnalyzer.java new file mode 100644 index 000000000..ed9125b23 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/HostCheckAnalyzer.java @@ -0,0 +1,54 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.tools.analyzer; + +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.metadata.RequiredCapability; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.expression.IMatchExpression; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.tools.analyzer.IUAnalyzer; + +/** + * This service checks that for each fragment the host can be resolved. + * Currently this service only checks requirements with the namespace "osgi.bundle" + */ +public class HostCheckAnalyzer extends IUAnalyzer { + + private IMetadataRepository repository; + + public void analyzeIU(IInstallableUnit iu) { + if (iu instanceof IInstallableUnitFragment) { + IInstallableUnitFragment fragment = (IInstallableUnitFragment) iu; + IRequirement[] hosts = fragment.getHost(); + for (int i = 0; i < hosts.length; i++) { + IMatchExpression hostMatch = hosts[i].getMatches(); + String namespace = RequiredCapability.extractNamespace(hostMatch); + if ("osgi.bundle".equals(namespace)) { + String name = RequiredCapability.extractName(hostMatch); + VersionRange range = RequiredCapability.extractRange(hostMatch); + IQueryResult results = repository.query(new InstallableUnitQuery(name, range), new NullProgressMonitor()); + if (results.isEmpty()) { + error(iu, "IU Fragment: " + iu.getId() + " cannot find host" + name + " : " + range); + return; + } + } + } + } + + } + + public void preAnalysis(IMetadataRepository repository) { + this.repository = repository; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/IUCounting.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/IUCounting.java new file mode 100644 index 000000000..4f1589c48 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/IUCounting.java @@ -0,0 +1,57 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.tools.analyzer; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.tools.analyzer.IIUAnalyzer; + +/** + * This service just counts the total number of IUs + */ +public class IUCounting implements IIUAnalyzer { + + int totalIUs = 0; + int totalGroups = 0; + int totalFragments = 0; + int totalCategories = 0; + + private boolean hasProperty(IInstallableUnit iu, String property) { + return Boolean.valueOf(iu.getProperty(property)).booleanValue(); + } + + public void analyzeIU(IInstallableUnit iu) { + totalIUs++; + if (hasProperty(iu, InstallableUnitDescription.PROP_TYPE_FRAGMENT)) + totalFragments++; + if (hasProperty(iu, InstallableUnitDescription.PROP_TYPE_GROUP)) + totalGroups++; + if (hasProperty(iu, InstallableUnitDescription.PROP_TYPE_CATEGORY)) + totalCategories++; + } + + public IStatus postAnalysis() { + System.out.println("Total IUs: " + totalIUs); + System.out.println(" Total Groups: " + totalGroups); + System.out.println(" Total Fragments: " + totalFragments); + System.out.println(" Total Categories: " + totalCategories); + return null; + } + + public void preAnalysis(IMetadataRepository repo) { + totalIUs = 0; + totalGroups = 0; + totalFragments = 0; + totalCategories = 0; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/LicenseAnalyzer.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/LicenseAnalyzer.java new file mode 100644 index 000000000..452e12427 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/LicenseAnalyzer.java @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright (c) 2009 EclipseSource and others. All rights reserved. This + * program and the accompanying materials are made available under the terms of + * the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * EclipseSource - initial API and implementation + ******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.tools.analyzer; + +import org.eclipse.equinox.p2.metadata.ILicense; + +import java.util.Collection; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.tools.analyzer.IUAnalyzer; + +/** + * This service checks that each IU has a license. + */ +public class LicenseAnalyzer extends IUAnalyzer { + + public void analyzeIU(IInstallableUnit iu) { + if (Boolean.valueOf(iu.getProperty(InstallableUnitDescription.PROP_TYPE_GROUP)).booleanValue()) { + Collection licenses = iu.getLicenses(); + if (iu.getLicenses() == null || licenses.size() == 0) { + // If there is no license then this is an error + error(iu, "[ERROR] " + iu.getId() + " has no license"); + return; + } else if (licenses.iterator().next().getBody().length() == 0) { + error(iu, "[ERROR] " + iu.getId() + " has no license"); + return; + } + for (ILicense license : licenses) { + if (license.getBody().startsWith("%")) { + String licenseProperty = license.getBody().substring(1); + if (iu.getProperty("df_LT." + licenseProperty) == null) { + error(iu, "[ERROR] " + iu.getId() + " has no license"); + } + } + } + } + } + + public void preAnalysis(IMetadataRepository repository) { + // Do nothing + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/UniqueIUAnalyzer.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/UniqueIUAnalyzer.java new file mode 100644 index 000000000..8e589bf05 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/UniqueIUAnalyzer.java @@ -0,0 +1,38 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.tools.analyzer; + +import java.util.HashSet; +import java.util.Set; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.tools.analyzer.IUAnalyzer; + +/** + * This service checks that each IU is unique in a given repository. + */ +public class UniqueIUAnalyzer extends IUAnalyzer { + + Set versionedNames = null; + + public void analyzeIU(IInstallableUnit iu) { + // Create a unique name / version pair and cache it + String uniqueID = iu.getId() + ":" + iu.getVersion().toString(); + if (versionedNames.contains(uniqueID)) { + error(iu, "[ERROR]" + iu.getId() + " with version: " + iu.getVersion() + " already exists in the repository"); + return; + } + versionedNames.add(uniqueID); + } + + public void preAnalysis(IMetadataRepository repo) { + versionedNames = new HashSet(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/UnzipFeatureJarAnalyzer.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/UnzipFeatureJarAnalyzer.java new file mode 100644 index 000000000..bb0d2193a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/UnzipFeatureJarAnalyzer.java @@ -0,0 +1,49 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.tools.analyzer; + +import org.eclipse.equinox.p2.metadata.ITouchpointData; +import org.eclipse.equinox.p2.metadata.ITouchpointInstruction; + +import java.util.List; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.tools.analyzer.IUAnalyzer; + +/** + * This service checks that each Feature Jar IU has the unzip touchpoint + */ +public class UnzipFeatureJarAnalyzer extends IUAnalyzer { + + public void analyzeIU(IInstallableUnit iu) { + if (iu.getId().indexOf("feature.jar") > -1) { + List touchpointData = iu.getTouchpointData(); + if (touchpointData.size() == 0) { + error(iu, "[ERROR] No unzip touchpoint for: " + iu.getId()); + } else { + boolean found = false; + for (int i = 0; i < touchpointData.size(); i++) { + ITouchpointInstruction instruction = touchpointData.get(i).getInstruction("zipped"); + if (instruction.getBody().equals("true")) + found = true; + } + if (!found) { + error(iu, "[ERROR] No unzip touchpoint for: " + iu.getId()); + } + } + } + + } + + public void preAnalysis(IMetadataRepository repository) { + // Do nothing + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/VersionAnalyzer.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/VersionAnalyzer.java new file mode 100644 index 000000000..81a90bdc7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/analyzer/VersionAnalyzer.java @@ -0,0 +1,43 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.tools.analyzer; + +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.tools.analyzer.IUAnalyzer; + +/** + * This service checks that each IU has a proper version number + * 1. No 0.0.0 + * 2. No x.y.z.qualifier (each qualifier has been replaced) + */ +public class VersionAnalyzer extends IUAnalyzer { + + public void analyzeIU(IInstallableUnit iu) { + if (iu.getVersion().equals(Version.emptyVersion)) { + error(iu, "[ERROR] IU: " + iu.getId() + " has not replaced its qualifiier"); + return; + } + if (iu.getVersion().isOSGiCompatible()) { + String qualifier = Version.toOSGiVersion(iu.getVersion()).getQualifier(); + if (qualifier != null && qualifier.equals("qualifier")) { + error(iu, "[ERROR] IU: " + iu.getId() + " has not replaced its qualifiier"); + return; + } + } + } + + public void preAnalysis(IMetadataRepository repo) { + // Do nothing + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/messages.properties b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/messages.properties index 6b07d7fc7..708aacfd7 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/messages.properties +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/messages.properties @@ -16,6 +16,10 @@ CompositeRepository_default_artifactRepo_name=Composite Artifact Repository CompositeRepository_default_metadataRepo_name=Composite Artifact Repository CompositeRepositoryApplication_failedComparator=Artifact repository failed test with comparator: {0} +info_noMD5Infomation=No MD5 information available for the artifact [{0}]. +info_noMD5InRepository=The repository {0} does not contain MD5 information for artifact [{1}]. +warning_differentMD5=The repositories {0} and {1} have different MD5 sums for the artifact [{2}]. + no_artifactRepo_manager=Unable to acquire artifact repository manager service. no_metadataRepo_manager=Unable to acquire metadata repository manager service. no_package_admin=Unable to acquire package admin service. @@ -27,12 +31,9 @@ skippingInvalidFilter=Invalid filter format, skipping {0}. MirrorApplication_artifactDestinationNoSource=Destination artifact repository specified without a corresponding source artifact repository. MirrorApplication_metadataDestinationNoSource=Destination metadata repository specified without a corresponding source metadata repository. -MirrorApplication_missingIU=Missing: {0} -MirrorApplication_missingSourceForIUs=Unable to locate source repository for IUs MirrorApplication_no_IUs=No IUs specified and no IUs obtained from metadata repositories. MirrorApplication_set_source_repositories=Need to set the source repository location(s). -MirrorApplication_validateAndMirrorProblems=Problems occurred during validation and mirroring -ProcessRepo_location_not_url=Repository location {0} must be a URL. +ProcessRepo_location_not_url=Repository location {0} must be a URI. ProcessRepo_must_be_local=Repository must be local: {0} @@ -44,7 +45,19 @@ exception_invalidSource=Invalid source repository location: {0}. exception_unableToRemoveRepo=Unable to remove artifact repository file: {0}. exception_notLocalFileRepo= {0} is not a local file based repository. exception_noEngineService=Unable to acquire engine service. +exception_noPlannerService=Unable to acquire planner service. +exception_loadingRepository=Exception while loading repository. exception_needIUsOrNonEmptyRepo=Need to specify either a non-empty source metadata repository or a valid list of IUs. exception_needDestinationRepo=Need to set the destination artifact repository location. exception_onlyOneComparator=Only one comparator should be defined. -Repo2RunnableTask_errorTransforming=Error occurred while transforming repository. \ No newline at end of file +Repo2RunnableTask_errorTransforming=Error occurred while transforming repository: {0}. + +message_mirroringStatus = Messages while mirroring artifact descriptors. +Mirroring_compareAndDownload=Compare and download of {0} from baseline. +mirror_alreadyExists=Artifact: {0} already exists in repository: {1}. +Mirroring_noMatchingDescriptor=Could not match descriptor for compare +Mirroring_ValidationError=Error occurred while validating mirror. +Mirroring_missingDescriptor=Missing descriptor: {0}. +Mirroring_differentDescriptorProperty=Descriptor {0} has different properties for {1}, source: {2}, destination: {3}. + +invalidComparatorId={0} is not a valid comparator id. \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/analyzer/IIUAnalyzer.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/analyzer/IIUAnalyzer.java new file mode 100644 index 000000000..f1dae6c8d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/analyzer/IIUAnalyzer.java @@ -0,0 +1,38 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.repository.tools.analyzer; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; + +/** + * The IUAnalaysis Interface. + * + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + * + * Clients are encouraged to extend IUAnalysis, an abstract class that implements + * this interface. + * + * @since 2.0 + * + */ +public interface IIUAnalyzer { + + public static final String ID = "org.eclipse.equinox.p2.repository.tools.verifier"; //$NON-NLS-1$ + + public void preAnalysis(IMetadataRepository repository); + + public IStatus postAnalysis(); + + public void analyzeIU(IInstallableUnit iu); + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/analyzer/IUAnalyzer.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/analyzer/IUAnalyzer.java new file mode 100644 index 000000000..4d5bc0ca3 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/analyzer/IUAnalyzer.java @@ -0,0 +1,46 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.repository.tools.analyzer; + +import java.util.ArrayList; +import java.util.List; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.p2.internal.repository.tools.Activator; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; + +/** + * An abstract base class for the Analyzer. Clients are encouraged to extends this + * class when defining IU Analysis extension points. + * + */ +public abstract class IUAnalyzer implements IIUAnalyzer { + + private List errors = null; + private String analyzerName; + + public void setName(String name) { + this.analyzerName = name; + } + + protected void error(IInstallableUnit iu, String error) { + if (errors == null) + errors = new ArrayList(); + errors.add(new Status(IStatus.ERROR, Activator.ID, error)); + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.repository.tools.verifier.IIUAnalysis#postAnalysis() + */ + public IStatus postAnalysis() { + if (errors == null || errors.size() == 0) + return Status.OK_STATUS; + return new MultiStatus(Activator.ID, IStatus.ERROR, errors.toArray(new IStatus[errors.size()]), analyzerName, null); + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/analyzer/RepositoryAnalyzer.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/analyzer/RepositoryAnalyzer.java new file mode 100644 index 000000000..f3e208ec1 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/analyzer/RepositoryAnalyzer.java @@ -0,0 +1,72 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.repository.tools.analyzer; + +import java.util.Iterator; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.p2.internal.repository.tools.Activator; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; + +/** + * + */ +public class RepositoryAnalyzer { + + private final IMetadataRepository[] repositories; + + public RepositoryAnalyzer(IMetadataRepository[] repositories) { + this.repositories = repositories; + } + + public IStatus analyze(IProgressMonitor monitor) { + MultiStatus result = new MultiStatus(Activator.ID, IStatus.OK, null, null); + + SubMonitor sub = SubMonitor.convert(monitor, repositories.length * 2); + IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(IIUAnalyzer.ID); + + for (int i = 0; i < repositories.length; i++) { + IQueryResult queryResult = repositories[i].query(InstallableUnitQuery.ANY, sub); + + SubMonitor repositoryMonitor = SubMonitor.convert(sub, IProgressMonitor.UNKNOWN); + for (int j = 0; j < config.length; j++) { + try { + IIUAnalyzer verifier = (IIUAnalyzer) config[j].createExecutableExtension("class"); //$NON-NLS-1$ + String analyizerName = config[j].getAttribute("name"); //$NON-NLS-1$ + if (verifier instanceof IUAnalyzer) { + ((IUAnalyzer) verifier).setName(analyizerName); + } + verifier.preAnalysis(repositories[i]); + Iterator iter = queryResult.iterator(); + while (iter.hasNext()) { + IInstallableUnit iu = iter.next(); + verifier.analyzeIU(iu); + } + IStatus postAnalysisResult = verifier.postAnalysis(); + if (postAnalysisResult == null) + postAnalysisResult = new Status(IStatus.OK, Activator.ID, analyizerName); + if (postAnalysisResult.isOK() && !postAnalysisResult.isMultiStatus()) + postAnalysisResult = new Status(IStatus.OK, Activator.ID, analyizerName); + result.add(postAnalysisResult); + } catch (CoreException e) { + if (e.getCause() instanceof ClassNotFoundException) { + result.add(new Status(IStatus.ERROR, Activator.ID, "Cannot find: " + config[j].getAttribute("class"))); + } else + e.printStackTrace(); + } + } + repositoryMonitor.done(); + } + sub.done(); + return result; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/comparator/ArtifactComparatorFactory.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/comparator/ArtifactComparatorFactory.java new file mode 100644 index 000000000..522fc9ac3 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/comparator/ArtifactComparatorFactory.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Compeople AG (Stefan Liebig) - various ongoing maintenance + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.tools.comparator; + +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.RegistryFactory; +import org.eclipse.equinox.internal.p2.artifact.repository.Messages; +import org.eclipse.osgi.util.NLS; + +public class ArtifactComparatorFactory { + private static final String comparatorPoint = "org.eclipse.equinox.p2.artifact.repository.artifactComparators"; //$NON-NLS-1$ + private static final String ATTR_ID = "id"; //$NON-NLS-1$ + private static final String ATTR_CLASS = "class"; //$NON-NLS-1$ + + public static IArtifactComparator getArtifactComparator(String comparatorID) { + IConfigurationElement[] extensions = RegistryFactory.getRegistry().getConfigurationElementsFor(comparatorPoint); + + IConfigurationElement element = null; + if (comparatorID == null && extensions.length > 0) { + element = extensions[0]; //just take the first one + } else { + for (int i = 0; i < extensions.length; i++) { + if (extensions[i].getAttribute(ATTR_ID).equals(comparatorID)) { + element = extensions[i]; + break; + } + } + } + if (element != null) { + try { + Object execExt = element.createExecutableExtension(ATTR_CLASS); + if (execExt instanceof IArtifactComparator) + return (IArtifactComparator) execExt; + } catch (Exception e) { + //fall through + } + } + + if (comparatorID != null) + throw new IllegalArgumentException(NLS.bind(Messages.exception_comparatorNotFound, comparatorID)); + throw new IllegalArgumentException(Messages.exception_noComparators); + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/comparator/IArtifactComparator.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/comparator/IArtifactComparator.java new file mode 100644 index 000000000..5197395ae --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/repository/tools/comparator/IArtifactComparator.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.p2.repository.tools.comparator; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; + +public interface IArtifactComparator { + + /** + * Compare 2 equivalent IArtifactDescriptors from different repositories. + * + * IArtifactDescriptors with the same id and version should represent the same + * set of bytes. The comparator should ensure this is true and return an error + * or warning otherwise. + * + * @param source - The source IArtifactRepository + * @param sourceDescriptor - The IArtifactDescriptor from the source repository + * @param destination - The target IArtifactRepository + * @param destDescriptor - The IArtifactDescriptor from the target repository + * + * @return IStatus + */ + public IStatus compare(IArtifactRepository source, IArtifactDescriptor sourceDescriptor, IArtifactRepository destination, IArtifactDescriptor destDescriptor); +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/AbstractRepositoryTask.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/AbstractRepositoryTask.java index 372a2929f..083755166 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/AbstractRepositoryTask.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/AbstractRepositoryTask.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. + * Copyright (c) 2009, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,10 +10,6 @@ *******************************************************************************/ package org.eclipse.equinox.p2.internal.repository.tools.tasks; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; - import java.io.File; import java.net.URI; import java.net.URISyntaxException; @@ -22,17 +18,18 @@ import org.apache.tools.ant.*; import org.apache.tools.ant.types.FileSet; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.p2.artifact.repository.ant.AntMirrorLog; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; import org.eclipse.equinox.p2.internal.repository.tools.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.osgi.util.NLS; public abstract class AbstractRepositoryTask extends Task { protected static final String ANT_PREFIX = "${"; //$NON-NLS-1$ protected AbstractApplication application; - protected List iuTasks = new ArrayList(); - protected List sourceRepos = new ArrayList(); - protected List destinations = new ArrayList(); + protected List iuTasks = new ArrayList(); + protected List sourceRepos = new ArrayList(); + protected List destinations = new ArrayList(); protected void addMetadataSourceRepository(URI repoLocation) { RepositoryDescriptor source = new RepositoryDescriptor(); @@ -105,13 +102,11 @@ public abstract class AbstractRepositoryTask extends Task { * Add source repositories to mirror from */ public void addConfiguredSource(RepositoryList sourceList) { - for (Iterator iter = sourceList.getRepositoryList().iterator(); iter.hasNext();) { - DestinationRepository repo = (DestinationRepository) iter.next(); + for (DestinationRepository repo : sourceList.getRepositoryList()) { application.addSource(repo.getDescriptor()); } - for (Iterator iter = sourceList.getFileSetList().iterator(); iter.hasNext();) { - FileSet fileSet = (FileSet) iter.next(); + for (FileSet fileSet : sourceList.getFileSetList()) { sourceRepos.add(fileSet); // Added to the application later through prepareSourceRepos } @@ -124,14 +119,15 @@ public abstract class AbstractRepositoryTask extends Task { protected void prepareSourceRepos() { if (sourceRepos == null || sourceRepos.isEmpty()) return; - for (Iterator iter = sourceRepos.iterator(); iter.hasNext();) { + for (Iterator iter = sourceRepos.iterator(); iter.hasNext();) { RepositoryFileSet fileset = (RepositoryFileSet) iter.next(); if (fileset.getRepoLocation() != null) { - //TODO depreciate if (!fileset.getRepoLocation().startsWith(ANT_PREFIX)) { - addArtifactSourceRepository(fileset.getRepoLocationURI()); - addMetadataSourceRepository(fileset.getRepoLocationURI()); + if (fileset.isArtifact()) + addArtifactSourceRepository(fileset.getRepoLocationURI()); + if (fileset.isMetadata()) + addMetadataSourceRepository(fileset.getRepoLocationURI()); } } else if (fileset.getDir() != null) { DirectoryScanner scanner = fileset.getDirectoryScanner(getProject()); @@ -160,22 +156,21 @@ public abstract class AbstractRepositoryTask extends Task { sourceRepos.clear(); } - protected List prepareIUs() { + protected List prepareIUs() { if (iuTasks == null || iuTasks.isEmpty()) return null; IMetadataRepository repository = application.getCompositeMetadataRepository(); - List result = new ArrayList(); - for (Iterator iter = iuTasks.iterator(); iter.hasNext();) { - IUDescription iu = (IUDescription) iter.next(); - Query iuQuery = iu.createQuery(); - Collector collector = new Collector(); + List result = new ArrayList(); + for (IUDescription iu : iuTasks) { + IQuery iuQuery = iu.createQuery(); - repository.query(iuQuery, collector, null); + Iterator queryResult = repository.query(iuQuery, null).iterator(); - if (iu.isRequired() && collector.isEmpty()) + if (iu.isRequired() && !queryResult.hasNext()) throw new BuildException(NLS.bind(Messages.AbstractRepositoryTask_unableToFind, iu.toString())); - result.addAll(collector.toCollection()); + while (queryResult.hasNext()) + result.add(queryResult.next()); } return result; } diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/AntMirrorLog.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/AntMirrorLog.java new file mode 100644 index 000000000..5c7d04d08 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/AntMirrorLog.java @@ -0,0 +1,106 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.tools.tasks; + +import org.eclipse.equinox.p2.internal.repository.mirroring.IArtifactMirrorLog; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.artifact.repository.Messages; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; + +public class AntMirrorLog implements IArtifactMirrorLog { + + private boolean consoleMessage = false; + private Method log; + private Object task; + + public AntMirrorLog(Object task) throws NoSuchMethodException { + this.task = task; + try { + log = task.getClass().getMethod("log", new Class[] {String.class, int.class}); //$NON-NLS-1$ + } catch (SecurityException e) { + exceptionOccurred(null, e); + } + } + + public void log(IArtifactDescriptor descriptor, IStatus status) { + log(descriptor.toString(), status.getSeverity()); + log(status); + } + + public void log(IStatus status) { + int severity = status.getSeverity(); + // Log the status message + log(status.getMessage(), severity); + // Log the exception if applicable + if (status.getException() != null) + log(status.getException().getMessage(), severity); + + // Log any children of this status + IStatus[] nestedStatus = status.getChildren(); + if (nestedStatus != null) + for (int i = 0; i < nestedStatus.length; i++) + log(nestedStatus[i]); + } + + public void close() { + // nothing to do here + } + + /* + * Log a message to the Ant Task + */ + private void log(String message, int statusSeverity) { + try { + log.invoke(task, new Object[] {message, new Integer(mapLogLevels(statusSeverity))}); + } catch (IllegalArgumentException e) { + exceptionOccurred(message, e); + } catch (IllegalAccessException e) { + exceptionOccurred(message, e); + } catch (InvocationTargetException e) { + exceptionOccurred(message, e); + } + } + + /* + * Show an error message if this the first time, and print status messages. + */ + private void exceptionOccurred(String message, Exception e) { + if (!consoleMessage) { + System.err.println(Messages.MirrorLog_Exception_Occurred); + e.printStackTrace(System.err); + System.err.println(Messages.MirrorLog_Console_Log); + consoleMessage = true; + } + if (message != null) + System.out.println(message); + } + + /** + * Copied from AntLogAdapter in pde build. + */ + private int mapLogLevels(int iStatusLevel) { + switch (iStatusLevel) { + case IStatus.ERROR : + return 0; + case IStatus.OK : + return 2; + case IStatus.INFO : + return 2; + case IStatus.WARNING : + return 1; + default : + return 1; + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/CompositeRepositoryTask.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/CompositeRepositoryTask.java index f1e8e9e9c..4560fe96f 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/CompositeRepositoryTask.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/CompositeRepositoryTask.java @@ -10,13 +10,18 @@ *******************************************************************************/ package org.eclipse.equinox.p2.internal.repository.tools.tasks; -import java.util.Iterator; +import java.net.URI; +import java.net.URISyntaxException; import org.apache.tools.ant.BuildException; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.core.runtime.URIUtil; +import org.eclipse.equinox.p2.core.ProvisionException; import org.eclipse.equinox.p2.internal.repository.tools.CompositeRepositoryApplication; +import org.eclipse.equinox.p2.internal.repository.tools.RepositoryDescriptor; public class CompositeRepositoryTask extends AbstractRepositoryTask { + private static String COMPOSITE_REMOVE = "p2.composite.artifact.repository.remove"; //$NON-NLS-1$ + private static String COMPOSITE_ADD = "p2.composite.artifact.repository.add"; //$NON-NLS-1$ public CompositeRepositoryTask() { application = new CompositeRepositoryApplication(); @@ -40,8 +45,7 @@ public class CompositeRepositoryTask extends AbstractRepositoryTask { * Add the listed repositories to the composite repository */ public void addConfiguredAdd(RepositoryList list) { - for (Iterator iter = list.getRepositoryList().iterator(); iter.hasNext();) { - DestinationRepository repo = (DestinationRepository) iter.next(); + for (DestinationRepository repo : list.getRepositoryList()) { ((CompositeRepositoryApplication) application).addChild(repo.getDescriptor()); } } @@ -50,8 +54,7 @@ public class CompositeRepositoryTask extends AbstractRepositoryTask { * Remove the listed repositories from the composite repository */ public void addConfiguredRemove(RepositoryList list) { - for (Iterator iter = list.getRepositoryList().iterator(); iter.hasNext();) { - DestinationRepository repo = (DestinationRepository) iter.next(); + for (DestinationRepository repo : list.getRepositoryList()) { ((CompositeRepositoryApplication) application).removeChild(repo.getDescriptor()); } } @@ -66,4 +69,35 @@ public class CompositeRepositoryTask extends AbstractRepositoryTask { public void setValidate(String value) { ((CompositeRepositoryApplication) application).setComparator(value); } + + /* p2.composite.artifact.repository.add + * p2.composite.artifact.repository.remove*/ + public void setLocation(String value) { + super.setDestination(value); + } + + /* p2.composite.artifact.repository.add + * p2.composite.artifact.repository.remove*/ + public void setChild(String value) throws URISyntaxException { + URI childURI = URIUtil.fromString(value); + RepositoryDescriptor repo = new RepositoryDescriptor(); + repo.setLocation(childURI); + + if (getTaskName().equals(COMPOSITE_ADD)) + ((CompositeRepositoryApplication) application).addChild(repo); + else if (getTaskName().equals(COMPOSITE_REMOVE)) + ((CompositeRepositoryApplication) application).removeChild(repo); + } + + /* p2.composite.artifact.repository.add */ + public void setComparatorID(String value) { + if (value != null && !value.startsWith(ANT_PREFIX)) + ((CompositeRepositoryApplication) application).setComparator(value); + } + + /* p2.composite.artifact.repository.remove */ + public void setAllChildren(String value) { + if (value != null && !value.startsWith(ANT_PREFIX)) + ((CompositeRepositoryApplication) application).setRemoveAll(Boolean.valueOf(value).booleanValue()); + } } diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/CreateCompositeArtifactRepositoryTask.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/CreateCompositeArtifactRepositoryTask.java new file mode 100644 index 000000000..d2a4a481a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/CreateCompositeArtifactRepositoryTask.java @@ -0,0 +1,121 @@ +/******************************************************************************* + * Copyright (c) 2008, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.tools.tasks; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.Map; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.eclipse.core.runtime.URIUtil; +import org.eclipse.equinox.internal.p2.artifact.repository.Activator; +import org.eclipse.equinox.internal.p2.artifact.repository.CompositeArtifactRepository; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; + +/** + * Ant task for creating a new composite artifact repository. + */ +public class CreateCompositeArtifactRepositoryTask extends Task { + + URI location; // desired location of the composite repository + String name = "Composite Artifact Repository"; + boolean compressed = true; + boolean failOnExists = false; // should we fail if a repo already exists? + Map properties = new HashMap(); + + /* (non-Javadoc) + * @see org.apache.tools.ant.Task#execute() + */ + public void execute() { + validate(); + IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); + if (manager == null) + throw new BuildException("Unable to aquire artifact repository manager service."); + + // remove the repo first. + manager.removeRepository(location); + + // first try and load to see if one already exists at that location. + // if we have an already existing repository at that location, then throw an error + // if the user told us to + try { + IArtifactRepository repository = manager.loadRepository(location, null); + if (repository instanceof CompositeArtifactRepository) { + if (failOnExists) + throw new BuildException("Composite repository already exists at location: " + location); + return; + } else { + // we have a non-composite repo at this location. that is ok because we can co-exist. + } + } catch (ProvisionException e) { + // re-throw the exception if we got anything other than "repo not found" + if (e.getStatus().getCode() != ProvisionException.REPOSITORY_NOT_FOUND) + throw new BuildException("Exception while trying to read repository at: " + location, e); + } + + // set the properties + if (compressed) + properties.put(IRepository.PROP_COMPRESSED, Boolean.toString(true)); + + // create the repository + try { + manager.createRepository(location, name, IArtifactRepositoryManager.TYPE_COMPOSITE_REPOSITORY, properties); + } catch (ProvisionException e) { + throw new BuildException("Error occurred while creating composite artifact repository.", e); + } + } + + /* + * Perform basic sanity checking of some of the parameters. + */ + private void validate() { + if (location == null) + throw new BuildException("Must specify repository location."); + if (name == null) + throw new BuildException("Must specify a repository name."); + } + + /* + * Set the name of the composite repository. + */ + public void setName(String value) { + name = value; + } + + /* + * Set the location of the repository. + */ + public void setLocation(String value) throws URISyntaxException { + location = URIUtil.fromString(value); + } + + /* + * Set a value indicating whether or not the repository should be compressed. + */ + public void setCompressed(boolean value) { + compressed = value; + } + + /* + * Set whether or not we should fail the operation if a repository + * already exists at the location. + */ + public void setFailOnExists(boolean value) { + failOnExists = value; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/IUDescription.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/IUDescription.java index 70a91b01c..f02a2b74a 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/IUDescription.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/IUDescription.java @@ -10,11 +10,18 @@ *******************************************************************************/ package org.eclipse.equinox.p2.internal.repository.tools.tasks; +import org.eclipse.equinox.p2.metadata.Version; + import java.util.*; import org.apache.tools.ant.types.DataType; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; +import org.eclipse.equinox.internal.p2.metadata.query.IUPropertyQuery; +import org.eclipse.equinox.internal.p2.metadata.query.LatestIUVersionQuery; import org.eclipse.equinox.p2.internal.repository.tools.Activator; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.PipedQuery; import org.osgi.framework.Filter; import org.osgi.framework.InvalidSyntaxException; @@ -100,29 +107,32 @@ public class IUDescription extends DataType { return buffer.toString(); } - public Query createQuery() { - List queries = new ArrayList(); + public IQuery createQuery() { + List> queries = new ArrayList>(); if (id != null) { if (version == null || version.length() == 0) { // Get the latest version of the iu queries.add(new InstallableUnitQuery(id)); - queries.add(new LatestIUVersionQuery()); + queries.add(new LatestIUVersionQuery()); } else { Version iuVersion = Version.parseVersion(version); queries.add(new InstallableUnitQuery(id, iuVersion)); } } - Query iuQuery = processQueryString(); + IQuery iuQuery = processQueryString(); if (iuQuery != null) queries.add(iuQuery); if (queries.size() == 1) - return (Query) queries.get(0); - return new CompositeQuery((Query[]) queries.toArray(new Query[queries.size()])); + return queries.get(0); + + @SuppressWarnings("unchecked") + IQuery query = new PipedQuery(queries.toArray(new IQuery[queries.size()])); + return query; } - private Query processQueryString() { + private IQuery processQueryString() { if (queryString == null) return null; int startIdx = queryString.indexOf('['); @@ -130,10 +140,10 @@ public class IUDescription extends DataType { if (startIdx == -1 || endIdx == -1 || endIdx < startIdx) return null; String element = queryString.substring(0, startIdx); - Map attributes = processQueryAttributes(queryString.substring(startIdx + 1, endIdx)); + Map attributes = processQueryAttributes(queryString.substring(startIdx + 1, endIdx)); if (element.equals(QUERY_PROPERTY)) { - String name = (String) attributes.get(QUERY_NAME); - String value = (String) attributes.get(QUERY_VALUE); + String name = attributes.get(QUERY_NAME); + String value = attributes.get(QUERY_VALUE); if (name == null) return null; return new IUPropertyQuery(name, value); @@ -142,11 +152,11 @@ public class IUDescription extends DataType { return null; } - private Map processQueryAttributes(String attributes) { + private Map processQueryAttributes(String attributes) { if (attributes == null || attributes.length() == 0) - return Collections.EMPTY_MAP; + return CollectionUtils.emptyMap(); - Map result = new HashMap(); + Map result = new HashMap(); int start = 0; int idx = 0; while ((idx = attributes.indexOf('@', start)) > -1) { diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/MirrorArtifactsTask.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/MirrorArtifactsTask.java new file mode 100644 index 000000000..f75497bf4 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/MirrorArtifactsTask.java @@ -0,0 +1,180 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.tools.tasks; + +import java.io.File; +import java.net.URI; +import java.net.URISyntaxException; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.eclipse.core.runtime.URIUtil; +import org.eclipse.equinox.p2.internal.repository.tools.MirrorApplication; +import org.eclipse.equinox.p2.internal.repository.tools.RepositoryDescriptor; + +/** + * Ant task for running the artifact repository mirroring application. + */ +public class MirrorArtifactsTask extends Task { + URI source; + URI destination; + String destinationName; + URI baseline; // location of known good repository for compare against (optional) + File mirrorLog; // file to log mirror output to (optional) + File comparatorLog; // file to comparator output to (optional) + String comparatorID; // specifies a comparator (optional) + String writeMode; + boolean compare = false; + boolean ignoreErrors = false; + boolean raw = false; // use raw artifact descriptors? + boolean verbose = false; + + /* (non-Javadoc) + * @see org.apache.tools.ant.Task#execute() + */ + public void execute() { + // Compare against if baseline specified + RepositoryDescriptor destinationRepo = new RepositoryDescriptor(); + destinationRepo.setName(destinationName); + destinationRepo.setLocation(destination); + destinationRepo.setKind(RepositoryDescriptor.KIND_ARTIFACT); + if (writeMode != null && writeMode.equals("clean")) //$NON-NLS-1$ + destinationRepo.setAppend(false); + + RepositoryDescriptor sourceRepo = new RepositoryDescriptor(); + sourceRepo.setLocation(source); + sourceRepo.setKind(RepositoryDescriptor.KIND_ARTIFACT); + + MirrorApplication app = new MirrorApplication(); + app.addDestination(destinationRepo); + app.addSource(sourceRepo); + app.setRaw(raw); + app.setIgnoreErrors(ignoreErrors); + app.setVerbose(verbose); + app.setCompare(compare); + app.setComparatorID(comparatorID); + app.setBaseline(baseline); + if (comparatorLog != null) + app.setComparatorLog(comparatorLog); + if (mirrorLog != null) + app.setLog(mirrorLog); + else { + try { + app.setLog(new AntMirrorLog(this)); + } catch (NoSuchMethodException e) { + //shouldn't happen + } + } + + try { + app.run(null); + } catch (Exception e) { + throw new BuildException("Exception while running mirror application.", e); + } + } + + /* + * Set the location of the source. + */ + public void setSource(String value) { + try { + source = URIUtil.fromString(value); + } catch (URISyntaxException e) { + throw new BuildException(e); + } + } + + /* + * Set the location of the destination. + */ + public void setDestination(String value) { + try { + destination = URIUtil.fromString(value); + } catch (URISyntaxException e) { + throw new BuildException(e); + } + } + + /* + * Set the name of the destination repository. + */ + public void setDestinationName(String value) { + destinationName = value; + } + + /* + * Set the location of the baseline repository. (used in comparison) + */ + public void setBaseline(String value) { + try { + baseline = URIUtil.fromString(value); + } catch (URISyntaxException e) { + throw new BuildException(e); + } + compare = true; + } + + /* + * Set the identifier of the comparator to use. + */ + public void setComparatorID(String value) { + comparatorID = value; + compare = true; + } + + /* + * Set the location of the comparator log + */ + public void setComparatorLog(String value) { + comparatorLog = new File(value); + } + + /* + * Set the write mode. (e.g. clean or append) + */ + public void setWriteMode(String value) { + writeMode = value; + } + + /* + * Set the log location if applicable + */ + public void setLog(String value) { + mirrorLog = new File(value); + } + + /* + * Set whether or not the application should be calling a comparator when mirroring. + */ + public void setCompare(boolean value) { + compare = value; + } + + /* + * Set whether or not we should ignore errors when running the mirror application. + */ + public void setIgnoreErrors(boolean value) { + ignoreErrors = value; + } + + /* + * Set whether or not the the artifacts are raw. + */ + public void setRaw(boolean value) { + raw = value; + } + + /* + * Set whether or not the mirror application should be run in verbose mode. + */ + public void setVerbose(boolean value) { + verbose = value; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/MirrorMetadataTask.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/MirrorMetadataTask.java new file mode 100644 index 000000000..f4350f3da --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/MirrorMetadataTask.java @@ -0,0 +1,95 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.tools.tasks; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.net.URI; +import java.net.URISyntaxException; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.URIUtil; +import org.eclipse.equinox.p2.internal.repository.tools.MirrorApplication; +import org.eclipse.equinox.p2.internal.repository.tools.RepositoryDescriptor; + +/** + * Ant task for running the metadata mirror application. + */ +public class MirrorMetadataTask extends Task { + URI source; + URI destination; + String destinationName; + String writeMode; + + /* (non-Javadoc) + * @see org.apache.tools.ant.Task#execute() + */ + public void execute() { + RepositoryDescriptor destinationRepo = new RepositoryDescriptor(); + destinationRepo.setName(destinationName); + destinationRepo.setLocation(destination); + destinationRepo.setKind(RepositoryDescriptor.KIND_METADATA); + if (writeMode != null && writeMode.equals("clean")) //$NON-NLS-1$ + destinationRepo.setAppend(false); + + RepositoryDescriptor sourceRepo = new RepositoryDescriptor(); + sourceRepo.setLocation(source); + sourceRepo.setKind(RepositoryDescriptor.KIND_METADATA); + + MirrorApplication app = new MirrorApplication(); + app.addDestination(destinationRepo); + app.addSource(sourceRepo); + try { + IStatus result = app.run(null); + if (result.getSeverity() != IStatus.OK) + log(result.getMessage()); + } catch (ProvisionException e) { + throw new BuildException(e); + } + } + + /* + * Set the source location. + */ + public void setSource(String value) { + try { + source = URIUtil.fromString(value); + } catch (URISyntaxException e) { + throw new BuildException(e); + } + } + + /* + * Set the destination location. + */ + public void setDestination(String value) { + try { + destination = URIUtil.fromString(value); + } catch (URISyntaxException e) { + throw new BuildException(e); + } + } + + /* + * Set the destination name. + */ + public void setDestinationName(String value) { + destinationName = value; + } + + /* + * Set the write mode for the application. (e.g. clean or append) + */ + public void setWriteMode(String value) { + writeMode = value; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/MirrorTask.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/MirrorTask.java index fceaaf32a..71f2b8bda 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/MirrorTask.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/MirrorTask.java @@ -10,14 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.internal.repository.tools.tasks; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.File; import java.util.List; import org.apache.tools.ant.BuildException; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.p2.artifact.repository.ant.AntMirrorLog; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.p2.internal.repository.tools.Messages; import org.eclipse.equinox.p2.internal.repository.tools.MirrorApplication; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; public class MirrorTask extends AbstractRepositoryTask { @@ -51,7 +52,7 @@ public class MirrorTask extends AbstractRepositoryTask { prepareSourceRepos(); application.initializeRepos(null); - List ius = prepareIUs(); + List ius = prepareIUs(); application.setSourceIUs(ius); IStatus result = application.run(null); if (result.matches(IStatus.ERROR)) diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/ProcessRepoTask.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/ProcessRepoTask.java index 9e8947335..aa069e184 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/ProcessRepoTask.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/ProcessRepoTask.java @@ -12,7 +12,6 @@ package org.eclipse.equinox.p2.internal.repository.tools.tasks; import java.io.File; -import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.apache.tools.ant.BuildException; @@ -20,7 +19,7 @@ import org.apache.tools.ant.Task; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.URIUtil; import org.eclipse.equinox.internal.p2.jarprocessor.ant.JarProcessorTask; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.core.ProvisionException; import org.eclipse.equinox.p2.internal.repository.tools.*; import org.eclipse.osgi.util.NLS; @@ -64,7 +63,8 @@ public class ProcessRepoTask extends Task { public void execute() throws BuildException { File file = URIUtil.toFile(repository); if (file == null || !file.exists()) { - throw new BuildException(NLS.bind(Messages.ProcessRepo_must_be_local, repository.toString())); + throw new BuildException(NLS.bind( + Messages.ProcessRepo_must_be_local, repository.toString())); } if (pack | repack | signing != null) { if (jarProcessor == null) @@ -76,7 +76,8 @@ public class ProcessRepoTask extends Task { jarProcessor.setStorepass(signing.storepass); jarProcessor.setUnsign(signing.unsign); - if (signing.alias != null && signing.alias.length() > 0 && !signing.alias.startsWith("${")) //$NON-NLS-1$ + if (signing.alias != null && signing.alias.length() > 0 + && !signing.alias.startsWith("${")) //$NON-NLS-1$ jarProcessor.setSign(true); } jarProcessor.setPack(pack); @@ -103,9 +104,6 @@ public class ProcessRepoTask extends Task { } catch (ProvisionException e) { // TODO Auto-generated catch block e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); } } @@ -113,7 +111,8 @@ public class ProcessRepoTask extends Task { try { this.repository = URIUtil.fromString(repository); } catch (URISyntaxException e) { - throw new IllegalArgumentException(NLS.bind(Messages.ProcessRepo_location_not_url, repository)); + throw new IllegalArgumentException(NLS.bind( + Messages.ProcessRepo_location_not_url, repository)); } } diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/RemoveIUTask.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/RemoveIUTask.java index c766504b8..531134c24 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/RemoveIUTask.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/RemoveIUTask.java @@ -14,15 +14,16 @@ import java.util.*; import org.apache.tools.ant.BuildException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.core.ProvisionException; import org.eclipse.equinox.p2.internal.repository.tools.AbstractApplication; import org.eclipse.equinox.p2.internal.repository.tools.Messages; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.osgi.util.NLS; import org.osgi.framework.Filter; import org.osgi.framework.InvalidSyntaxException; @@ -59,20 +60,18 @@ public class RemoveIUTask extends AbstractRepositoryTask { IMetadataRepository repository = application.getDestinationMetadataRepository(); IArtifactRepository artifacts = application.getDestinationArtifactRepository(); - final Set toRemove = new HashSet(); - for (Iterator iter = iuTasks.iterator(); iter.hasNext();) { - IUDescription iu = (IUDescription) iter.next(); - Query iuQuery = iu.createQuery(); + final Set toRemove = new HashSet(); + for (IUDescription iu : iuTasks) { + IQuery iuQuery = iu.createQuery(); - Collector collector = new Collector(); - repository.query(iuQuery, collector, null); + IQueryResult queryResult = repository.query(iuQuery, null); - if (collector.isEmpty()) + if (queryResult.isEmpty()) getProject().log(NLS.bind(Messages.AbstractRepositoryTask_unableToFind, iu.toString())); else { - for (Iterator iterator = collector.iterator(); iterator.hasNext();) { - IInstallableUnit unit = (IInstallableUnit) iterator.next(); - IArtifactKey[] keys = unit.getArtifacts(); + for (Iterator iterator = queryResult.iterator(); iterator.hasNext();) { + IInstallableUnit unit = iterator.next(); + Collection keys = unit.getArtifacts(); Filter filter = null; try { filter = iu.getArtifactFilter(); @@ -83,11 +82,11 @@ public class RemoveIUTask extends AbstractRepositoryTask { //we will only remove the metadata if all artifacts were removed boolean removeMetadata = true; - for (int i = 0; i < keys.length; i++) { + for (IArtifactKey key : keys) { if (filter == null) { - artifacts.removeDescriptor(keys[i]); + artifacts.removeDescriptor(key); } else { - IArtifactDescriptor[] descriptors = artifacts.getArtifactDescriptors(keys[i]); + IArtifactDescriptor[] descriptors = artifacts.getArtifactDescriptors(key); for (int j = 0; j < descriptors.length; j++) { if (filter.match(createDictionary(descriptors[j]))) { artifacts.removeDescriptor(descriptors[j]); @@ -104,12 +103,7 @@ public class RemoveIUTask extends AbstractRepositoryTask { } if (toRemove.size() > 0) { - Query removeQuery = new MatchQuery() { - public boolean isMatch(Object candidate) { - return toRemove.contains(candidate); - } - }; - repository.removeInstallableUnits(removeQuery, null); + repository.removeInstallableUnits(toRemove.toArray(new IInstallableUnit[toRemove.size()]), null); } } catch (ProvisionException e) { throw new BuildException(e); @@ -122,8 +116,8 @@ public class RemoveIUTask extends AbstractRepositoryTask { } } - private Dictionary createDictionary(IArtifactDescriptor descriptor) { - Hashtable result = new Hashtable(5); + private Dictionary createDictionary(IArtifactDescriptor descriptor) { + Hashtable result = new Hashtable(5); result.putAll(descriptor.getProperties()); IArtifactKey key = descriptor.getArtifactKey(); result.put(CLASSIFIER, key.getClassifier()); diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/Repo2RunnableTask.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/Repo2RunnableTask.java index 8763492a5..f0af711ae 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/Repo2RunnableTask.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/Repo2RunnableTask.java @@ -10,13 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.internal.repository.tools.tasks; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.util.List; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.p2.internal.repository.tools.Messages; import org.eclipse.equinox.p2.internal.repository.tools.Repo2Runnable; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.osgi.util.NLS; /** * Ant task which calls the "repo to runnable" application. This application takes an @@ -47,7 +50,7 @@ public class Repo2RunnableTask extends AbstractRepositoryTask { try { prepareSourceRepos(); application.initializeRepos(null); - List ius = prepareIUs(); + List ius = prepareIUs(); if ((ius == null || ius.size() == 0) && !(application.hasArtifactSources() || application.hasMetadataSources())) throw new BuildException(Messages.exception_needIUsOrNonEmptyRepo); application.setSourceIUs(ius); @@ -56,9 +59,9 @@ public class Repo2RunnableTask extends AbstractRepositoryTask { throw new ProvisionException(result); } catch (ProvisionException e) { if (failOnError) - throw new BuildException(Messages.Repo2RunnableTask_errorTransforming, e); + throw new BuildException(NLS.bind(Messages.Repo2RunnableTask_errorTransforming, null != e.getMessage() ? e.getMessage() : e.toString()), e); /* else */ - getProject().log(Messages.Repo2RunnableTask_errorTransforming, Project.MSG_WARN); + getProject().log(NLS.bind(Messages.Repo2RunnableTask_errorTransforming, null != e.getMessage() ? e.getMessage() : e.toString()), Project.MSG_WARN); getProject().log(e.getMessage(), Project.MSG_WARN); } } diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/RepositoryFileSet.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/RepositoryFileSet.java index c7e88ddf4..79b16675c 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/RepositoryFileSet.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/RepositoryFileSet.java @@ -16,8 +16,8 @@ import org.apache.tools.ant.BuildException; import org.apache.tools.ant.types.FileSet; import org.eclipse.core.runtime.URIUtil; import org.eclipse.equinox.internal.p2.repository.helpers.RepositoryHelper; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; import org.eclipse.equinox.p2.internal.repository.tools.RepositoryDescriptor; +import org.eclipse.equinox.p2.repository.IRepository; public class RepositoryFileSet extends FileSet { public final static int TYPE_ARTIFACT = IRepository.TYPE_ARTIFACT; @@ -47,17 +47,14 @@ public class RepositoryFileSet extends FileSet { } public void setLocation(String value) { - // TODO depreciate myLocation = value; } public String getRepoLocation() { - // TODO depreciate return myLocation; } public URI getRepoLocationURI() { - // TODO depreciate try { return RepositoryHelper.localRepoURIHelper(URIUtil.fromString(getRepoLocation())); } catch (URISyntaxException e) { diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/RepositoryList.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/RepositoryList.java index a76d3218d..8f31ce3a7 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/RepositoryList.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/RepositoryList.java @@ -12,11 +12,12 @@ package org.eclipse.equinox.p2.internal.repository.tools.tasks; import java.util.ArrayList; import java.util.List; +import org.apache.tools.ant.types.FileSet; public class RepositoryList extends RepositoryFileSet { // TODO this class should extend DataType, currently RepoFileSet to support - List repositories = new ArrayList(); - List sourceFileSets = new ArrayList(); + List repositories = new ArrayList(); + List sourceFileSets = new ArrayList(); public DestinationRepository createRepository() { DestinationRepository repo = new DestinationRepository(); @@ -30,11 +31,11 @@ public class RepositoryList extends RepositoryFileSet { return fileSet; } - public List getRepositoryList() { + public List getRepositoryList() { return repositories; } - public List getFileSetList() { + public List getFileSetList() { //TODO this should eventually be removed sourceFileSets.add(this); return sourceFileSets; diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/SlicingOption.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/SlicingOption.java index fcd8a6b37..774201a83 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/SlicingOption.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/SlicingOption.java @@ -56,7 +56,7 @@ public class SlicingOption extends Task { StringTokenizer tok = new StringTokenizer(platformFilter, ","); //$NON-NLS-1$ if (tok.countTokens() != 3) throw new BuildException(NLS.bind(Messages.SlicingOption_invalid_platform, platformFilter)); - Dictionary filter = options.getFilter(); + Dictionary filter = options.getFilter(); filter.put("osgi.os", tok.nextToken().trim()); //$NON-NLS-1$ filter.put("osgi.ws", tok.nextToken().trim()); //$NON-NLS-1$ filter.put("osgi.arch", tok.nextToken().trim()); //$NON-NLS-1$ @@ -68,7 +68,7 @@ public class SlicingOption extends Task { } public void setIncludeFeatures(boolean includeFeatures) { - Dictionary filter = options.getFilter(); + Dictionary filter = options.getFilter(); filter.put("org.eclipse.update.install.features", String.valueOf(includeFeatures)); //$NON-NLS-1$ options.setFilter(filter); } @@ -76,7 +76,7 @@ public class SlicingOption extends Task { public void setFilter(String filterString) { if (filterString == null || filterString.trim().equals("")) //$NON-NLS-1$ return; - Dictionary filter = options.getFilter(); + Dictionary filter = options.getFilter(); StringTokenizer tok = new StringTokenizer(filterString, ","); //$NON-NLS-1$ while (tok.hasMoreTokens()) { String rule = tok.nextToken().trim(); diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/ValidateTask.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/ValidateTask.java new file mode 100644 index 000000000..5b3188218 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/ValidateTask.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (c) 2008, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.internal.repository.tools.tasks; + +import java.net.URI; +import org.apache.tools.ant.BuildException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.artifact.repository.Activator; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.internal.repository.tools.ArtifactRepositoryValidator; +import org.eclipse.equinox.p2.internal.repository.tools.Messages; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; + +/** + * Ant task for validating the contents of a composite artifact repository. + */ +public class ValidateTask extends AbstractRepositoryTask { + + private String comparatorID; // specifies the comparator we want to use. + + /* (non-Javadoc) + * @see org.apache.tools.ant.Task#execute() + */ + public void execute() { + IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); + if (manager == null) + throw new BuildException(Messages.no_artifactRepo_manager); + + ArtifactRepositoryValidator validator; + try { + validator = new ArtifactRepositoryValidator(comparatorID); + } catch (ProvisionException e) { + throw new BuildException(Messages.invalidComparatorId, e); + } + + IArtifactRepository artifactRepository = null; + for (DestinationRepository repo : destinations) { + URI repoLocation = repo.getDescriptor().getRepoLocation(); + try { + artifactRepository = manager.loadRepository(repoLocation, null); + IStatus result = validator.validateRepository(artifactRepository); + if (!result.isOK()) + throw new BuildException(result.getMessage()); + } catch (ProvisionException e) { + throw new BuildException(Messages.exception_loadingRepository, e); + } + } + } + + /* + * Set the repository location. + */ + public void setLocation(String value) { + super.setDestination(value); + } + + /* + * Set the ID of the comparator. + */ + public void setComparatorID(String value) { + comparatorID = value; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository/.classpath b/bundles/org.eclipse.equinox.p2.repository/.classpath index 2fbb7a23e..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.repository/.classpath +++ b/bundles/org.eclipse.equinox.p2.repository/.classpath @@ -1,6 +1,6 @@ - + diff --git a/bundles/org.eclipse.equinox.p2.repository/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.repository/.settings/org.eclipse.jdt.core.prefs index fe9a0e76d..ff91d95c4 100644 --- a/bundles/org.eclipse.equinox.p2.repository/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.repository/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Mon May 04 16:59:04 EDT 2009 +#Tue Dec 22 19:20:12 CET 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.builder.cleanOutputFolder=clean org.eclipse.jdt.core.builder.duplicateResourceTask=warning @@ -7,17 +7,17 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning org.eclipse.jdt.core.compiler.problem.deadCode=warning @@ -26,7 +26,7 @@ org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=ignore org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=warning @@ -88,7 +88,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enab org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 diff --git a/bundles/org.eclipse.equinox.p2.repository/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.repository/META-INF/MANIFEST.MF index 892eea393..4e740051a 100644 --- a/bundles/org.eclipse.equinox.p2.repository/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.repository/META-INF/MANIFEST.MF @@ -3,30 +3,37 @@ Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-Localization: plugin Bundle-SymbolicName: org.eclipse.equinox.p2.repository;singleton:=true -Bundle-Version: 1.0.0.qualifier +Bundle-Version: 2.0.0.qualifier Bundle-Activator: org.eclipse.equinox.internal.p2.repository.Activator Require-Bundle: org.eclipse.equinox.common, org.eclipse.ecf.filetransfer, org.eclipse.ecf, - org.eclipse.equinox.p2.core, - org.eclipse.equinox.registry;bundle-version="3.4.100", + org.eclipse.equinox.registry;bundle-version="3.3.0", org.eclipse.ecf.provider.filetransfer;bundle-version="3.0.1" Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: J2SE-1.4, +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, CDC-1.1/Foundation-1.1 Bundle-Vendor: %providerName Import-Package: javax.xml.parsers, org.eclipse.core.runtime.jobs, org.eclipse.core.runtime.preferences;version="3.2.0", + org.eclipse.equinox.internal.p2.core, + org.eclipse.equinox.internal.p2.core.helpers, org.eclipse.equinox.internal.p2.repository.helpers, org.eclipse.equinox.internal.provisional.p2.core, + org.eclipse.equinox.internal.provisional.p2.core.eventbus, org.eclipse.equinox.internal.provisional.p2.metadata, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.query, org.eclipse.equinox.security.storage, org.eclipse.osgi.service.debug, org.eclipse.osgi.util;version="1.1.0", - org.osgi.framework;version="1.4.0", + org.osgi.framework;version="1.3.0", org.osgi.service.packageadmin;version="1.2.0", - org.osgi.service.prefs;version="1.1.1", + org.osgi.service.prefs;version="1.0.0", org.osgi.util.tracker;version="1.3.0", org.xml.sax, org.xml.sax.helpers @@ -36,9 +43,15 @@ Export-Package: org.eclipse.equinox.internal.p2.persistence;x-friends:="org.ecli x-friends:="org.eclipse.equinox.p2.artifact.repository, org.eclipse.equinox.p2.exemplarysetup, org.eclipse.equinox.p2.metadata.repository, + org.eclipse.equinox.p2.operations, org.eclipse.equinox.p2.updatesite, org.eclipse.equinox.p2.repository.tools, org.eclipse.equinox.p2.ui, org.eclipse.equinox.p2.metadata.generator", org.eclipse.equinox.internal.provisional.p2.repository;uses:="org.osgi.framework,org.eclipse.core.runtime", - org.eclipse.equinox.internal.provisional.spi.p2.repository + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.artifact.spi, + org.eclipse.equinox.p2.repository.metadata, + org.eclipse.equinox.p2.repository.metadata.spi, + org.eclipse.equinox.p2.repository.spi diff --git a/bundles/org.eclipse.equinox.p2.repository/build.properties b/bundles/org.eclipse.equinox.p2.repository/build.properties index 42c5dd351..7ac06b41b 100644 --- a/bundles/org.eclipse.equinox.p2.repository/build.properties +++ b/bundles/org.eclipse.equinox.p2.repository/build.properties @@ -15,3 +15,5 @@ bin.includes = META-INF/,\ about.html,\ plugin.properties src.includes = about.html +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeParser.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeParser.java index 057c53f3c..c3d91c1ab 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeParser.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeParser.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.persistence; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; + import java.io.*; import java.net.URI; -import java.util.*; +import java.util.ArrayList; +import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; import org.eclipse.osgi.util.NLS; import org.osgi.framework.BundleContext; import org.xml.sax.*; @@ -26,30 +28,24 @@ import org.xml.sax.*; */ public class CompositeParser extends XMLParser implements XMLConstants { - private static final Version CURRENT_VERSION = new Version(1, 0, 0); - static final VersionRange XML_TOLERANCE = new VersionRange(CURRENT_VERSION, true, new Version(2, 0, 0), false); + private static final Version CURRENT_VERSION = Version.createOSGi(1, 0, 0); + static final VersionRange XML_TOLERANCE = new VersionRange(CURRENT_VERSION, true, Version.createOSGi(2, 0, 0), false); private static final String REQUIRED_CAPABILITY_ELEMENT = "required"; //$NON-NLS-1$ private static final String REPOSITORY_ELEMENT = "repository"; //$NON-NLS-1$ String repositoryType; private CompositeRepositoryState theState; protected class ChildrenHandler extends AbstractHandler { - private ArrayList children; + private ArrayList children; public ChildrenHandler(AbstractHandler parentHandler, Attributes attributes) { super(parentHandler, CHILDREN_ELEMENT); String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE); - children = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); + children = (size != null ? new ArrayList(new Integer(size).intValue()) : new ArrayList(4)); } public URI[] getChildren() { - int size = children.size(); - URI[] result = new URI[size]; - int i = 0; - for (Iterator it = children.iterator(); it.hasNext(); i++) { - result[i] = (URI) it.next(); - } - return result; + return children.toArray(new URI[children.size()]); } public void startElement(String name, Attributes attributes) { @@ -67,9 +63,9 @@ public class CompositeParser extends XMLParser implements XMLConstants { URI currentRepo = null; - private List repos; + private List repos; - public ChildHandler(AbstractHandler parentHandler, Attributes attributes, List repos) { + public ChildHandler(AbstractHandler parentHandler, Attributes attributes, List repos) { super(parentHandler, CHILD_ELEMENT); String[] values = parseAttributes(attributes, required, optional); this.repos = repos; diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeRepositoryIO.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeRepositoryIO.java index 02319fb52..2a5b1672c 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeRepositoryIO.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeRepositoryIO.java @@ -10,12 +10,13 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.persistence; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.*; import java.net.URL; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.Activator; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.osgi.util.NLS; /** diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeRepositoryState.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeRepositoryState.java index 83f7795a6..8a5fe9841 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeRepositoryState.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeRepositoryState.java @@ -24,7 +24,7 @@ public class CompositeRepositoryState { private String provider; private String description; private URI location; - private Map properties; + private Map properties; private URI[] children; public void setName(String value) { @@ -75,11 +75,11 @@ public class CompositeRepositoryState { return location; } - public void setProperties(Map value) { + public void setProperties(Map value) { properties = value; } - public Map getProperties() { + public Map getProperties() { return properties; } diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeWriter.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeWriter.java index 00f3e1544..81d064fb5 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeWriter.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/CompositeWriter.java @@ -10,11 +10,12 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.persistence; +import org.eclipse.equinox.p2.metadata.Version; + import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; /* * Class used to persist a composite repository. @@ -22,7 +23,7 @@ import org.eclipse.equinox.internal.provisional.p2.metadata.Version; public class CompositeWriter extends XMLWriter implements XMLConstants { private static final String REPOSITORY_ELEMENT = "repository"; //$NON-NLS-1$ - private static final Version CURRENT_VERSION = new Version(1, 0, 0); + private static final Version CURRENT_VERSION = Version.createOSGi(1, 0, 0); public CompositeWriter(OutputStream output, String type) throws UnsupportedEncodingException { super(output, new XMLWriter.ProcessingInstruction[] {XMLWriter.ProcessingInstruction.makeTargetVersionInstruction(type, CURRENT_VERSION)}); diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/XMLParser.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/XMLParser.java index a428bc891..6f4e4448d 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/XMLParser.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/XMLParser.java @@ -10,6 +10,9 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.persistence; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; + import java.net.*; import java.util.List; import java.util.StringTokenizer; @@ -19,8 +22,6 @@ import org.eclipse.equinox.internal.p2.core.Activator; import org.eclipse.equinox.internal.p2.core.StringPool; import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; import org.eclipse.equinox.internal.p2.core.helpers.Tracing; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; import org.eclipse.osgi.util.NLS; import org.osgi.framework.BundleContext; import org.osgi.util.tracker.ServiceTracker; @@ -454,7 +455,7 @@ public abstract class XMLParser extends DefaultHandler implements XMLConstants { parseAttributes(attributes, noAttributes, noAttributes); } - public TextHandler(AbstractHandler parent, String elementName, Attributes attributes, List texts) { + public TextHandler(AbstractHandler parent, String elementName, Attributes attributes, List texts) { super(parent, elementName); parseAttributes(attributes, noAttributes, noAttributes); } @@ -682,7 +683,7 @@ public abstract class XMLParser extends DefaultHandler implements XMLConstants { public VersionRange checkVersionRange(String element, String attribute, String value) { try { - if (value != null && !value.equals("0.0.0")) //$NON-NLS-1$ + if (value != null) return new VersionRange(value); } catch (IllegalArgumentException iae) { invalidAttributeValue(element, attribute, value); diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/XMLWriter.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/XMLWriter.java index eb11327ce..af517d170 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/XMLWriter.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/persistence/XMLWriter.java @@ -10,9 +10,11 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.persistence; +import org.eclipse.equinox.p2.metadata.Version; + import java.io.*; import java.util.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import java.util.Map.Entry; public class XMLWriter implements XMLConstants { @@ -51,7 +53,7 @@ public class XMLWriter implements XMLConstants { } } - private Stack elements; // XML elements that have not yet been closed + private Stack elements; // XML elements that have not yet been closed private boolean open; // Can attributes be added to the current element? private String indent; // used for each level of indentation @@ -60,7 +62,7 @@ public class XMLWriter implements XMLConstants { public XMLWriter(OutputStream output, ProcessingInstruction[] piElements) throws UnsupportedEncodingException { this.pw = new PrintWriter(new OutputStreamWriter(output, "UTF8"), false); //$NON-NLS-1$ println(ProcessingInstruction.XML_UTF8); - this.elements = new Stack(); + this.elements = new Stack(); this.open = false; this.indent = " "; //$NON-NLS-1$ if (piElements != null) { @@ -101,7 +103,7 @@ public class XMLWriter implements XMLConstants { if (this.elements.empty()) { throw new EndWithoutStartError(); } - String name = (String) this.elements.pop(); + String name = this.elements.pop(); if (this.open) { println("/>"); //$NON-NLS-1$ } else { @@ -217,17 +219,16 @@ public class XMLWriter implements XMLConstants { this.pw.flush(); } - public void writeProperties(Map properties) { + public void writeProperties(Map properties) { writeProperties(PROPERTIES_ELEMENT, properties); } - public void writeProperties(String propertiesElement, Map properties) { + public void writeProperties(String propertiesElement, Map properties) { if (properties != null && properties.size() > 0) { start(propertiesElement); attribute(COLLECTION_SIZE_ATTRIBUTE, properties.size()); - for (Iterator iter = properties.keySet().iterator(); iter.hasNext();) { - String name = (String) iter.next(); - writeProperty(name, (String) properties.get(name)); + for (Entry entry : properties.entrySet()) { + writeProperty(entry.getKey(), entry.getValue()); } end(propertiesElement); } diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/Activator.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/Activator.java index 34d943870..695e2874d 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/Activator.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/Activator.java @@ -1,11 +1,15 @@ /******************************************************************************* - * Copyright (c) 2009, Cloudsmith Inc. - * The code, documentation and other materials contained herein have been - * licensed under the Eclipse Public License - v 1.0 by the copyright holder - * listed above, as the Initial Contributor under such license. The text of - * such license is available at www.eclipse.org. + * Copyright (c) 2009 Cloudsmith Inc and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc - initial API and implementation + * IBM Corporation - ongoing development + * Genuitec - Bug 291926 ******************************************************************************/ - package org.eclipse.equinox.internal.p2.repository; import org.eclipse.ecf.filetransfer.service.IRetrieveFileTransferFactory; @@ -150,7 +154,8 @@ public class Activator implements BundleActivator { for (int i = 0; i < bundles.length; i++) { try { if ((bundles[i].getState() & Bundle.INSTALLED) == 0) { - bundles[i].start(); + bundles[i].start(Bundle.START_ACTIVATION_POLICY); + bundles[i].start(Bundle.START_TRANSIENT); return true; } } catch (BundleException e) { diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/CacheManager.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/CacheManager.java index 24397e5e4..0e4eba8e5 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/CacheManager.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/CacheManager.java @@ -11,21 +11,22 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.repository; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.*; import java.net.URI; -import java.net.URL; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.ecf.filetransfer.UserCancelledException; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.p2.core.helpers.URLUtil; import org.eclipse.equinox.internal.p2.repository.*; import org.eclipse.equinox.internal.p2.repository.Activator; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.SynchronousProvisioningListener; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; -import org.eclipse.equinox.internal.provisional.p2.repository.*; +import org.eclipse.equinox.internal.provisional.p2.repository.IStateful; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.repository.IRepository; import org.eclipse.osgi.util.NLS; /** @@ -37,7 +38,12 @@ import org.eclipse.osgi.util.NLS; * was created for the repository. */ public class CacheManager { - private final AgentLocation agentLocation; + /** + * Service name for the internal cache manager service. + */ + public static final String SERVICE_NAME = CacheManager.class.getName(); + + private final IAgentLocation agentLocation; /** * IStateful implementation of BufferedOutputStream. Class is used to get the status from @@ -61,7 +67,7 @@ public class CacheManager { } - public CacheManager(AgentLocation agentLocation) { + public CacheManager(IAgentLocation agentLocation) { this.agentLocation = agentLocation; } @@ -72,7 +78,7 @@ public class CacheManager { private static final String RESUME_DEFAULT = "true"; //$NON-NLS-1$ private static final String XML_EXTENSION = ".xml"; //$NON-NLS-1$ - private final HashSet knownPrefixes = new HashSet(5); + private final HashSet knownPrefixes = new HashSet(5); /** * Returns a hash of the repository location. @@ -211,8 +217,7 @@ public class CacheManager { * @param repositoryLocation */ void deleteCache(URI repositoryLocation) { - for (Iterator it = knownPrefixes.iterator(); it.hasNext();) { - String prefix = (String) it.next(); + for (String prefix : knownPrefixes) { File[] cacheFiles = getCacheFiles(repositoryLocation, prefix); for (int i = 0; i < cacheFiles.length; i++) { // delete the cache file if it exists @@ -241,8 +246,7 @@ public class CacheManager { * Returns the file corresponding to the data area to be used by the cache manager. */ private File getCacheDirectory() { - URL dataArea = agentLocation.getDataArea(Activator.ID + "/cache/"); //$NON-NLS-1$ - return URLUtil.toFile(dataArea); + return URIUtil.toFile(agentLocation.getDataArea(Activator.ID + "/cache/")); //$NON-NLS-1$ } /** @@ -264,7 +268,7 @@ public class CacheManager { return RepositoryTransport.getInstance(); } - public boolean isResumeEnabled() { + private boolean isResumeEnabled() { String resumeProp = System.getProperty(PROP_RESUMABLE, RESUME_DEFAULT); return Boolean.valueOf(resumeProp).booleanValue(); } @@ -333,7 +337,7 @@ public class CacheManager { * Adds a {@link SynchronousProvisioningListener} to the event bus for * deleting cache files when the corresponding repository is deleted. */ - public void registerRepoEventListener(IProvisioningEventBus eventBus) { + private void registerRepoEventListener(IProvisioningEventBus eventBus) { if (busListener == null) { busListener = new SynchronousProvisioningListener() { public void notify(EventObject o) { @@ -372,7 +376,7 @@ public class CacheManager { * Removes the {@link SynchronousProvisioningListener} that cleans up the * cache file from the event bus. */ - public void unregisterRepoEventListener(IProvisioningEventBus bus) { + private void unregisterRepoEventListener(IProvisioningEventBus bus) { if (bus != null && busListener != null) bus.removeListener(busListener); } diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/Credentials.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/Credentials.java index 0ff55aac9..09500c2db 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/Credentials.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/Credentials.java @@ -22,7 +22,7 @@ import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.repository.helpers.DebugHelper; import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI; import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI.AuthenticationInfo; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepository; import org.eclipse.equinox.security.storage.*; /** @@ -39,13 +39,13 @@ public class Credentials { /** * Cache of auth information that is not persisted, and modified auth info. */ - private static final Map savedAuthInfo = Collections.synchronizedMap(new HashMap()); + private static final Map savedAuthInfo = Collections.synchronizedMap(new HashMap()); /** * Information about retry counts, and prompts canceled by user. The SoftReference is * a Map if not null. The keys are also used as serialization per host. */ - private static Map remembered; + private static Map remembered; /** * Serializes pop up of login/password prompt @@ -118,8 +118,8 @@ public class Credentials { // Start by getting a key to lock on HostEntry hostLock = null; synchronized (Credentials.class) { - Map r = getRemembered(); - hostLock = (HostEntry) r.get(host); + Map r = getRemembered(); + hostLock = r.get(host); if (hostLock == null) { hostLock = new HostEntry(0); r.put(host, hostLock); @@ -321,7 +321,7 @@ public class Credentials { * or null if no information is stored. */ private static AuthenticationInfo restoreFromMemory(String nodeName) { - return (AuthenticationInfo) savedAuthInfo.get(nodeName); + return savedAuthInfo.get(nodeName); } /** @@ -336,7 +336,7 @@ public class Credentials { * @param host */ private static void rememberCancel(String host) { - Map r = getRemembered(); + Map r = getRemembered(); if (r != null) r.put(host, new HostEntry(-1)); } @@ -348,7 +348,7 @@ public class Credentials { * @throws LoginCanceledException */ private static void checkRememberedCancel(String host) throws LoginCanceledException { - Map r = getRemembered(); + Map r = getRemembered(); if (r != null) { Object x = r.get(host); if (x != null && x instanceof HostEntry) @@ -370,9 +370,9 @@ public class Credentials { * @param host */ private static void incrementPromptCount(String host) { - Map r = getRemembered(); + Map r = getRemembered(); if (r != null) { - HostEntry value = (HostEntry) r.get(host); + HostEntry value = r.get(host); if (value == null) r.put(host, value = new HostEntry(1)); else { @@ -389,9 +389,9 @@ public class Credentials { * @return number of time prompt has been performed for a host (or 0 if information is stale) */ private static int getPromptCount(String host) { - Map r = getRemembered(); + Map r = getRemembered(); if (r != null) { - HostEntry value = (HostEntry) r.get(host); + HostEntry value = r.get(host); if (value != null && !value.isStale()) return value.getCount(); } @@ -406,14 +406,13 @@ public class Credentials { public static synchronized void clearPromptCache() { if (remembered == null) return; - Map r = remembered; + Map r = remembered; if (r == null || r.isEmpty()) return; // reset entries rather than creating a new empty map since the entries // are also used as locks - Iterator itor = r.entrySet().iterator(); - while (itor.hasNext()) - ((HostEntry) itor.next()).reset(); + for (HostEntry entry : r.values()) + entry.reset(); } /** @@ -433,17 +432,17 @@ public class Credentials { public static synchronized void clearPromptCache(String host) { if (remembered == null) return; - Map r = remembered; + Map r = remembered; if (r == null) return; - HostEntry value = (HostEntry) r.get(host); + HostEntry value = r.get(host); if (value != null) value.reset(); } - private static synchronized Map getRemembered() { + private static synchronized Map getRemembered() { if (remembered == null) - remembered = Collections.synchronizedMap(new HashMap()); + remembered = Collections.synchronizedMap(new HashMap()); return remembered; } diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/ProgressStatistics.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/ProgressStatistics.java index ec9d2985a..6b740e448 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/ProgressStatistics.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/ProgressStatistics.java @@ -1,16 +1,21 @@ /******************************************************************************* - * Copyright (c) 2006-2009, Cloudsmith Inc. - * The code, documentation and other materials contained herein have been - * licensed under the Eclipse Public License - v 1.0 by the copyright holder - * listed above, as the Initial Contributor under such license. The text or - * such license is available at www.eclipse.org. + * Copyright (c) 2006, 2009 Cloudsmith Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc - initial API and implementation + * IBM Corporation - ongoing development + * Genuitec - Bug 291926 ******************************************************************************/ package org.eclipse.equinox.internal.p2.repository; import java.net.URI; import java.text.NumberFormat; -import java.util.*; -import java.util.Map.Entry; +import java.util.SortedMap; +import java.util.TreeMap; import org.eclipse.osgi.util.NLS; /** @@ -49,7 +54,7 @@ public class ProgressStatistics { private int m_reportInterval; - private SortedMap m_recentSpeedMap; + private SortedMap m_recentSpeedMap; private long m_recentSpeedMapKey; @@ -64,17 +69,15 @@ public class ProgressStatistics { m_current = 0; m_lastReportTime = 0; m_reportInterval = DEFAULT_REPORT_INTERVAL; - m_recentSpeedMap = new TreeMap(); + m_recentSpeedMap = new TreeMap(); m_recentSpeedMapKey = 0L; m_uri = uri; } public long getAverageSpeed() { long dur = getDuration(); - - if (dur >= 1000) - return m_current / (dur / 1000); - + if (dur > 0) + return (int) (m_current / (dur / 1000.0)); return 0L; } @@ -93,13 +96,11 @@ public class ProgressStatistics { removeObsoleteRecentSpeedData(getDuration() / SPEED_RESOLUTION); long dur = 0L; long amount = 0L; - SortedMap relevantData = m_recentSpeedMap.headMap(new Long(m_recentSpeedMapKey)); + SortedMap relevantData = m_recentSpeedMap.headMap(new Long(m_recentSpeedMapKey)); - Iterator itor = relevantData.entrySet().iterator(); - while (itor.hasNext()) { - Entry entry = (Entry) itor.next(); + for (Long rl : relevantData.values()) { dur += SPEED_RESOLUTION; - amount += ((Long) entry.getValue()).longValue(); + amount += rl.longValue(); } if (dur >= 1000) @@ -144,7 +145,7 @@ public class ProgressStatistics { synchronized private void registerRecentSpeed(long key, long inc) { Long keyL = new Long(key); - Long currentValueL = (Long) m_recentSpeedMap.get(keyL); + Long currentValueL = m_recentSpeedMap.get(keyL); long currentValue = 0L; if (currentValueL != null) currentValue = currentValueL.longValue(); diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/RepositoryStatus.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/RepositoryStatus.java index 67fbb9cd0..aae393d0f 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/RepositoryStatus.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/RepositoryStatus.java @@ -11,13 +11,14 @@ package org.eclipse.equinox.internal.p2.repository; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.FileNotFoundException; import java.net.*; import org.eclipse.core.runtime.IStatus; import org.eclipse.ecf.core.identity.IDCreateException; import org.eclipse.ecf.filetransfer.BrowseFileTransferException; import org.eclipse.ecf.filetransfer.IncomingFileTransferException; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.osgi.util.NLS; /** diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/RepositoryStatusHelper.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/RepositoryStatusHelper.java index 601a2da4d..ac3d66bd0 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/RepositoryStatusHelper.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/RepositoryStatusHelper.java @@ -10,13 +10,14 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.repository; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.*; import java.lang.reflect.InvocationTargetException; import java.net.URI; import org.eclipse.core.runtime.*; import org.eclipse.ecf.filetransfer.BrowseFileTransferException; import org.eclipse.ecf.filetransfer.IncomingFileTransferException; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.osgi.util.NLS; /** @@ -122,7 +123,7 @@ public abstract class RepositoryStatusHelper { public static Throwable unwind(Throwable t) { for (;;) { - Class tc = t.getClass(); + Class tc = t.getClass(); // We don't use instanceof operator since we want // the explicit class, not subclasses. diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/RepositoryTransport.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/RepositoryTransport.java index 02d7027b3..717920796 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/RepositoryTransport.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/RepositoryTransport.java @@ -12,6 +12,8 @@ package org.eclipse.equinox.internal.p2.repository; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.*; import java.net.URI; import org.eclipse.core.runtime.*; @@ -19,7 +21,6 @@ import org.eclipse.ecf.core.security.ConnectContextFactory; import org.eclipse.ecf.core.security.IConnectContext; import org.eclipse.ecf.filetransfer.UserCancelledException; import org.eclipse.equinox.internal.p2.repository.Credentials.LoginCanceledException; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI.AuthenticationInfo; import org.eclipse.equinox.internal.provisional.p2.repository.IStateful; import org.eclipse.osgi.util.NLS; diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/AbstractRepositoryManager.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/AbstractRepositoryManager.java index 8670f223e..15c8af8fe 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/AbstractRepositoryManager.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/AbstractRepositoryManager.java @@ -17,10 +17,14 @@ import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.preferences.IPreferencesService; import org.eclipse.equinox.internal.p2.core.Activator; import org.eclipse.equinox.internal.p2.core.helpers.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.ProvisioningListener; -import org.eclipse.equinox.internal.provisional.p2.repository.*; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.core.*; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.security.storage.EncodingUtils; import org.eclipse.osgi.util.NLS; import org.osgi.service.prefs.BackingStoreException; import org.osgi.service.prefs.Preferences; @@ -28,15 +32,15 @@ import org.osgi.service.prefs.Preferences; /** * Common code shared between artifact and metadata repository managers. */ -public abstract class AbstractRepositoryManager implements IRepositoryManager, ProvisioningListener { - protected static class RepositoryInfo { +public abstract class AbstractRepositoryManager implements IRepositoryManager, ProvisioningListener { + protected static class RepositoryInfo { public String description; public boolean isEnabled = true; public boolean isSystem = false; public URI location; public String name; public String nickname; - public SoftReference repository; + public SoftReference> repository; public String suffix; public RepositoryInfo() { @@ -65,7 +69,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P * Map of String->RepositoryInfo, where String is the repository key * obtained via getKey(URI). */ - protected Map repositories = null; + protected Map> repositories = null; //lock object to be held when referring to the repositories field protected final Object repositoryLock = new Object(); @@ -74,13 +78,15 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P * Cache List of repositories that are not reachable. Maintain cache * for short duration because repository may become available at any time. */ - protected SoftReference unavailableRepositories; + protected SoftReference> unavailableRepositories; /** * Set used to manage exclusive load locks on repository locations. */ - private Map loadLocks = new HashMap(); + private Map loadLocks = new HashMap(); protected IProvisioningEventBus eventBus; + private IAgentLocation agentLocation; + protected IProvisioningAgent agent; protected AbstractRepositoryManager() { super(); @@ -92,23 +98,23 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P * @param signalAdd whether a repository change event should be fired * @param suffix the suffix used to load the repository, or null if unknown */ - protected void addRepository(IRepository repository, boolean signalAdd, String suffix) { + protected void addRepository(IRepository repository, boolean signalAdd, String suffix) { boolean added = false; synchronized (repositoryLock) { if (repositories == null) restoreRepositories(); String key = getKey(repository.getLocation()); - RepositoryInfo info = (RepositoryInfo) repositories.get(key); + RepositoryInfo info = repositories.get(key); if (info == null) { - info = new RepositoryInfo(); + info = new RepositoryInfo(); added = true; repositories.put(key, info); } - info.repository = new SoftReference(repository); + info.repository = new SoftReference>(repository); info.name = repository.getName(); info.description = repository.getDescription(); info.location = repository.getLocation(); - String value = (String) repository.getProperties().get(IRepository.PROP_SYSTEM); + String value = repository.getProperties().get(IRepository.PROP_SYSTEM); if (value != null) info.isSystem = Boolean.valueOf(value).booleanValue(); info.suffix = suffix; @@ -138,7 +144,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P * false otherwise. */ private boolean addRepository(URI location, boolean isEnabled, boolean signalAdd) { - RepositoryInfo info = new RepositoryInfo(); + RepositoryInfo info = new RepositoryInfo(); info.location = location; info.isEnabled = isEnabled; boolean added = true; @@ -156,15 +162,15 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P return added; } - protected IRepository basicGetRepository(URI location) { + protected IRepository basicGetRepository(URI location) { checkValidLocation(location); synchronized (repositoryLock) { if (repositories == null) restoreRepositories(); - RepositoryInfo info = (RepositoryInfo) repositories.get(getKey(location)); + RepositoryInfo info = repositories.get(getKey(location)); if (info == null || info.repository == null) return null; - IRepository repo = (IRepository) info.repository.get(); + IRepository repo = info.repository.get(); //update our repository info because the repository may have changed if (repo != null) addRepository(repo, false, null); @@ -172,7 +178,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P } } - public IRepository basicRefreshRepository(URI location, IProgressMonitor monitor) throws ProvisionException { + public IRepository basicRefreshRepository(URI location, IProgressMonitor monitor) throws ProvisionException { checkValidLocation(location); clearNotFound(location); boolean wasEnabled = isEnabled(location); @@ -182,7 +188,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P fail(location, ProvisionException.REPOSITORY_NOT_FOUND); boolean loaded = false; try { - IRepository result = loadRepository(location, monitor, null, 0); + IRepository result = loadRepository(location, monitor, null, 0); loaded = true; setEnabled(location, wasEnabled); return result; @@ -208,7 +214,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P private boolean checkNotFound(URI location) { if (unavailableRepositories == null) return false; - List badRepos = (List) unavailableRepositories.get(); + List badRepos = unavailableRepositories.get(); if (badRepos == null) return false; return badRepos.contains(location); @@ -218,9 +224,9 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P * Clear the fact that we tried to load a repository at this location and did not find anything. */ private void clearNotFound(URI location) { - List badRepos; + List badRepos; if (unavailableRepositories != null) { - badRepos = (List) unavailableRepositories.get(); + badRepos = unavailableRepositories.get(); if (badRepos != null) { badRepos.remove(location); return; @@ -243,11 +249,11 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager#createRepository(java.net.URL, java.lang.String, java.lang.String, java.util.Map) */ - protected IRepository doCreateRepository(URI location, String name, String type, Map properties) throws ProvisionException { + protected IRepository doCreateRepository(URI location, String name, String type, Map properties) throws ProvisionException { checkValidLocation(location); Assert.isNotNull(name); Assert.isNotNull(type); - IRepository result = null; + IRepository result = null; try { enterLoad(location, new NullProgressMonitor()); boolean loaded = false; @@ -315,7 +321,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P Thread current = Thread.currentThread(); synchronized (loadLocks) { while (true) { - Thread owner = (Thread) loadLocks.get(location); + Thread owner = loadLocks.get(location); if (owner == null || current.equals(owner)) break; if (monitor.isCanceled()) @@ -346,13 +352,13 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P * Creates and returns a repository using the given repository factory extension. Returns * null if no factory could be found associated with that extension. */ - protected abstract IRepository factoryCreate(URI location, String name, String type, Map properties, IExtension extension) throws ProvisionException; + protected abstract IRepository factoryCreate(URI location, String name, String type, Map properties, IExtension extension) throws ProvisionException; /** * Loads and returns a repository using the given repository factory extension. Returns * null if no factory could be found associated with that extension. */ - protected abstract IRepository factoryLoad(URI location, IExtension extension, int flags, SubMonitor monitor) throws ProvisionException; + protected abstract IRepository factoryLoad(URI location, IExtension extension, int flags, SubMonitor monitor) throws ProvisionException; private void fail(URI location, int code) throws ProvisionException { String msg = null; @@ -408,7 +414,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P protected String[] getAllSuffixes() { IConfigurationElement[] elements = RegistryFactory.getRegistry().getConfigurationElementsFor(getRepositoryProviderExtensionPointId()); - ArrayList result = new ArrayList(elements.length); + ArrayList result = new ArrayList(elements.length); result.add(getDefaultSuffix()); for (int i = 0; i < elements.length; i++) { if (elements[i].getName().equals(EL_FILTER)) { @@ -417,7 +423,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P result.add(suffix); } } - return (String[]) result.toArray(new String[result.size()]); + return result.toArray(new String[result.size()]); } /** @@ -452,25 +458,27 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P synchronized (repositoryLock) { if (repositories == null) restoreRepositories(); - ArrayList result = new ArrayList(); - int i = 0; - for (Iterator it = repositories.values().iterator(); it.hasNext(); i++) { - RepositoryInfo info = (RepositoryInfo) it.next(); + ArrayList result = new ArrayList(); + for (RepositoryInfo info : repositories.values()) { if (matchesFlags(info, flags)) result.add(info.location); } - return (URI[]) result.toArray(new URI[result.size()]); + return result.toArray(new URI[result.size()]); } } /** * Return the preference node which is the root for where we store the repository information. + * Returns null if no preferences are available */ Preferences getPreferences() { + if (agentLocation == null) + return null; IPreferencesService prefService = (IPreferencesService) ServiceHelper.getService(Activator.getContext(), IPreferencesService.class.getName()); - try { - return prefService.getRootNode().node("/profile/_SELF_/" + getBundleId() + "/" + NODE_REPOSITORIES); //$NON-NLS-1$ //$NON-NLS-2$ + //see ProfileScope for preference path format + String locationString = EncodingUtils.encodeSlashes(agentLocation.getRootLocation().toString()); + return prefService.getRootNode().node("/profile/" + locationString + "/_SELF_/" + getBundleId() + '/' + NODE_REPOSITORIES); //$NON-NLS-1$ //$NON-NLS-2$ } catch (IllegalArgumentException e) { return null; } @@ -517,7 +525,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P synchronized (repositoryLock) { if (repositories == null) restoreRepositories(); - RepositoryInfo info = (RepositoryInfo) repositories.get(getKey(location)); + RepositoryInfo info = repositories.get(getKey(location)); if (info == null) return null;// Repository not found if (IRepository.PROP_DESCRIPTION.equals(key)) @@ -541,7 +549,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P synchronized (repositoryLock) { if (repositories == null) restoreRepositories(); - RepositoryInfo info = (RepositoryInfo) repositories.get(getKey(location)); + RepositoryInfo info = repositories.get(getKey(location)); if (info == null) return;// Repository not found if (IRepository.PROP_DESCRIPTION.equals(key)) @@ -580,7 +588,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P synchronized (repositoryLock) { if (repositories == null) restoreRepositories(); - RepositoryInfo info = (RepositoryInfo) repositories.get(getKey(location)); + RepositoryInfo info = repositories.get(getKey(location)); if (info != null) return info.isEnabled; // Repository not found, return false @@ -588,12 +596,12 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P } } - protected IRepository loadRepository(URI location, IProgressMonitor monitor, String type, int flags) throws ProvisionException { + protected IRepository loadRepository(URI location, IProgressMonitor monitor, String type, int flags) throws ProvisionException { checkValidLocation(location); if (monitor == null) monitor = new NullProgressMonitor(); boolean added = false; - IRepository result = null; + IRepository result = null; try { enterLoad(location, monitor); @@ -658,13 +666,13 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P return location; } - private IRepository loadRepository(URI location, String suffix, String type, int flags, SubMonitor monitor) throws ProvisionException { + private IRepository loadRepository(URI location, String suffix, String type, int flags, SubMonitor monitor) throws ProvisionException { IExtension[] providers = findMatchingRepositoryExtensions(suffix, type); // Loop over the candidates and return the first one that successfully loads monitor.beginTask("", providers.length * 10); //$NON-NLS-1$ for (int i = 0; i < providers.length; i++) try { - IRepository repo = factoryLoad(location, providers[i], flags, monitor); + IRepository repo = factoryLoad(location, providers[i], flags, monitor); if (repo != null) return repo; } catch (ProvisionException e) { @@ -687,7 +695,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P LogHelper.log(new Status(IStatus.ERROR, getBundleId(), message, t)); } - private boolean matchesFlags(RepositoryInfo info, int flags) { + private boolean matchesFlags(RepositoryInfo info, int flags) { if ((flags & REPOSITORIES_SYSTEM) == REPOSITORIES_SYSTEM) if (!info.isSystem) return false; @@ -736,7 +744,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P /* * Add the given repository object to the preferences and save. */ - private void remember(IRepository repository, String suffix) { + private void remember(IRepository repository, String suffix) { boolean changed = false; Preferences node = getPreferences(); // Ensure we retrieved preferences @@ -753,7 +761,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P changed |= putValue(node, KEY_TYPE, repository.getType()); changed |= putValue(node, KEY_VERSION, repository.getVersion()); //allow repository manager to define system property if it is undefined in the repository itself - String value = (String) repository.getProperties().get(IRepository.PROP_SYSTEM); + String value = repository.getProperties().get(IRepository.PROP_SYSTEM); if (value != null) changed |= putValue(node, KEY_SYSTEM, value); changed |= putValue(node, KEY_SUFFIX, suffix); @@ -771,7 +779,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P * @param flush true if the preference node should be flushed to * disk, and false otherwise */ - private boolean remember(RepositoryInfo info, boolean flush) { + private boolean remember(RepositoryInfo info, boolean flush) { boolean changed = false; Preferences node = getPreferences(); // Ensure we retrieved preferences @@ -800,17 +808,17 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P * Cache the fact that we tried to load a repository at this location and did not find anything. */ private void rememberNotFound(URI location) { - List badRepos; + List badRepos; if (unavailableRepositories != null) { - badRepos = (List) unavailableRepositories.get(); + badRepos = unavailableRepositories.get(); if (badRepos != null) { badRepos.add(location); return; } } - badRepos = new ArrayList(); + badRepos = new ArrayList(); badRepos.add(location); - unavailableRepositories = new SoftReference(badRepos); + unavailableRepositories = new SoftReference>(badRepos); } public boolean removeRepository(URI toRemove) { @@ -835,7 +843,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P } Preferences node = getPreferences(); if (node != null) { - getPreferences().node(repoKey).removeNode(); + node.node(repoKey).removeNode(); saveToPreferences(); } clearNotFound(toRemove); @@ -874,7 +882,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P log("Error removing invalid repository", e); //$NON-NLS-1$ } } - RepositoryInfo info = new RepositoryInfo(); + RepositoryInfo info = new RepositoryInfo(); info.location = location; info.name = child.get(KEY_NAME, null); info.nickname = child.get(KEY_NICKNAME, null); @@ -907,7 +915,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P */ private void restoreRepositories() { synchronized (repositoryLock) { - repositories = new HashMap(); + repositories = new HashMap>(); restoreSpecialRepositories(); restoreFromSystemProperty(); restoreFromPreferences(); @@ -942,7 +950,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P synchronized (repositoryLock) { if (repositories == null) restoreRepositories(); - RepositoryInfo info = (RepositoryInfo) repositories.get(getKey(location)); + RepositoryInfo info = repositories.get(getKey(location)); if (info == null || info.isEnabled == enablement) return; info.isEnabled = enablement; @@ -951,6 +959,22 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P broadcastChangeEvent(location, getRepositoryType(), RepositoryEvent.ENABLEMENT, enablement); } + /** + * Injects the agent service to be used by this repository manager + * @param agent The agent for this repository manager + */ + public void setAgent(IProvisioningAgent agent) { + this.agent = agent; + } + + /** + * Injects the agent location service to be used by this repository manager + * @param location The agent location + */ + public void setAgentLocation(IAgentLocation location) { + this.agentLocation = location; + } + /** * Injects the event bus service to be used by this repository manager. * @param bus The event bus being added @@ -987,8 +1011,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P boolean changed = false; synchronized (repositoryLock) { if (repositories != null) { - for (Iterator it = repositories.values().iterator(); it.hasNext();) { - RepositoryInfo info = (RepositoryInfo) it.next(); + for (RepositoryInfo info : repositories.values()) { changed |= remember(info, false); } } @@ -1010,7 +1033,7 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P synchronized (repositoryLock) { if (repositories == null) restoreRepositories(); - RepositoryInfo info = (RepositoryInfo) repositories.get(getKey(location)); + RepositoryInfo info = repositories.get(getKey(location)); if (info == null || info.suffix == null) return suffixes; //move lastSuffix to the front of the list but preserve order of remaining entries @@ -1026,4 +1049,43 @@ public abstract class AbstractRepositoryManager implements IRepositoryManager, P return suffixes; } + /** + * Performs a query against the contents of each known + * repository, accumulating any objects that satisfy the query in the + * provided collector. + *

    + * Note that using this method can be quite expensive, as every known + * repository will be loaded in order to query each one. If a + * client wishes to query only certain repositories, it is better to use + * {@link #getKnownRepositories(int)} to filter the list of repositories + * loaded and then query each of the returned repositories. + *

    + * This method is long-running; progress and cancellation are provided + * by the given progress monitor. + * + * @param query The query to perform against each element in each known repository + * @param monitor a progress monitor, or null if progress + * reporting is not desired + * @return A collector containing the results of the query + */ + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + URI[] locations = getKnownRepositories(REPOSITORIES_ALL); + List> queryables = new ArrayList>(locations.length); // use a list since we don't know exactly how many will load + SubMonitor sub = SubMonitor.convert(monitor, locations.length * 10); + for (int i = 0; i < locations.length; i++) { + try { + if (sub.isCanceled()) + throw new OperationCanceledException(); + queryables.add(loadRepository(locations[i], sub.newChild(9), null, 0)); + } catch (ProvisionException e) { + //ignore this repository for this query + } + } + try { + CompoundQueryable compoundQueryable = new CompoundQueryable(queryables); + return compoundQueryable.query(query, sub.newChild(locations.length * 1)); + } finally { + sub.done(); + } + } } diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/DebugHelper.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/DebugHelper.java index f230f47c5..b2f599bca 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/DebugHelper.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/DebugHelper.java @@ -11,6 +11,7 @@ package org.eclipse.equinox.internal.p2.repository.helpers; import java.util.*; +import java.util.Map.Entry; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.repository.Activator; import org.eclipse.osgi.service.debug.DebugOptions; @@ -49,7 +50,7 @@ public class DebugHelper { if (keyValueArray == null || keyValueArray.length == 0) debug(name, message); else { - Map params = new LinkedHashMap(keyValueArray.length / 2); + Map params = new LinkedHashMap(keyValueArray.length / 2); for (int i = 0; i < keyValueArray.length; i += 2) params.put(keyValueArray[i], keyValueArray[i + 1]); StringBuffer buffer = new StringBuffer(); @@ -95,15 +96,13 @@ public class DebugHelper { return buffer.toString(); } - public static String formatMap(Map map, boolean toString, boolean newLines) { + public static String formatMap(Map map, boolean toString, boolean newLines) { if (map == null || map.size() == 0) return "[]"; //$NON-NLS-1$ StringBuffer buffer = new StringBuffer(); buffer.append('['); - Iterator itor = map.entrySet().iterator(); - while (itor.hasNext()) { - Map.Entry e = (Map.Entry) itor.next(); + for (Entry e : map.entrySet()) { buffer.append(e.getKey()); buffer.append('='); if (toString) diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/RepositoryHelper.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/RepositoryHelper.java index 693231562..050693f9e 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/RepositoryHelper.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/p2/repository/helpers/RepositoryHelper.java @@ -15,7 +15,7 @@ import java.io.File; import java.net.*; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.repository.Activator; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepository; import org.eclipse.osgi.util.NLS; public class RepositoryHelper { @@ -53,7 +53,7 @@ public class RepositoryHelper { * @param repository the repository to test * @return the repository */ - public static IRepository validDestinationRepository(IRepository repository) { + public static IRepository validDestinationRepository(IRepository repository) { if (!repository.isModifiable()) throw new IllegalStateException(NLS.bind(Messages.DestinationNotModifiable, repository.getLocation())); return repository; diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/ICompositeRepository.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/ICompositeRepository.java deleted file mode 100644 index c18060524..000000000 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/ICompositeRepository.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.repository; - -import java.net.URI; -import java.util.List; - -public interface ICompositeRepository extends IRepository { - /** - * - * @return a list of URIs containing the locations of the children repositories - */ - public abstract List getChildren(); - - /** - * Removes all child repositories - */ - public abstract void removeAllChildren(); - - /** - * Removes specified URI from list of child repositories. - * Does nothing if specified URI is not a child repository - * @param child - */ - public abstract void removeChild(URI child); - - /** - * Adds a specified URI to list of child repositories. - * Does nothing if URI is a duplicate of an existing child repository. - * @param child - */ - public abstract void addChild(URI child); -} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/IRepository.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/IRepository.java deleted file mode 100644 index c472b66d1..000000000 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/IRepository.java +++ /dev/null @@ -1,188 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.repository; - -import java.net.URI; -import java.util.Map; -import org.eclipse.core.runtime.IAdaptable; - -/** - * Base interface that defines common properties that may be provided by - * various kinds of repositories. - * - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface IRepository extends IAdaptable { - /** - * The key for a boolean property indicating that the repository - * is a system repository. System repositories are implementation details - * that are not subject to general access, hidden from the typical user, etc. - */ - public static final String PROP_SYSTEM = "p2.system"; //$NON-NLS-1$ - - /** - * The key for a boolean property indicating that repository metadata is - * stored in compressed form. A compressed repository will have lower - * bandwidth cost to read when remote, but higher processing cost to - * uncompress when reading. - */ - public static final String PROP_COMPRESSED = "p2.compressed"; //$NON-NLS-1$ - - /** - * The key for a string property providing a human-readable name for the repository. - */ - public static final String PROP_NAME = "name"; //$NON-NLS-1$ - - /** - * The key for a string property providing a user-defined name for the repository. - * This property is never stored in the repository itself, but is instead tracked and managed - * by an {@link IRepositoryManager}. - */ - public static final String PROP_NICKNAME = "p2.nickname"; //$NON-NLS-1$ - - /** - * The key for a string property providing a human-readable description for the repository. - */ - public static final String PROP_DESCRIPTION = "description"; //$NON-NLS-1$ - - /** - * The key for a string property providing the common base URL that should - * be replaced with the mirror URL. - */ - public static final String PROP_MIRRORS_BASE_URL = "p2.mirrorsBaseURL"; //$NON-NLS-1$ - - /** - * The key for a string property providing a URL that can return mirrors of this - * repository. - */ - public static final String PROP_MIRRORS_URL = "p2.mirrorsURL"; //$NON-NLS-1$ - - /** - * The key for a string property containing the time when the repository was last modified. - */ - public static final String PROP_TIMESTAMP = "p2.timestamp"; //$NON-NLS-1$ - - /** - * The key for a string property providing the user name to an authenticated - * URL. This key is used in the secure preference store for repository data. - * @see #PREFERENCE_NODE - */ - public static final String PROP_USERNAME = "username"; //$NON-NLS-1$ - - /** - * The key for a string property providing the password to an authenticated - * URL. This key is used in the secure preference store for repository data. - * @see #PREFERENCE_NODE - */ - public static final String PROP_PASSWORD = "password"; //$NON-NLS-1$ - - /** - * The node identifier for repository secure preference store. - */ - public static final String PREFERENCE_NODE = "org.eclipse.equinox.p2.repository"; //$NON-NLS-1$ - - /** - * A repository type constant (value 0) representing a metadata repository. - */ - public static final int TYPE_METADATA = 0; - - /** - * A repository type constant (value 1) representing an artifact repository. - */ - public static final int TYPE_ARTIFACT = 1; - - /** - * General purpose zero-valued bit mask constant. Useful whenever you need to - * supply a bit mask with no bits set. - */ - public static final int NONE = 0; - - /** - * An option flag constant (value 1) indicating an enabled repository. - */ - public static final int ENABLED = 1; - - /** - * Returns the URL of the repository. - * TODO: Should we use URL or URI? URL requires a protocol handler - * to be installed in Java. Can the URL have any protocol? - * @return the URL of the repository. - */ - public URI getLocation(); - - /** - * Returns the name of the repository. - * @return the name of the repository. - */ - public String getName(); - - /** - * Returns a string representing the type of the repository. - * @return the type of the repository. - */ - public String getType(); - - /** - * Returns a string representing the version for the repository type. - * @return the version of the type of the repository. - */ - public String getVersion(); - - /** - * Returns a brief description of the repository. - * @return the description of the repository. - */ - public String getDescription(); - - /** - * Returns the name of the provider of the repository. - * @return the provider of this repository. - */ - public String getProvider(); - - /** - * Returns a read-only collection of the properties of the repository. - * @return the properties of this repository. - */ - public Map getProperties(); - - /** - * Returns true if this repository can be modified. - * @return whether or not this repository can be modified - */ - public boolean isModifiable(); - - /** - * Set the name of the repository. - */ - public void setName(String name); - - /** - * Sets the description of the repository. - */ - public void setDescription(String description); - - /** - * Sets the value of the property with the given key. Returns the old property - * associated with that key, if any. Setting a value of null will - * remove the corresponding key from the properties of this repository. - * - * @param key The property key - * @param value The new property value, or null to remove the key - * @return The old property value, or null if there was no old value - */ - public String setProperty(String key, String value); - - /** - * Sets the name of the provider of the repository. - */ - public void setProvider(String provider); -} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/IRepositoryManager.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/IRepositoryManager.java deleted file mode 100644 index 6506ded9e..000000000 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/IRepositoryManager.java +++ /dev/null @@ -1,211 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.repository; - -import java.net.URI; - -/** - * The common base class for metadata and artifact repository managers. - *

    - * A repository manager keeps track of a set of known repositories, and provides - * caching of these known repositories to avoid unnecessary loading of repositories - * from the disk or network. The manager fires {@link RepositoryEvent}s when the - * set of known repositories changes. - *

    - *

    - * All {@link URI} instances provided to a repository manager must be absolute. - *

    - * - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface IRepositoryManager { - /** - * Constant used to indicate that all enabled repositories are of interest. - */ - public static final int REPOSITORIES_ALL = 0; - - /** - * Constant used to indicate that disabled repositories are of interest. - * @see #getKnownRepositories(int) - */ - public static final int REPOSITORIES_DISABLED = 1 << 3; - - /** - * Constant used to indicate that local repositories are of interest. - * @see #getKnownRepositories(int) - */ - public static final int REPOSITORIES_LOCAL = 1 << 2; - - /** - * Constant used to indicate that non-system repositories are of interest. - * @see IRepository#PROP_SYSTEM - * @see #getKnownRepositories(int) - */ - public static final int REPOSITORIES_NON_SYSTEM = 1 << 1; - - /** - * Constant used to indicate that system repositories are of interest. - * @see IRepository#PROP_SYSTEM - * @see #getKnownRepositories(int) - */ - public static final int REPOSITORIES_SYSTEM = 1 << 0; - - /** - * Constant used to indicate that a repository manager should only load the - * repository if the repository is modifiable. - * @see IRepository#isModifiable() - */ - public static final int REPOSITORY_HINT_MODIFIABLE = 1 << 0; - - /** - * Adds the repository at the given location to the list of repositories tracked by - * this repository manager. - *

    - * If there is a known disabled repository at the given location, it will become - * enabled as a result of this method. Thus the caller can be guaranteed that - * there is a known, enabled repository at the given location when this method returns. - * - * @param location The absolute location of the repository to add - * @see #isEnabled(URI) - */ - public void addRepository(URI location); - - /** - * Returns whether a repository at the given location is in the list of repositories - * tracked by this repository manager. - * - * @param location The absolute location of the repository to look for - * @return true if the repository is known to this manager, - * and false otherwise - */ - public boolean contains(URI location); - - /** - * Returns the artifact repository locations known to the repository manager. - *

    - * Note that the repository manager does not guarantee that a valid repository - * exists at any of the returned locations at any particular moment in time. - * A subsequent attempt to load a repository at any of the given locations may - * or may not succeed. - * - * @param flags an integer bit-mask indicating which repositories should be - * returned. REPOSITORIES_ALL can be used as the mask when - * all enabled repositories should be returned. - * @return the locations of the repositories managed by this repository manager. - * - * @see #REPOSITORIES_ALL - * @see #REPOSITORIES_SYSTEM - * @see #REPOSITORIES_NON_SYSTEM - * @see #REPOSITORIES_LOCAL - * @see #REPOSITORIES_DISABLED - */ - public URI[] getKnownRepositories(int flags); - - /** - * Returns the property associated with the repository at the given URI, - * without loading the repository. - *

    - * Note that some properties for a repository can only be - * determined when that repository is loaded. This method will return null - * for such properties. Only values for the properties that are already - * known by a repository manager will be returned. - *

    - * If a client wishes to retrieve a property value from a repository - * regardless of the cost of retrieving it, the client should load the - * repository and then retrieve the property from the repository itself. - * - * @param location the absolute URI of the repository in question - * @param key the String key of the property desired - * @return the value of the property, or null if the repository - * does not exist, the value does not exist, or the property value - * could not be determined without loading the repository. - * - * @see IRepository#getProperties() - * @see #setRepositoryProperty(URI, String, String) - */ - public String getRepositoryProperty(URI location, String key); - - /** - * Sets the property associated with the repository at the given URI, - * without loading the repository. - *

    - * This method stores properties in a cache in the repository manager and does - * not write the property to the backing repository. This is useful for making - * repository properties available without incurring the cost of loading the repository. - * When the repository is loaded, it will overwrite any conflicting properties that - * have been set using this method. - *

    - *

    - * To persistently set a property on a repository, clients must load - * the repository and call {@link IRepository#setProperty(String, String)}. - *

    - * - * @param location the absolute URI of the repository in question - * @param key the String key of the property desired - * @param value the value to set the property to - * @see #getRepositoryProperty(URI, String) - * @see IRepository#setProperty(String, String) - */ - public void setRepositoryProperty(URI location, String key, String value); - - /** - * Returns the enablement value of a repository. Disabled repositories are known - * to the repository manager, but are never used in the context of provisioning - * operations. Disabled repositories are useful as a form of bookmark to indicate that a - * repository location is of interest, but not currently used. - *

    - * Note that enablement is a property of the repository manager and not a property - * of the affected repository. The enablement of the repository is discarded when - * a repository is removed from the repository manager. - * - * @param location The absolute location of the repository whose enablement is requested - * @return true if the repository is enabled, and - * false if it is not enabled, or if the repository location - * is not known to the repository manager. - * @see #REPOSITORIES_DISABLED - * @see #setEnabled(URI, boolean) - */ - public boolean isEnabled(URI location); - - /** - * Removes the repository at the given location from the list of - * repositories known to this repository manager. The underlying - * repository is not deleted. This method has no effect if the given - * repository is not already known to this repository manager. - * - * @param location The absolute location of the repository to remove - * @return true if a repository was removed, and - * false otherwise. - */ - public boolean removeRepository(URI location); - - /** - * Sets the enablement of a repository. Disabled repositories are known - * to the repository manager, but are never used in the context of provisioning - * operation. Disabled repositories are useful as a form of bookmark to indicate that a - * repository location is of interest, but not currently used. - *

    - * Note that enablement is a property of the repository manager and not a property - * of the affected repository. The enablement of the repository is discarded when - * a repository is removed from the repository manager. - *

    - * This method has no effect if the given repository location is not known to the - * repository manager. - * - * @param location The absolute location of the repository to enable or disable - * @param enablement trueto enable the repository, and - * false to disable the repository - * @see #REPOSITORIES_DISABLED - * @see #isEnabled(URI) - */ - public void setEnabled(URI location, boolean enablement); - -} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/RepositoryCreationException.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/RepositoryCreationException.java deleted file mode 100644 index 0a6899ad8..000000000 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/RepositoryCreationException.java +++ /dev/null @@ -1,21 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.repository; - -public class RepositoryCreationException extends Exception { - - private static final long serialVersionUID = -5648382121963317100L; - - public RepositoryCreationException(Throwable e) { - super(e); - } - -} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/RepositoryEvent.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/RepositoryEvent.java index 1768f9c91..a62905e9d 100644 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/RepositoryEvent.java +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/p2/repository/RepositoryEvent.java @@ -12,6 +12,7 @@ package org.eclipse.equinox.internal.provisional.p2.repository; import java.net.URI; import java.util.EventObject; +import org.eclipse.equinox.p2.repository.IRepository; /** * An event indicating a repository was added, removed, changed, diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/repository/AbstractRepository.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/repository/AbstractRepository.java deleted file mode 100644 index c2a626edc..000000000 --- a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/internal/provisional/spi/p2/repository/AbstractRepository.java +++ /dev/null @@ -1,134 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.spi.p2.repository; - -import java.net.URI; -import java.util.Map; -import org.eclipse.core.runtime.PlatformObject; -import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; - -/** -* AbstractRepository defines common properties that may be provided by various kinds -* of repositories. -*

    -* Clients may extend this class. -*

    -*/ -public abstract class AbstractRepository extends PlatformObject implements IRepository { - protected String description; - protected transient URI location; - protected String name; - protected Map properties = new OrderedProperties(); - protected String provider; - protected String type; - protected String version; - - protected AbstractRepository(String name, String type, String version, URI location, String description, String provider, Map properties) { - this.name = name; - this.type = type; - this.version = version; - this.location = location; - this.description = description == null ? "" : description; //$NON-NLS-1$ - this.provider = provider == null ? "" : provider; //$NON-NLS-1$ - if (properties != null) - this.properties.putAll(properties); - } - - /** - * Asserts that this repository is modifiable, throwing a runtime exception if - * it is not. This is suitable for use by subclasses when an attempt is made - * to write to a repository. - */ - protected void assertModifiable() { - if (!isModifiable()) - throw new UnsupportedOperationException("Repository not modifiable: " + location); //$NON-NLS-1$ - } - - /** - * Returns a brief description of the repository. - * @return the description of the repository. - */ - public synchronized String getDescription() { - return description; - } - - /** - * Returns the location of this repository. - * TODO: Should we use URL or URI? URL requires a protocol handler - * to be installed in Java. Can the URL have any protocol? - * @return the URL of the repository. - */ - public synchronized URI getLocation() { - return location; - } - - /** - * Returns the name of the repository. - * @return the name of the repository. - */ - public synchronized String getName() { - return name; - } - - /** - * Returns a read-only collection of the properties of the repository. - * @return the properties of this repository. - */ - public synchronized Map getProperties() { - return OrderedProperties.unmodifiableProperties(properties); - } - - /** - * Returns the name of the provider of the repository. - * @return the provider of this repository. - */ - public synchronized String getProvider() { - return provider; - } - - /** - * Returns a string representing the type of the repository. - * @return the type of the repository. - */ - public synchronized String getType() { - return type; - } - - /** - * Returns a string representing the version for the repository type. - * @return the version of the type of the repository. - */ - public synchronized String getVersion() { - return version; - } - - public boolean isModifiable() { - return false; - } - - public synchronized void setDescription(String description) { - this.description = description; - } - - public synchronized void setName(String value) { - this.name = value; - } - - public synchronized String setProperty(String key, String value) { - assertModifiable(); - return (String) (value == null ? properties.remove(key) : properties.put(key, value)); - } - - public synchronized void setProvider(String provider) { - this.provider = provider; - } -} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/ICompositeRepository.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/ICompositeRepository.java new file mode 100644 index 000000000..1bfada5b9 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/ICompositeRepository.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository; + +import java.net.URI; +import java.util.List; + +/** + * @since 2.0 + */ +public interface ICompositeRepository extends IRepository { + /** + * + * @return a list of URIs containing the locations of the children repositories + */ + public abstract List getChildren(); + + /** + * Removes all child repositories + */ + public abstract void removeAllChildren(); + + /** + * Removes specified URI from list of child repositories. + * Does nothing if specified URI is not a child repository + * @param child + */ + public abstract void removeChild(URI child); + + /** + * Adds a specified URI to list of child repositories. + * Does nothing if URI is a duplicate of an existing child repository. + * @param child + */ + public abstract void addChild(URI child); +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/IRepository.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/IRepository.java new file mode 100644 index 000000000..c8d949853 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/IRepository.java @@ -0,0 +1,190 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository; + +import java.net.URI; +import java.util.Map; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.equinox.p2.query.IQueryable; + +/** + * Base interface that defines common properties that may be provided by + * various kinds of repositories. + * + * @noimplement This interface is not intended to be implemented by clients. + * @since 2.0 + */ +public interface IRepository extends IAdaptable, IQueryable { + /** + * The key for a boolean property indicating that the repository + * is a system repository. System repositories are implementation details + * that are not subject to general access, hidden from the typical user, etc. + */ + public static final String PROP_SYSTEM = "p2.system"; //$NON-NLS-1$ + + /** + * The key for a boolean property indicating that repository metadata is + * stored in compressed form. A compressed repository will have lower + * bandwidth cost to read when remote, but higher processing cost to + * uncompress when reading. + */ + public static final String PROP_COMPRESSED = "p2.compressed"; //$NON-NLS-1$ + + /** + * The key for a string property providing a human-readable name for the repository. + */ + public static final String PROP_NAME = "name"; //$NON-NLS-1$ + + /** + * The key for a string property providing a user-defined name for the repository. + * This property is never stored in the repository itself, but is instead tracked and managed + * by an {@link IRepositoryManager}. + */ + public static final String PROP_NICKNAME = "p2.nickname"; //$NON-NLS-1$ + + /** + * The key for a string property providing a human-readable description for the repository. + */ + public static final String PROP_DESCRIPTION = "description"; //$NON-NLS-1$ + + /** + * The key for a string property providing the common base URL that should + * be replaced with the mirror URL. + */ + public static final String PROP_MIRRORS_BASE_URL = "p2.mirrorsBaseURL"; //$NON-NLS-1$ + + /** + * The key for a string property providing a URL that can return mirrors of this + * repository. + */ + public static final String PROP_MIRRORS_URL = "p2.mirrorsURL"; //$NON-NLS-1$ + + /** + * The key for a string property containing the time when the repository was last modified. + */ + public static final String PROP_TIMESTAMP = "p2.timestamp"; //$NON-NLS-1$ + + /** + * The key for a string property providing the user name to an authenticated + * URL. This key is used in the secure preference store for repository data. + * @see #PREFERENCE_NODE + */ + public static final String PROP_USERNAME = "username"; //$NON-NLS-1$ + + /** + * The key for a string property providing the password to an authenticated + * URL. This key is used in the secure preference store for repository data. + * @see #PREFERENCE_NODE + */ + public static final String PROP_PASSWORD = "password"; //$NON-NLS-1$ + + /** + * The node identifier for repository secure preference store. + */ + public static final String PREFERENCE_NODE = "org.eclipse.equinox.p2.repository"; //$NON-NLS-1$ + + /** + * A repository type constant (value 0) representing a metadata repository. + */ + public static final int TYPE_METADATA = 0; + + /** + * A repository type constant (value 1) representing an artifact repository. + */ + public static final int TYPE_ARTIFACT = 1; + + /** + * General purpose zero-valued bit mask constant. Useful whenever you need to + * supply a bit mask with no bits set. + */ + public static final int NONE = 0; + + /** + * An option flag constant (value 1) indicating an enabled repository. + */ + public static final int ENABLED = 1; + + /** + * Returns the URL of the repository. + * TODO: Should we use URL or URI? URL requires a protocol handler + * to be installed in Java. Can the URL have any protocol? + * @return the URL of the repository. + */ + public URI getLocation(); + + /** + * Returns the name of the repository. + * @return the name of the repository. + */ + public String getName(); + + /** + * Returns a string representing the type of the repository. + * @return the type of the repository. + */ + public String getType(); + + /** + * Returns a string representing the version for the repository type. + * @return the version of the type of the repository. + */ + public String getVersion(); + + /** + * Returns a brief description of the repository. + * @return the description of the repository. + */ + public String getDescription(); + + /** + * Returns the name of the provider of the repository. + * @return the provider of this repository. + */ + public String getProvider(); + + /** + * Returns a read-only collection of the properties of the repository. + * @return the properties of this repository. + */ + public Map getProperties(); + + /** + * Returns true if this repository can be modified. + * @return whether or not this repository can be modified + */ + public boolean isModifiable(); + + /** + * Set the name of the repository. + */ + public void setName(String name); + + /** + * Sets the description of the repository. + */ + public void setDescription(String description); + + /** + * Sets the value of the property with the given key. Returns the old property + * associated with that key, if any. Setting a value of null will + * remove the corresponding key from the properties of this repository. + * + * @param key The property key + * @param value The new property value, or null to remove the key + * @return The old property value, or null if there was no old value + */ + public String setProperty(String key, String value); + + /** + * Sets the name of the provider of the repository. + */ + public void setProvider(String provider); +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/IRepositoryManager.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/IRepositoryManager.java new file mode 100644 index 000000000..6c0800393 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/IRepositoryManager.java @@ -0,0 +1,217 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository; + +import org.eclipse.equinox.p2.query.IQueryable; + +import java.net.URI; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; + +/** + * The common base class for metadata and artifact repository managers. + *

    + * A repository manager keeps track of a set of known repositories, and provides + * caching of these known repositories to avoid unnecessary loading of repositories + * from the disk or network. The manager fires {@link RepositoryEvent}s when the + * set of known repositories changes. + *

    + *

    + * All {@link URI} instances provided to a repository manager must be absolute. + *

    + * + * @noimplement This interface is not intended to be implemented by clients. + * @since 2.0 + */ +public interface IRepositoryManager extends IQueryable { + /** + * Constant used to indicate that all enabled repositories are of interest. + */ + public static final int REPOSITORIES_ALL = 0; + + /** + * Constant used to indicate that disabled repositories are of interest. + * @see #getKnownRepositories(int) + */ + public static final int REPOSITORIES_DISABLED = 1 << 3; + + /** + * Constant used to indicate that local repositories are of interest. + * @see #getKnownRepositories(int) + */ + public static final int REPOSITORIES_LOCAL = 1 << 2; + + /** + * Constant used to indicate that non-system repositories are of interest. + * @see IRepository#PROP_SYSTEM + * @see #getKnownRepositories(int) + */ + public static final int REPOSITORIES_NON_SYSTEM = 1 << 1; + + /** + * Constant used to indicate that system repositories are of interest. + * @see IRepository#PROP_SYSTEM + * @see #getKnownRepositories(int) + */ + public static final int REPOSITORIES_SYSTEM = 1 << 0; + + /** + * Constant used to indicate that a repository manager should only load the + * repository if the repository is modifiable. + * @see IRepository#isModifiable() + */ + public static final int REPOSITORY_HINT_MODIFIABLE = 1 << 0; + + /** + * Adds the repository at the given location to the list of repositories tracked by + * this repository manager. This method does not attempt to contact or load + * the repository, and makes no attempt to determine whether there is a valid + * repository at the provided location. + *

    + * If there is a known disabled repository at the given location, it will become + * enabled as a result of this method. Thus the caller can be guaranteed that + * there is a known, enabled repository at the given location when this method returns. + * + * @param location The absolute location of the repository to add + * @see #isEnabled(URI) + */ + public void addRepository(URI location); + + /** + * Returns whether a repository at the given location is in the list of repositories + * tracked by this repository manager. + * + * @param location The absolute location of the repository to look for + * @return true if the repository is known to this manager, + * and false otherwise + */ + public boolean contains(URI location); + + /** + * Returns the artifact repository locations known to the repository manager. + *

    + * Note that the repository manager does not guarantee that a valid repository + * exists at any of the returned locations at any particular moment in time. + * A subsequent attempt to load a repository at any of the given locations may + * or may not succeed. + * + * @param flags an integer bit-mask indicating which repositories should be + * returned. REPOSITORIES_ALL can be used as the mask when + * all enabled repositories should be returned. + * @return the locations of the repositories managed by this repository manager. + * + * @see #REPOSITORIES_ALL + * @see #REPOSITORIES_SYSTEM + * @see #REPOSITORIES_NON_SYSTEM + * @see #REPOSITORIES_LOCAL + * @see #REPOSITORIES_DISABLED + */ + public URI[] getKnownRepositories(int flags); + + /** + * Returns the property associated with the repository at the given URI, + * without loading the repository. + *

    + * Note that some properties for a repository can only be + * determined when that repository is loaded. This method will return null + * for such properties. Only values for the properties that are already + * known by a repository manager will be returned. + *

    + * If a client wishes to retrieve a property value from a repository + * regardless of the cost of retrieving it, the client should load the + * repository and then retrieve the property from the repository itself. + * + * @param location the absolute URI of the repository in question + * @param key the String key of the property desired + * @return the value of the property, or null if the repository + * does not exist, the value does not exist, or the property value + * could not be determined without loading the repository. + * + * @see IRepository#getProperties() + * @see #setRepositoryProperty(URI, String, String) + */ + public String getRepositoryProperty(URI location, String key); + + /** + * Sets the property associated with the repository at the given URI, + * without loading the repository. + *

    + * This method stores properties in a cache in the repository manager and does + * not write the property to the backing repository. This is useful for making + * repository properties available without incurring the cost of loading the repository. + * When the repository is loaded, it will overwrite any conflicting properties that + * have been set using this method. + *

    + *

    + * To persistently set a property on a repository, clients must load + * the repository and call {@link IRepository#setProperty(String, String)}. + *

    + * + * @param location the absolute URI of the repository in question + * @param key the String key of the property desired + * @param value the value to set the property to + * @see #getRepositoryProperty(URI, String) + * @see IRepository#setProperty(String, String) + */ + public void setRepositoryProperty(URI location, String key, String value); + + /** + * Returns the enablement value of a repository. Disabled repositories are known + * to the repository manager, but are never used in the context of provisioning + * operations. Disabled repositories are useful as a form of bookmark to indicate that a + * repository location is of interest, but not currently used. + *

    + * Note that enablement is a property of the repository manager and not a property + * of the affected repository. The enablement of the repository is discarded when + * a repository is removed from the repository manager. + * + * @param location The absolute location of the repository whose enablement is requested + * @return true if the repository is enabled, and + * false if it is not enabled, or if the repository location + * is not known to the repository manager. + * @see #REPOSITORIES_DISABLED + * @see #setEnabled(URI, boolean) + */ + public boolean isEnabled(URI location); + + /** + * Removes the repository at the given location from the list of + * repositories known to this repository manager. The underlying + * repository is not deleted. This method has no effect if the given + * repository is not already known to this repository manager. + * + * @param location The absolute location of the repository to remove + * @return true if a repository was removed, and + * false otherwise. + */ + public boolean removeRepository(URI location); + + /** + * Sets the enablement of a repository. Disabled repositories are known + * to the repository manager, but are never used in the context of provisioning + * operation. Disabled repositories are useful as a form of bookmark to indicate that a + * repository location is of interest, but not currently used. + *

    + * Note that enablement is a property of the repository manager and not a property + * of the affected repository. The enablement of the repository is discarded when + * a repository is removed from the repository manager. + *

    + * This method has no effect if the given repository location is not known to the + * repository manager. + * + * @param location The absolute location of the repository to enable or disable + * @param enablement trueto enable the repository, and + * false to disable the repository + * @see #REPOSITORIES_DISABLED + * @see #isEnabled(URI) + */ + public void setEnabled(URI location, boolean enablement); + +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/ArtifactDescriptorQuery.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/ArtifactDescriptorQuery.java new file mode 100644 index 000000000..1347b8ff0 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/ArtifactDescriptorQuery.java @@ -0,0 +1,101 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.p2.repository.artifact; + +import org.eclipse.equinox.p2.metadata.VersionRange; + +import org.eclipse.equinox.p2.query.MatchQuery; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; + +/** + * An implementation of IArtifactQuery that matches IArtifactDescriptors + * @since 2.0 + */ +public class ArtifactDescriptorQuery extends MatchQuery { + public static final ArtifactDescriptorQuery ALL_DESCRIPTORS = new ArtifactDescriptorQuery(); + private VersionRange range = null; + private String id = null; + private String format = null; + private ArtifactDescriptor descriptor = null; + private IArtifactRepository repository = null; + + /** + * The query will match descriptors with the given id, version and format + * If any parameter is null, that attribute will be ignored + * @param id - the id to match, or null + * @param versionRange - the version range to match or null + * @param format - {@link IArtifactDescriptor#FORMAT} value to match, or null + */ + public ArtifactDescriptorQuery(String id, VersionRange versionRange, String format) { + this(id, versionRange, format, null); + } + + /** + * The query will match descriptors with the given id, version range, format and repository + * if any parameter is null, that attribute will be ignored + * @param id - the id to match, or null + * @param versionRange - the version range to match or null + * @param format - {@link IArtifactDescriptor#FORMAT} value to match, or null + * @param repository + */ + public ArtifactDescriptorQuery(String id, VersionRange versionRange, String format, IArtifactRepository repository) { + this.id = id; + this.range = versionRange; + this.format = format; + this.repository = repository; + } + + public ArtifactDescriptorQuery() { + //matches everything + } + + /** + * The query will match candidate descriptors where + * new ArtifactDescriptor(descriptor).equals(new ArtifactDescriptor(candidate)) + * @param descriptor + */ + public ArtifactDescriptorQuery(IArtifactDescriptor descriptor) { + this.descriptor = (descriptor.getClass() == ArtifactDescriptor.class) ? (ArtifactDescriptor) descriptor : new ArtifactDescriptor(descriptor); + } + + public boolean isMatch(IArtifactDescriptor candidate) { + if (descriptor != null) + return matchDescriptor(candidate); + + if (id != null && !id.equals(candidate.getArtifactKey().getId())) + return false; + + if (range != null && !range.isIncluded(candidate.getArtifactKey().getVersion())) + return false; + + if (format != null && !format.equals(candidate.getProperty(IArtifactDescriptor.FORMAT))) + return false; + + if (repository != null && repository != candidate.getRepository()) + return false; + + return true; + } + + protected boolean matchDescriptor(IArtifactDescriptor candidate) { + ArtifactDescriptor candidateDescriptor = (candidate.getClass() == ArtifactDescriptor.class) ? (ArtifactDescriptor) candidate : new ArtifactDescriptor(candidate); + return descriptor.equals(candidateDescriptor); + } + + public Boolean getExcludeArtifactDescriptors() { + return Boolean.FALSE; + } + + public Boolean getExcludeArtifactKeys() { + return Boolean.TRUE; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/ArtifactKeyQuery.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/ArtifactKeyQuery.java new file mode 100644 index 000000000..0d48ccabf --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/ArtifactKeyQuery.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.p2.repository.artifact; + +import org.eclipse.equinox.p2.metadata.VersionRange; + +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.MatchQuery; + +/** + * An IArtifactQuery returning matching IArtifactKey objects. + * @since 2.0 + */ +public class ArtifactKeyQuery extends MatchQuery { + public static final ArtifactKeyQuery ALL_KEYS = new ArtifactKeyQuery(); + + private String id; + private String classifier; + private VersionRange range; + private IArtifactKey artifactKey; + + /** + * Pass the id and/or version range to match IArtifactKeys against. + * Passing null results in matching any id/version + * @param classifier The artifact key classifier, or null + * @param id The artifact key id, or null + * @param range A version range, or null + */ + public ArtifactKeyQuery(String classifier, String id, VersionRange range) { + this.id = id; + this.classifier = classifier; + this.range = range; + } + + public ArtifactKeyQuery() { + //matches everything + } + + public ArtifactKeyQuery(IArtifactKey key) { + this.artifactKey = key; + } + + public boolean isMatch(IArtifactKey key) { + if (artifactKey != null) + return matchKey(key); + + if (classifier != null && !key.getClassifier().equals(classifier)) + return false; + + if (id != null && !key.getId().equals(id)) + return false; + + if (range != null && !range.isIncluded(key.getVersion())) + return false; + + return true; + } + + protected boolean matchKey(IArtifactKey candidate) { + return artifactKey.equals(candidate); + } + + // We are interested in IArtifactKey objects + public Boolean getExcludeArtifactKeys() { + return Boolean.FALSE; + } + + // We are not interested in IArtifactDescriptor objects + public Boolean getExcludeArtifactDescriptors() { + return Boolean.TRUE; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactDescriptor.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactDescriptor.java new file mode 100644 index 000000000..4d64628d3 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactDescriptor.java @@ -0,0 +1,109 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.artifact; + +import java.util.Map; +import org.eclipse.equinox.p2.metadata.IArtifactKey; + +/** + * An artifact descriptor describes an artifact stored in some artifact repository. The + * descriptor defines the artifact it contains, as well as any processing steps that + * must be performed when the artifact is transferred out of the repository (such + * as decompression, error checking, etc). + * + * @since 2.0 + */ +public interface IArtifactDescriptor { + + /** + * An artifact descriptor property (value "download.size") indicating the number + * of bytes that will be transferred when this artifact is transferred out of the repository. + */ + public static final String DOWNLOAD_SIZE = "download.size"; //$NON-NLS-1$ + /** + * An artifact descriptor property (value "artifact.size") indicating the size in + * bytes of the artifact in its native format (after processing steps have been applied). + */ + public static final String ARTIFACT_SIZE = "artifact.size"; //$NON-NLS-1$ + /** + * An artifact descriptor property (value "download.md5") indicating the MD5 + * checksum of the artifact bytes that are transferred. + */ + public static final String DOWNLOAD_MD5 = "download.md5"; //$NON-NLS-1$ + /** + * An artifact descriptor property (value "download.contentType") indicating the + * content type of the artifact bytes that are transferred. + */ + public static final String DOWNLOAD_CONTENTTYPE = "download.contentType"; //$NON-NLS-1$ + /** + * An content type (value "application/zip") indicating the content is a zip file. + */ + public static final String TYPE_ZIP = "application/zip"; //$NON-NLS-1$ + /** + * An artifact descriptor property (value "artifact.md5") indicating the MD5 + * checksum of the artifact bytes in its native format (after processing steps have + * been applied). + */ + public static final String ARTIFACT_MD5 = "artifact.md5"; //$NON-NLS-1$ + + /** + * An artifact descriptor property (value "format") indicating the storage format + * of the artifact in the repository. + * @see #FORMAT_PACKED + */ + public static final String FORMAT = "format"; //$NON-NLS-1$ + + /** + * A property value for the {@link #FORMAT} artifact descriptor property (value "packed") + * indicating the storage format is using pack200 compression. + * @see #FORMAT + */ + public static final String FORMAT_PACKED = "packed"; //$NON-NLS-1$ + + /** + * Return the key for the artifact described by this descriptor. + * @return the key associated with this descriptor + */ + public abstract IArtifactKey getArtifactKey(); + + /** + * Return the value of the given property in this descriptor null + * is returned if no such property exists + * @param key the property key to look for + * @return the value of the given property or null + */ + public abstract String getProperty(String key); + + /** + * Returns a read-only collection of the properties of the artifact descriptor. + * @return the properties of this artifact descriptor. + */ + public Map getProperties(); + + /** + * Return the list of processing steps associated with this descriptor. + * An empty set of steps implies that this descriptor describes a complete + * copy of the artifact in its native form. If one or more steps are present, + * they may be performed when the artifact is transferred from the repository + * that contains it. + * + * @return the list of processing steps for this descriptor + */ + public abstract IProcessingStepDescriptor[] getProcessingSteps(); + + /** + * Return the artifact repository that holds the artifact described by this descriptor. + * null is returned if this descriptor is not held in a repository. + * + * @return the repository holding this artifact or null if none. + */ + public abstract IArtifactRepository getRepository(); +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactRepository.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactRepository.java new file mode 100644 index 000000000..fd442f9c1 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactRepository.java @@ -0,0 +1,142 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.artifact; + +import java.io.OutputStream; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.AbstractArtifactRepository; + +/** + * A repository containing artifacts. + *

    + * This interface is not intended to be implemented by clients. Artifact repository + * implementations must subclass {@link AbstractArtifactRepository} rather than + * implementing this interface directly. + *

    + * @noimplement This interface is not intended to be implemented by clients. + * @since 2.0 + */ +public interface IArtifactRepository extends IRepository { + + /** + * The return code to use when a client could/should retry a failed getArtifact() operation. + * For example, the repository may have additional mirrors that could be consulted. + */ + public static int CODE_RETRY = 13; + + /** + * Create an instance of IArtifactDescriptor based on the given key + * @param key + * @return a new instanceof of IArtifactDescriptor + */ + public IArtifactDescriptor createArtifactDescriptor(IArtifactKey key); + + /** + * Add the given descriptor to the set of descriptors in this repository. This is + * a relatively low-level operation that should be used only when the actual related + * content is in this repository and the given descriptor accurately describes + * that content. + * @param descriptor the descriptor to add. + */ + public void addDescriptor(IArtifactDescriptor descriptor); + + /** + * Add the given artifact descriptors to this repository + * @param descriptors the artifact descriptors to add + */ + public void addDescriptors(IArtifactDescriptor[] descriptors); + + /** + * Returns true if this repository contains the given descriptor. + * @param descriptor the descriptor to query + * @return true if the given descriptor is already in this repository + */ + public boolean contains(IArtifactDescriptor descriptor); + + /** + * Returns true if this repository contains the given artifact key. + * @param key the key to query + * @return true if the given key is already in this repository + */ + public boolean contains(IArtifactKey key); + + /** + * Write to the given output stream the bytes represented by the artifact descriptor processed by the processing steps of the given descriptor. + */ + public IStatus getArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor); + + /** + * Write to the given output stream the bytes represented by the artifact descriptor without processing by the steps of the given descriptor. + */ + public IStatus getRawArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor); + + /** + * Return the set of artifact descriptors describing the ways that this repository + * can supply the artifact associated with the given artifact key + * @param key the artifact key to lookup + * @return the descriptors associated with the given key + */ + public IArtifactDescriptor[] getArtifactDescriptors(IArtifactKey key); + + /** + * Executes the given artifact requests on this byte server. + * @param requests The artifact requests + * @param monitor + * @return a status object that is OK if requests were + * processed successfully. Otherwise, a status indicating information, + * warnings, or errors that occurred while executing the artifact requests + */ + public IStatus getArtifacts(IArtifactRequest[] requests, IProgressMonitor monitor); + + /** + * Open an output stream to which a client can write the data for the given + * artifact descriptor. + * @param descriptor the descriptor describing the artifact data to be written to the + * resultant stream + * @return the stream to which the artifact content can be written. The returned output + * stream may implement IStateful. + * @throws ProvisionException if the output stream could not be created. Reasons include: + *
      + *
    • An I/O exception occurred (@link {@link ProvisionException#REPOSITORY_FAILED_WRITE}) .
    • + *
    • An artifact already exists at that location ({@link ProvisionException#ARTIFACT_EXISTS}).
    • + *
    + */ + public OutputStream getOutputStream(IArtifactDescriptor descriptor) throws ProvisionException; + + /** + * Returns a queryable that can be queried for artifact descriptors contained in this repository + * @return The queryable of artifact descriptors + */ + public IQueryable descriptorQueryable(); + + /** + * Remove the all keys, descriptors, and contents from this repository. + */ + public void removeAll(); + + /** + * Remove the given descriptor and its corresponding content in this repository. + * @param descriptor the descriptor to remove. + */ + public void removeDescriptor(IArtifactDescriptor descriptor); + + /** + * Remove the given key and all related content and descriptors from this repository. + * @param key the key to remove. + */ + public void removeDescriptor(IArtifactKey key); + +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactRepositoryManager.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactRepositoryManager.java new file mode 100644 index 000000000..c86defc10 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactRepositoryManager.java @@ -0,0 +1,150 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.artifact; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.net.URI; +import java.util.Map; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.IRepositoryManager; + +/** + * A metadata repository manager is used to create, access, and manipulate + * {@link IArtifactRepository} instances. See {@link IRepositoryManager} + * for a general description of the characteristics of repository managers. + * + * @noimplement This interface is not intended to be implemented by clients. + * @since 2.0 + */ +public interface IArtifactRepositoryManager extends IRepositoryManager { + /** + * The name used for obtaining a reference to the metadata repository manager service + */ + public static final String SERVICE_NAME = IArtifactRepositoryManager.class.getName(); + + public static final IArtifactRequest[] NO_ARTIFACT_REQUEST = new IArtifactRequest[0]; + + /** + * Repository type for a simple repository based on a URL or local file system location. + */ + public static final String TYPE_SIMPLE_REPOSITORY = "org.eclipse.equinox.p2.artifact.repository.simpleRepository"; //$NON-NLS-1$ + public static final String TYPE_COMPOSITE_REPOSITORY = "org.eclipse.equinox.p2.artifact.repository.compositeRepository"; //$NON-NLS-1$ + + /** + * Return a new request to mirror the given artifact into the destination repository. + * @param key the artifact to mirror + * @param destination the destination where the artifact will be mirrored + * @param destinationDescriptorProperties additional properties for use in creating the repository's ArtifactDescriptor, + * or null to indicate no additional properties are needed + * @param destinationRepositoryProperties additional repository specific properties for use in creating the repositor's ArtifactDescriptor, + * , or null to indicate no additional properties are needed + * @return the newly created request object + */ + public IArtifactRequest createMirrorRequest(IArtifactKey key, IArtifactRepository destination, Map destinationDescriptorProperties, Map destinationRepositoryProperties); + + /** + * Creates and returns a new empty artifact repository of the given type at + * the given location. + *

    + * The resulting repository is added to the list of repositories tracked by + * the repository manager. Clients must make a subsequent call to {@link #removeRepository(URI)} + * if they do not want the repository manager to remember the repository for subsequent + * load attempts. + *

    + * + * @param location the absolute location for the new repository + * @param name the name of the new repository + * @param type the kind of repository to create + * @param properties the properties to set on the repository + * @return the newly created repository + * @throws ProvisionException if the repository could not be created. Reasons include: + *
      + *
    • The repository type is unknown.
    • + *
    • There was an error writing to the given repository location.
    • + *
    • A repository already exists at that location.
    • + *
    + */ + public IArtifactRepository createRepository(URI location, String name, String type, Map properties) throws ProvisionException; + + /** + * Loads the repository at the given location. The location is expected to contain + * data that describes a valid artifact repository of a known type. If this manager + * already knows a repository at the given location then that repository is returned. + *

    + * The resulting repository is added to the list of repositories tracked by + * the repository manager. Clients must make a subsequent call to {@link #removeRepository(URI)} + * if they do not want the repository manager to remember the repository for subsequent + * load attempts. + *

    + * + * @param location the absolute location in which to look for a repository description + * @param monitor a progress monitor, or null if progress + * reporting is not desired + * @return a repository object for the given location + * @throws ProvisionException if the repository could not be created. Reasons include: + *
      + *
    • There is no existing repository at that location.
    • + *
    • The repository at that location could not be read.
    • + *
    + */ + public IArtifactRepository loadRepository(URI location, IProgressMonitor monitor) throws ProvisionException; + + /** + * Loads the repository at the given location. The location is expected to contain + * data that describes a valid artifact repository of a known type. If this manager + * already knows a repository at the given location then that repository is returned. + *

    + * The resulting repository is added to the list of repositories tracked by + * the repository manager. Clients must make a subsequent call to {@link #removeRepository(URI)} + * if they do not want the repository manager to remember the repository for subsequent + * load attempts. + *

    + *

    + * The flags passed in should be taken as a hint for the type of repository to load. If + * the manager cannot load a repository that satisfies these hints, it can fail fast. + *

    + * @param location the absolute location in which to look for a repository description + * @param flags - bit-wise or of flags to consider when loading the repository + * (currently only {@link IRepositoryManager#REPOSITORY_HINT_MODIFIABLE} is supported) + * @param monitor a progress monitor, or null if progress + * reporting is not desired + * @return a repository object for the given location + * @throws ProvisionException if the repository could not be created. Reasons include: + *
      + *
    • There is no existing repository at that location.
    • + *
    • The repository at that location could not be read.
    • + *
    + * @see IRepositoryManager#REPOSITORY_HINT_MODIFIABLE + */ + public IArtifactRepository loadRepository(URI location, int flags, IProgressMonitor monitor) throws ProvisionException; + + /** + * Refreshes the repository corresponding to the given URL. This method discards + * any cached state held by the repository manager and reloads the repository + * contents. The provided repository location must already be known to the repository + * manager. + * + * @param location The absolute location of the repository to refresh + * @param monitor a progress monitor, or null if progress + * reporting is not desired + * @return The refreshed metadata repository + * @throws ProvisionException if the repository could not be created. Reasons include: + *
      + *
    • The location is not known to the repository manager.
    • + *
    • There is no existing repository at that location.
    • + *
    • The repository at that location could not be read.
    • + *
    + */ + public IArtifactRepository refreshRepository(URI location, IProgressMonitor monitor) throws ProvisionException; + +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactRequest.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactRequest.java new file mode 100644 index 000000000..bced2464c --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IArtifactRequest.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.artifact; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.p2.metadata.IArtifactKey; + +/** + * Represents a request to transfer an artifact from an artifact repository. When the + * request is executed against a repository, it will be executed and the result + * of the execution will become available. + * + * @see IArtifactRepositoryManager#createMirrorRequest(IArtifactKey, IArtifactRepository, java.util.Map, java.util.Map) + * @see IArtifactRepository#getArtifacts(IArtifactRequest[], IProgressMonitor) + * @noimplement This interface is not intended to be implemented by clients. + * @since 2.0 + */ +public interface IArtifactRequest { + + /** + * Returns the key for the artifact that is being requested + * + * @return The requested artifact key + */ + public IArtifactKey getArtifactKey(); + + /** + * Returns the result of the executed artifact request, or null if + * the request has never been executed. Artifact requests are executed by invoking + * {@link IArtifactRepository#getArtifacts(IArtifactRequest[], IProgressMonitor)}. + * + * @return The result of the previous perform call, or null + */ + public IStatus getResult(); +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IFileArtifactRepository.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IFileArtifactRepository.java new file mode 100644 index 000000000..78a7701d3 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IFileArtifactRepository.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.artifact; + +import java.io.File; +import org.eclipse.equinox.p2.metadata.IArtifactKey; + +/** + * @since 2.0 + */ +public interface IFileArtifactRepository extends IArtifactRepository { + /** + * Return the location of the full local file corresponding to the given + * artifact key to the given key, or null if not available. + * + * @return the location of the requested artifact ornull if not available + */ + public File getArtifactFile(IArtifactKey key); + + /** + * Return the location of the local file corresponding to the given + * artifact descriptor, or null if not available. + * + * @return the location of the requested descriptor ornull if not available + */ + public File getArtifactFile(IArtifactDescriptor descriptor); +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IProcessingStepDescriptor.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IProcessingStepDescriptor.java new file mode 100644 index 000000000..5b45e0279 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/IProcessingStepDescriptor.java @@ -0,0 +1,45 @@ +/******************************************************************************* +* Copyright (c) 2010 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +******************************************************************************/ +package org.eclipse.equinox.p2.repository.artifact; + +/** + * Describes a processing step. Processing steps are pieces of code that participate + * in the the transfer of an artifact between artifact repositories. A step may alter + * the shape of the artifact from its storage format in the repository (such as performing + * compression), or it may perform additional checks on the transferred bytes such as + * checksums or signature verification. + * + * @see IArtifactDescriptor#getProcessingSteps() + * @since 2.0 + */ +public interface IProcessingStepDescriptor { + + /** + * Returns the fully qualified id of the processing step extension. + * + * @return The fully qualified processing step extension id + */ + public abstract String getProcessorId(); + + public abstract String getData(); + + /** + * Returns whether the successful execution of this processing step is + * required for the transfer to be successful. If the processing step extension + * is not installed, or fails to execute, then the artifact transfer will fail if the + * step is required. Failure of optional steps will result in warnings but not prevent + * the transfer from succeeding. + * + * @return true if the transfer will fail if this step does not succeed, + * and false otherwise + */ + public abstract boolean isRequired(); + +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/AbstractArtifactRepository.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/AbstractArtifactRepository.java new file mode 100644 index 000000000..fd7bddb67 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/AbstractArtifactRepository.java @@ -0,0 +1,89 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.artifact.spi; + +import org.eclipse.equinox.p2.repository.spi.AbstractRepository; + +import java.io.OutputStream; +import java.net.URI; +import java.util.Map; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.*; + +/** + * The common base class for all artifact repository implementations. Clients must + * subclass this class to create their own repository implementations. + *

    + * This base class provides default implementations of all methods that modify the repository. + * These default methods throw an exception if {@link #isModifiable()} returns false. + * Therefore a client can implement a read-only repository by overriding only the abstract methods. + * @since 2.0 + */ +public abstract class AbstractArtifactRepository extends AbstractRepository implements IArtifactRepository { + + protected AbstractArtifactRepository(String name, String type, String version, URI location, String description, String provider, Map properties) { + super(name, type, version, location, description, provider, properties); + } + + public abstract boolean contains(IArtifactDescriptor descriptor); + + public abstract boolean contains(IArtifactKey key); + + public abstract IStatus getArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor); + + public abstract IArtifactDescriptor[] getArtifactDescriptors(IArtifactKey key); + + public abstract IStatus getArtifacts(IArtifactRequest[] requests, IProgressMonitor monitor); + + public abstract OutputStream getOutputStream(IArtifactDescriptor descriptor) throws ProvisionException; + + public void addDescriptor(IArtifactDescriptor descriptor) { + assertModifiable(); + } + + public void addDescriptors(IArtifactDescriptor[] descriptors) { + assertModifiable(); + } + + public void removeDescriptor(IArtifactDescriptor descriptor) { + assertModifiable(); + } + + public void removeDescriptor(IArtifactKey key) { + assertModifiable(); + } + + public void removeAll() { + assertModifiable(); + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof AbstractArtifactRepository)) { + return false; + } + if (URIUtil.sameURI(getLocation(), ((AbstractArtifactRepository) o).getLocation())) + return true; + return false; + } + + public int hashCode() { + return (this.getLocation().toString().hashCode()) * 87; + } + + public IArtifactDescriptor createArtifactDescriptor(IArtifactKey key) { + return new ArtifactDescriptor(key); + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/ArtifactDescriptor.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/ArtifactDescriptor.java new file mode 100644 index 000000000..8f82ba1a0 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/ArtifactDescriptor.java @@ -0,0 +1,145 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.artifact.spi; + +import java.util.Arrays; +import java.util.Map; +import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.*; + +/** + * This represents information about a given artifact stored on a particular byte server. + * @since 2.0 + */ +public class ArtifactDescriptor implements IArtifactDescriptor { + private static final IProcessingStepDescriptor[] EMPTY_STEPS = new ProcessingStepDescriptor[0]; + + protected IArtifactKey key; // The key associated with this artifact + + // The list of post processing steps that must be applied one the artifact once it + // has been downloaded (e.g, unpack, then md5 checksum, then...) + protected IProcessingStepDescriptor[] processingSteps = EMPTY_STEPS; + + protected Map properties = new OrderedProperties(); + protected transient IArtifactRepository repository; + + public ArtifactDescriptor(IArtifactDescriptor base) { + super(); + key = base.getArtifactKey(); + processingSteps = base.getProcessingSteps(); + properties.putAll(base.getProperties()); + repository = base.getRepository(); + } + + public ArtifactDescriptor(ArtifactDescriptor base) { + super(); + key = base.key; + processingSteps = base.processingSteps; + properties.putAll(base.properties); + repository = base.repository; + } + + public ArtifactDescriptor(IArtifactKey key) { + super(); + this.key = key; + } + + public IArtifactKey getArtifactKey() { + return key; + } + + public String getProperty(String propertyKey) { + return properties.get(propertyKey); + } + + public void setProperty(String key, String value) { + if (value == null) + properties.remove(key); + else + properties.put(key, value); + } + + public void addProperties(Map additionalProperties) { + properties.putAll(additionalProperties); + } + + /** + * Returns a read-only collection of the properties of the artifact descriptor. + * @return the properties of this artifact descriptor. + */ + public Map getProperties() { + return OrderedProperties.unmodifiableProperties(properties); + } + + public IProcessingStepDescriptor[] getProcessingSteps() { + return processingSteps; + } + + public void setProcessingSteps(IProcessingStepDescriptor[] value) { + processingSteps = value == null ? EMPTY_STEPS : value; + } + + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + + // Other implementations of IArtifactDescriptor must not be considered equal + if (!(obj.getClass().equals(getClass()))) + return false; + + ArtifactDescriptor other = (ArtifactDescriptor) obj; + if (key == null) { + if (other.getArtifactKey() != null) + return false; + } else if (!key.equals(other.getArtifactKey())) + return false; + + if (!Arrays.equals(processingSteps, other.getProcessingSteps())) + return false; + + String format = getProperty(FORMAT); + String otherFormat = other.getProperty(FORMAT); + if (format != null ? !format.equals(otherFormat) : otherFormat != null) + return false; + + return true; + } + + public int hashCode() { + String format = getProperty(FORMAT); + + final int prime = 31; + int result = 1; + result = prime * result + ((key == null) ? 0 : key.hashCode()); + result = prime * result + Arrays.asList(processingSteps).hashCode(); + result = prime * result + (format != null ? format.hashCode() : 0); + return result; + } + + public IArtifactRepository getRepository() { + return repository; + } + + public void setRepository(IArtifactRepository value) { + repository = value; + } + + public String toString() { + String format = getProperty(IArtifactDescriptor.FORMAT); + if (format == null) + return "canonical: " + key.toString(); //$NON-NLS-1$ + return format + ": " + key.toString(); //$NON-NLS-1$ + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/ArtifactRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/ArtifactRepositoryFactory.java new file mode 100644 index 000000000..ead8d661c --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/ArtifactRepositoryFactory.java @@ -0,0 +1,99 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.artifact.spi; + +import java.net.URI; +import java.util.Map; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; + +/** + * An artifact repository factory is responsible for creating and loading instances + * of a particular type of artifact repository. Factories are provided via the + * org.eclipse.equinox.p2.artifact.repository.artifactRepositories extension point. + * @since 2.0 + */ +public abstract class ArtifactRepositoryFactory { + + private IProvisioningAgent agent; + + /** + * Creates and returns a new empty artifact repository of the given type at + * the given location. + * + * @param location the location for the new repository + * @param name the name of the new repository + * @param type the kind of repository to create + * @param properties the properties to set on the repository + * @return the newly created repository + * @throws ProvisionException if the repository could not be created. Reasons include: + *

      + *
    • The repository type is unknown.
    • + *
    • There was an error writing to the given repository location.
    • + *
    • A repository already exists at that location.
    • + *
    + */ + public abstract IArtifactRepository create(URI location, String name, String type, Map properties) throws ProvisionException; + + /** + * Returns the provisioning agent associated with this factory, or null + * if this factory is not associated with an agent. + * @return The provisioning agent, or null + */ + protected IProvisioningAgent getAgent() { + return agent; + } + + /** + * Loads and returns the repository of this factory's type at the given location. + *

    + * The error code returned in the case of failure is significant. In particular an + * error code of {@link ProvisionException#REPOSITORY_FAILED_READ} indicates + * that the location definitely identifies a repository of this type, but an error occurred + * while loading the repository. The repository manager will not attempt to load + * a repository from that location using any other factory. An error code of + * {@link ProvisionException#REPOSITORY_NOT_FOUND} indicates there is no + * repository of this type at the given location, and the repository manager is free + * to try again with a different repository factory. + *

    + *

    + * The flags passed in should be taken as a hint for the type of repository to load. If + * the factory knows it will not load a repository that satisfies these hints, it can fail + * fast and return null. + * @see IRepositoryManager#REPOSITORY_HINT_MODIFIABLE + *

    + * @param location the location in which to look for a repository description + * @param flags to consider while loading the repository + * @param monitor a progress monitor, or null if progress + * reporting is not desired + * @return a repository object for the given location + * @throws ProvisionException if the repository could not be created. Reasons include: + *
      + *
    • There is no existing repository at that location.
    • + *
    • The repository at that location could not be read.
    • + *
    + */ + public abstract IArtifactRepository load(URI location, int flags, IProgressMonitor monitor) throws ProvisionException; + + /** + * Sets the provisioning agent associated with this repository factory. This method + * is called by the provisioning agent to provide access to the agent instance. This + * method is not intended to be called by clients. + * + * @param agent The provisioning agent + */ + public void setAgent(IProvisioningAgent agent) { + this.agent = agent; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/ProcessingStepDescriptor.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/ProcessingStepDescriptor.java new file mode 100644 index 000000000..95261f4ce --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/artifact/spi/ProcessingStepDescriptor.java @@ -0,0 +1,103 @@ +/******************************************************************************* +* Copyright (c) 2007, 2009 compeople AG and others. +* All rights reserved. This program and the accompanying materials +* are made available under the terms of the Eclipse Public License v1.0 +* which accompanies this distribution, and is available at +* http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* compeople AG (Stefan Liebig) - initial API and implementation +*******************************************************************************/ +package org.eclipse.equinox.p2.repository.artifact.spi; + +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; + +/** + * @since 2.0 + */ +public class ProcessingStepDescriptor implements IProcessingStepDescriptor { + + private final String processorId; //the operation to be applied (e.g: unpack, md5, signature verification, etc.) + private final String data; //data requested for the processing (eg. expected checksum) + private final boolean required; //whether the step is optional or not + + /** + * Create a processing step description. + * + * @param processorId + * @param data + * @param required + */ + public ProcessingStepDescriptor(String processorId, String data, boolean required) { + super(); + this.processorId = processorId; + this.data = data; + this.required = required; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor#getProcessorId() + */ + public String getProcessorId() { + return processorId; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor#getData() + */ + public String getData() { + return data; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor#isRequired() + */ + public boolean isRequired() { + return required; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((data == null) ? 0 : data.hashCode()); + result = prime * result + ((processorId == null) ? 0 : processorId.hashCode()); + result = prime * result + (required ? 1231 : 1237); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof IProcessingStepDescriptor)) + return false; + final IProcessingStepDescriptor other = (IProcessingStepDescriptor) obj; + if (data == null) { + if (other.getData() != null) + return false; + } else if (!data.equals(other.getData())) + return false; + if (processorId == null) { + if (other.getProcessorId() != null) + return false; + } else if (!processorId.equals(other.getProcessorId())) + return false; + if (required != other.isRequired()) + return false; + return true; + } + + /** + * Returns a string representation of this descriptor for debugging purposes only. + */ + public String toString() { + return "Processor: " + processorId + (required ? "(req)" : "(notReq)") + " ,data: " + data; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/IMetadataRepository.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/IMetadataRepository.java new file mode 100644 index 000000000..88be97f9d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/IMetadataRepository.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.metadata; + +import java.net.URI; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.spi.AbstractMetadataRepository; + +/** + * A metadata repository stores information about a set of installable units + *

    + * This interface is not intended to be implemented by clients. Metadata repository + * implementations must subclass {@link AbstractMetadataRepository} rather than + * implementing this interface directly. + *

    + * @noimplement This interface is not intended to be implemented by clients. + * @since 2.0 + */ +public interface IMetadataRepository extends IRepository { + + /** + * Add the given installable units to this repository + * @param installableUnits the installable units to add + */ + public void addInstallableUnits(IInstallableUnit[] installableUnits); + + /** + * Adds a reference to another repository to this repository. When a repository + * is loaded by {@link IMetadataRepositoryManager}, its references + * are automatically added to the repository manager's set of known repositories. + *

    + * Note that this method does not add the contents of the given + * repository to this repository, but merely adds the location of another + * repository to the metadata of this repository. + *

    + * The {@link IRepository#ENABLED} option flag controls whether the + * referenced repository should be marked as enabled when added to the repository + * manager. If this flag is set, the repository will be marked as enabled when + * added to the repository manager. If this flag is missing, the repository will + * be marked as disabled. + * + * @param location the location of the repository to add + * @param nickname The nickname of the repository, or null + * @param type the repository type (currently either {@link IRepository#TYPE_METADATA} + * or {@link IRepository#TYPE_ARTIFACT}). + * @param options bit-wise or of option constants (currently either + * {@link IRepository#ENABLED} or {@link IRepository#NONE}). + * @see IMetadataRepositoryManager#setEnabled(URI, boolean) + */ + public void addReference(URI location, String nickname, int type, int options); + + /** + * Removes all installable units that match the given query from this repository. + * + * @param installableUnits the installable units to remove + * @param monitor a progress monitor, or null if progress + * reporting is not desired + * @return true if any units were actually removed, and + * false otherwise + */ + public boolean removeInstallableUnits(IInstallableUnit[] installableUnits, IProgressMonitor monitor); + + /** + * Remove all installable units from this repository. + */ + public void removeAll(); + +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/IMetadataRepositoryManager.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/IMetadataRepositoryManager.java new file mode 100644 index 000000000..8862e6161 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/IMetadataRepositoryManager.java @@ -0,0 +1,157 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.metadata; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.net.URI; +import java.util.Map; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.IRepositoryManager; + +/** + * A metadata repository manager is used to create, access, and manipulate + * {@link IMetadataRepository} instances. See {@link IRepositoryManager} + * for a general description of the characteristics of repository managers. + * + * @noimplement This interface is not intended to be implemented by clients. + * @since 2.0 + */ +public interface IMetadataRepositoryManager extends IRepositoryManager { + /** + * The name used for obtaining a reference to the metadata repository manager service + */ + public static final String SERVICE_NAME = IMetadataRepositoryManager.class.getName(); + + /** + * Repository type for a simple repository based on a URL or local file system location. + */ + public static final String TYPE_SIMPLE_REPOSITORY = "org.eclipse.equinox.p2.metadata.repository.simpleRepository"; //$NON-NLS-1$ + public static final String TYPE_COMPOSITE_REPOSITORY = "org.eclipse.equinox.p2.metadata.repository.compositeRepository"; //$NON-NLS-1$ + + /** + * Creates and returns a new empty metadata repository of the given type at + * the given location. + *

    + * The resulting repository is added to the list of repositories tracked by + * the repository manager. Clients must make a subsequent call to {@link #removeRepository(URI)} + * if they do not want the repository manager to remember the repository for subsequent + * load attempts. + *

    + * + * @param location the absolute location for the new repository + * @param name the name of the new repository + * @param type the kind of repository to create + * @param properties the properties to set on the repository + * @return the newly created repository + * @throws ProvisionException if the repository could not be created. Reasons include: + *
      + *
    • The repository type is unknown.
    • + *
    • There was an error writing to the given repository location.
    • + *
    • A repository already exists at that location.
    • + *
    + */ + public IMetadataRepository createRepository(URI location, String name, String type, Map properties) throws ProvisionException; + + /** + * Loads a repository corresponding to the given URL. If a repository has + * previously been loaded at the given location, the same cached repository + * may be returned. + *

    + * The resulting repository is added to the list of repositories tracked by + * the repository manager. Clients must make a subsequent call to {@link #removeRepository(URI)} + * if they do not want the repository manager to remember the repository for subsequent + * load attempts. + *

    + * + * @param location The absolute location of the repository to load + * @param monitor a progress monitor, or null if progress + * reporting is not desired + * @return The loaded metadata repository + * @throws ProvisionException if the repository could not be created. Reasons include: + *
      + *
    • There is no existing repository at that location.
    • + *
    • The repository at that location could not be read.
    • + *
    + */ + public IMetadataRepository loadRepository(URI location, IProgressMonitor monitor) throws ProvisionException; + + /** + * Loads a repository corresponding to the given URL. If a repository has + * previously been loaded at the given location, the same cached repository + * may be returned. + *

    + * The resulting repository is added to the list of repositories tracked by + * the repository manager. Clients must make a subsequent call to {@link #removeRepository(URI)} + * if they do not want the repository manager to remember the repository for subsequent + * load attempts. + *

    + *

    + * The flags passed in should be taken as a hint for the type of repository to load. If + * the manager cannot load a repository that satisfies these hints, it can fail fast. + *

    + * @param location The absolute location of the repository to load + * @param flags - bit-wise or of flags to consider when loading the repository + * (currently only {@link IRepositoryManager#REPOSITORY_HINT_MODIFIABLE} is supported) + * @param monitor a progress monitor, or null if progress + * reporting is not desired + * @return The loaded metadata repository + * @throws ProvisionException if the repository could not be created. Reasons include: + *
      + *
    • There is no existing repository at that location.
    • + *
    • The repository at that location could not be read.
    • + *
    + * @see IRepositoryManager#REPOSITORY_HINT_MODIFIABLE + */ + public IMetadataRepository loadRepository(URI location, int flags, IProgressMonitor monitor) throws ProvisionException; + + /** + * Refreshes the repository corresponding to the given URL. This method discards + * any cached state held by the repository manager and reloads the repository + * contents. The provided repository location must already be known to the repository + * manager. + * + * @param location The absolute location of the repository to refresh + * @param monitor a progress monitor, or null if progress + * reporting is not desired + * @return The refreshed metadata repository + * @throws ProvisionException if the repository could not be refreshed. Reasons include: + *
      + *
    • The location is not known to the repository manager.
    • + *
    • There is no existing repository at that location.
    • + *
    • The repository at that location could not be read.
    • + *
    + */ + public IMetadataRepository refreshRepository(URI location, IProgressMonitor monitor) throws ProvisionException; + + /** + * Validates a given URL and returns a status indicating whether a valid repository is likely + * to be found at the given URL. Callers must assume that the validity of a + * repository location cannot be completely determined until an attempt to load + * the repository is made. + * + * @param location The absolute location of the repository to validate + * @param monitor a progress monitor, or null if progress + * reporting is not desired + * @return A status indicating whether a valid repository is likely located at the + * location. A status with severity OK indicates that the repository is + * likely to be loadable, or that as much validation as could be done was successful. + * Reasons for a non-OK status include: + *
      + *
    • The specified location is not a valid repository location.
    • + *
    • There is no existing repository at that location.
    • + *
    • The repository at that location could not be read.
    • + *
    + */ + public IStatus validateRepositoryLocation(URI location, IProgressMonitor monitor); +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/spi/AbstractMetadataRepository.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/spi/AbstractMetadataRepository.java new file mode 100644 index 000000000..e130ed70a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/spi/AbstractMetadataRepository.java @@ -0,0 +1,74 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.metadata.spi; + +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.p2.repository.spi.RepositoryReference; + +import java.net.URI; +import java.util.Map; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.spi.AbstractRepository; + +/** + * The common base class for all metadata repositories. + *

    + * Clients may subclass this class. + *

    + * @since 2.0 + */ +public abstract class AbstractMetadataRepository extends AbstractRepository implements IMetadataRepository { + + //TODO Consider removing from abstract class, this is currently an implementation detail of the simple metadata repo parser + public static class RepositoryState { + public String Name; + public String Type; + public Version Version; + public String Provider; + public String Description; + public URI Location; + public Map Properties; + public IInstallableUnit[] Units; + public RepositoryReference[] Repositories; + } + + public AbstractMetadataRepository() { + super("noName", "noType", "noVersion", null, null, null, null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + + //TODO Consider removing from abstract class, this is currently an implementation detail of the simple metadata repo parser + public abstract void initialize(RepositoryState state); + + protected AbstractMetadataRepository(String name, String type, String version, URI location, String description, String provider, Map properties) { + super(name, type, version, location, description, provider, properties); + } + + public void addInstallableUnits(IInstallableUnit[] installableUnit) { + assertModifiable(); + } + + public void addReference(URI repositoryLocation, String nickname, int repositoryType, int options) { + assertModifiable(); + } + + public void removeAll() { + assertModifiable(); + } + + public boolean removeInstallableUnits(IInstallableUnit[] installableUnits, IProgressMonitor monitor) { + assertModifiable(); + return false; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/spi/MetadataRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/spi/MetadataRepositoryFactory.java new file mode 100644 index 000000000..2dc550f1a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/metadata/spi/MetadataRepositoryFactory.java @@ -0,0 +1,119 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.metadata.spi; + +import java.net.URI; +import java.util.Map; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; + +/** + * A metadata repository factory is responsible for creating and loading instances + * of a particular type of metadata repository. Factories are provided via the + * org.eclipse.equinox.p2.metadata.repository.metadataRepositories extension point. + * @since 2.0 + */ +public abstract class MetadataRepositoryFactory { + private IProvisioningAgent agent; + + /** + * Creates and returns a new empty metadata repository of the given type at + * the given location. + * + * @param location the location for the new repository + * @param name the name of the new repository + * @param type the kind of repository to create + * @param properties the properties to set on the repository + * @return the newly created repository + * @throws ProvisionException if the repository could not be created. Reasons include: + *

      + *
    • The repository type is not supported by this factory.
    • + *
    • There was an error writing to the given repository location.
    • + *
    + */ + public abstract IMetadataRepository create(URI location, String name, String type, Map properties) throws ProvisionException; + + /** + * Returns the provisioning agent associated with this factory, or null + * if this factory is not associated with an agent. + * @return The provisioning agent, or null + */ + protected IProvisioningAgent getAgent() { + return agent; + } + + /** + * Loads a repository corresponding to the given URL. + *

    + * The error code returned in the case of failure is significant. In particular an + * error code of {@link ProvisionException#REPOSITORY_FAILED_READ} indicates + * that the location definitely identifies a repository of this type, but an error occurred + * while loading the repository. The repository manager will not attempt to load + * a repository from that location using any other factory. An error code of + * {@link ProvisionException#REPOSITORY_NOT_FOUND} indicates there is no + * repository of this type at the given location, and the repository manager is free + * to try again with a different repository factory. + *

    + *

    + * The flags passed in should be taken as a hint for the type of repository to load. If + * the factory knows it will not load a repository that satisfies these hints, it can fail + * fast and return null.
    + * See {@link IRepositoryManager#REPOSITORY_HINT_MODIFIABLE} + *

    + * @param location The location of the repository to load + * @param flags to consider while loading the repository + * @param monitor a progress monitor, or null if progress + * reporting is not desired + * @return The loaded metadata repository + * @throws ProvisionException if the repository could not be created. Reasons include: + *
      + *
    • There is no existing repository at that location.
    • + *
    • The repository at that location could not be read.
    • + *
    + */ + public abstract IMetadataRepository load(URI location, int flags, IProgressMonitor monitor) throws ProvisionException; + + /** + * Sets the provisioning agent associated with this repository factory. + * @param agent The provisioning agent + */ + public void setAgent(IProvisioningAgent agent) { + this.agent = agent; + } + + /** + * Validates a candidate repository URL and returns a status indicating the + * likelihood of a valid repository being located at the location. Implementors + * should make all attempts to validate the URL that can be made without + * actually loading the repository. The computation for this method must be + * significantly faster than loading the repository. Early detectable error + * conditions, such as the non-existence of the location, or an inability to read + * the location, should be determined in this method. + * + * @param location The location of the repository to validate + * @param monitor a progress monitor, or null if progress + * reporting is not desired + * @return A status indicating whether a valid repository is likely located at the + * location. A status with severity OK indicates that the repository is + * likely to be loadable, or that as much validation as could be done was successful. + * Reasons for a non-OK status include: + *
      + *
    • The specified location is not a valid repository location.
    • + *
    • There is no existing repository at that location.
    • + *
    • The repository at that location could not be read.
    • + *
    + */ + public abstract IStatus validate(URI location, IProgressMonitor monitor); +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/spi/AbstractRepository.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/spi/AbstractRepository.java new file mode 100644 index 000000000..5cb14b01f --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/spi/AbstractRepository.java @@ -0,0 +1,136 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.spi; + +import java.net.URI; +import java.util.Map; +import org.eclipse.core.runtime.PlatformObject; +import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; +import org.eclipse.equinox.p2.repository.IRepository; + +/** +* AbstractRepository defines common properties that may be provided by various kinds +* of repositories. +*

    +* Clients may extend this class. +*

    +* @param the type of object that can be queried for in this repository + * @since 2.0 +*/ +public abstract class AbstractRepository extends PlatformObject implements IRepository { + protected String description; + protected transient URI location; + protected String name; + protected Map properties = new OrderedProperties(); + protected String provider; + protected String type; + protected String version; + + protected AbstractRepository(String name, String type, String version, URI location, String description, String provider, Map properties) { + this.name = name; + this.type = type; + this.version = version; + this.location = location; + this.description = description == null ? "" : description; //$NON-NLS-1$ + this.provider = provider == null ? "" : provider; //$NON-NLS-1$ + if (properties != null) + this.properties.putAll(properties); + } + + /** + * Asserts that this repository is modifiable, throwing a runtime exception if + * it is not. This is suitable for use by subclasses when an attempt is made + * to write to a repository. + */ + protected void assertModifiable() { + if (!isModifiable()) + throw new UnsupportedOperationException("Repository not modifiable: " + location); //$NON-NLS-1$ + } + + /** + * Returns a brief description of the repository. + * @return the description of the repository. + */ + public synchronized String getDescription() { + return description; + } + + /** + * Returns the location of this repository. + * TODO: Should we use URL or URI? URL requires a protocol handler + * to be installed in Java. Can the URL have any protocol? + * @return the URL of the repository. + */ + public synchronized URI getLocation() { + return location; + } + + /** + * Returns the name of the repository. + * @return the name of the repository. + */ + public synchronized String getName() { + return name; + } + + /** + * Returns a read-only collection of the properties of the repository. + * @return the properties of this repository. + */ + public synchronized Map getProperties() { + return OrderedProperties.unmodifiableProperties(properties); + } + + /** + * Returns the name of the provider of the repository. + * @return the provider of this repository. + */ + public synchronized String getProvider() { + return provider; + } + + /** + * Returns a string representing the type of the repository. + * @return the type of the repository. + */ + public synchronized String getType() { + return type; + } + + /** + * Returns a string representing the version for the repository type. + * @return the version of the type of the repository. + */ + public synchronized String getVersion() { + return version; + } + + public boolean isModifiable() { + return false; + } + + public synchronized void setDescription(String description) { + this.description = description; + } + + public synchronized void setName(String value) { + this.name = value; + } + + public synchronized String setProperty(String key, String value) { + assertModifiable(); + return (value == null ? properties.remove(key) : properties.put(key, value)); + } + + public synchronized void setProvider(String provider) { + this.provider = provider; + } +} diff --git a/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/spi/RepositoryReference.java b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/spi/RepositoryReference.java new file mode 100644 index 000000000..b50398f41 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.repository/src/org/eclipse/equinox/p2/repository/spi/RepositoryReference.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.repository.spi; + +import java.net.URI; + +/** + * Serialization helper class for repository references. + * @since 2.0 + */ +public class RepositoryReference { + public URI Location; + public int Type; + public int Options; + public String Nickname; + + public RepositoryReference(URI location, String nickname, int type, int options) { + this.Location = location; + this.Type = type; + this.Options = options; + this.Nickname = nickname; + } + + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + RepositoryReference other = (RepositoryReference) obj; + if (Location == null) { + if (other.Location != null) + return false; + } else if (!Location.equals(other.Location)) + return false; + if (Type != other.Type) + return false; + return true; + } + + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((Location == null) ? 0 : Location.hashCode()); + result = prime * result + Type; + return result; + } + +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.tests.optimizers/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.tests.optimizers/META-INF/MANIFEST.MF index b453b2380..aca89fba1 100644 --- a/bundles/org.eclipse.equinox.p2.tests.optimizers/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.tests.optimizers/META-INF/MANIFEST.MF @@ -21,7 +21,6 @@ Import-Package: ie.wombat.jbdiff, org.eclipse.equinox.internal.p2.core.helpers, org.eclipse.equinox.internal.p2.metadata, org.eclipse.equinox.internal.p2.sar, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing, org.eclipse.equinox.internal.provisional.p2.metadata, org.eclipse.equinox.internal.provisional.p2.repository, diff --git a/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/optimizers/JBDiffStepTest.java b/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/optimizers/JBDiffStepTest.java index eb0a24997..5e06e758a 100644 --- a/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/optimizers/JBDiffStepTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/optimizers/JBDiffStepTest.java @@ -10,7 +10,11 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.optimizers; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; + +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; import java.io.*; import java.util.Arrays; @@ -19,10 +23,9 @@ import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.artifact.optimizers.jbdiff.JBDiffStep; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.tests.artifact.processors.ArtifactRepositoryMock; import org.eclipse.equinox.p2.tests.optimizers.TestData; @@ -47,8 +50,8 @@ public class JBDiffStepTest extends TestCase { IArtifactRepository repoMock = ArtifactRepositoryMock.getMock("testData/optimizers/eclipse-3.2.exe"); MockableJBDiffStep differ = new MockableJBDiffStep(repoMock); - ProcessingStepDescriptor stepDescriptor = new ProcessingStepDescriptor("id", "ns,cl,id1,1.0", true); - IArtifactKey key = new ArtifactKey("cl", "id1", new Version("1.1")); + IProcessingStepDescriptor stepDescriptor = new ProcessingStepDescriptor("id", "ns,cl,id1,1.0", true); + IArtifactKey key = new ArtifactKey("cl", "id1", Version.create("1.1")); ArtifactDescriptor descriptor = new ArtifactDescriptor(key); differ.initialize(stepDescriptor, descriptor); diff --git a/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/optimizers/JBDiffZipStepTest.java b/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/optimizers/JBDiffZipStepTest.java index 53fdbcf3b..b654cc923 100644 --- a/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/optimizers/JBDiffZipStepTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/optimizers/JBDiffZipStepTest.java @@ -10,7 +10,11 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.optimizers; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; + +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; import java.io.*; import java.util.Arrays; @@ -19,10 +23,9 @@ import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.artifact.optimizers.jbdiff.JBDiffZipStep; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.tests.artifact.processors.ArtifactRepositoryMock; import org.eclipse.equinox.p2.tests.optimizers.TestData; @@ -39,8 +42,8 @@ public class JBDiffZipStepTest extends TestCase { public void testDiffJdt32to33() throws IOException { IArtifactRepository repoMock = ArtifactRepositoryMock.getMock("testData/optimizers/org.eclipse.jdt_3.2.0.v20060605-1400.njar"); MockableJBDiffZipStep differ = new MockableJBDiffZipStep(repoMock); - ProcessingStepDescriptor stepDescriptor = new ProcessingStepDescriptor("id", "ns,cl,id1,1.0", true); - IArtifactKey key = new ArtifactKey("cl", "id1", new Version("1.1")); + IProcessingStepDescriptor stepDescriptor = new ProcessingStepDescriptor("id", "ns,cl,id1,1.0", true); + IArtifactKey key = new ArtifactKey("cl", "id1", Version.create("1.1")); ArtifactDescriptor descriptor = new ArtifactDescriptor(key); differ.initialize(stepDescriptor, descriptor); diff --git a/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/optimizers/JarDeltaOptimizerTest.java b/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/optimizers/JarDeltaOptimizerTest.java index e9c69085d..a53fc4cbc 100644 --- a/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/optimizers/JarDeltaOptimizerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/optimizers/JarDeltaOptimizerTest.java @@ -11,7 +11,11 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.optimizers; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; + +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; import java.io.*; import java.util.zip.ZipInputStream; @@ -20,11 +24,10 @@ import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.artifact.optimizers.jardelta.JarDeltaOptimizerStep; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.tests.artifact.processors.ArtifactRepositoryMock; import org.eclipse.equinox.p2.tests.optimizers.TestData; @@ -37,7 +40,7 @@ public class JarDeltaOptimizerTest extends TestCase { // IArtifactRepository repoMock = ArtifactRepositoryMock.getMock("testData/optimizers/testdata_1.0.0.1.jar"); // ProcessingStep step = new MockableJarDeltaOptimizerStep(repoMock); // ProcessingStepDescriptor stepDescriptor = new ProcessingStepDescriptor("id", "ns,cl,id1,1.0.0.1", true); - // IArtifactKey key = new ArtifactKey("ns", "cl", "id1", new Version("1.0.0.2")); + // IArtifactKey key = new ArtifactKey("ns", "cl", "id1", Version.create("1.0.0.2")); // ArtifactDescriptor descriptor = new ArtifactDescriptor(key); // step.initialize(stepDescriptor, descriptor); // ByteArrayOutputStream destination = new ByteArrayOutputStream(); @@ -55,8 +58,8 @@ public class JarDeltaOptimizerTest extends TestCase { public void testOptimization() throws IOException { IArtifactRepository repoMock = ArtifactRepositoryMock.getMock("testData/optimizers/testdata_1.0.0.1.jar"); ProcessingStep step = new MockableJarDeltaOptimizerStep(repoMock); - ProcessingStepDescriptor stepDescriptor = new ProcessingStepDescriptor("id", "ns,cl,id1,1.0.0.1", true); - IArtifactKey key = new ArtifactKey("cl", "id1", new Version("1.0.0.2")); + IProcessingStepDescriptor stepDescriptor = new ProcessingStepDescriptor("id", "ns,cl,id1,1.0.0.1", true); + IArtifactKey key = new ArtifactKey("cl", "id1", Version.create("1.0.0.2")); ArtifactDescriptor descriptor = new ArtifactDescriptor(key); step.initialize(stepDescriptor, descriptor); ByteArrayOutputStream destination = new ByteArrayOutputStream(); diff --git a/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/ArtifactRepositoryMock.java b/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/ArtifactRepositoryMock.java index fe1a13df9..49d63936f 100644 --- a/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/ArtifactRepositoryMock.java +++ b/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/ArtifactRepositoryMock.java @@ -14,8 +14,8 @@ import java.io.*; import java.lang.reflect.*; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; import org.eclipse.equinox.p2.tests.optimizers.TestActivator; /** diff --git a/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/JBPatchStepTest.java b/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/JBPatchStepTest.java index bceff17eb..29a6b2162 100644 --- a/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/JBPatchStepTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/JBPatchStepTest.java @@ -10,7 +10,11 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.processors; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; + +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; import java.io.*; import java.util.Arrays; @@ -19,11 +23,10 @@ import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.artifact.processors.jbdiff.JBPatchStep; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.tests.optimizers.TestData; /** @@ -35,8 +38,8 @@ public class JBPatchStepTest extends TestCase { public void testPatchEclipseExe32to33() throws IOException { IArtifactRepository repoMock = ArtifactRepositoryMock.getMock("testData/optimizers/eclipse-3.2.exe"); ProcessingStep patcher = new MockableJBPatchStep(repoMock); - ProcessingStepDescriptor descriptor = new ProcessingStepDescriptor("id", "ns,cl,id1,1.0", true); - IArtifactKey key = new ArtifactKey("cl", "id1", new Version("1.1")); + IProcessingStepDescriptor descriptor = new ProcessingStepDescriptor("id", "ns,cl,id1,1.0", true); + IArtifactKey key = new ArtifactKey("cl", "id1", Version.create("1.1")); ArtifactDescriptor context = new ArtifactDescriptor(key); patcher.initialize(descriptor, context); diff --git a/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/JBPatchZipStepTest.java b/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/JBPatchZipStepTest.java index 7eb16eb2b..61e0a92ed 100644 --- a/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/JBPatchZipStepTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/JBPatchZipStepTest.java @@ -10,7 +10,11 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.processors; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; + +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; import java.io.*; import java.util.Arrays; @@ -19,11 +23,10 @@ import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.artifact.processors.jbdiff.JBPatchZipStep; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.tests.optimizers.TestData; /** @@ -53,8 +56,8 @@ public class JBPatchZipStepTest extends TestCase { IArtifactRepository repoMock = ArtifactRepositoryMock.getMock("testData/optimizers/org.eclipse.jdt_3.2.0.v20060605-1400.njar"); ProcessingStep patcher = new MockableJBPatchZipStep(repoMock); - ProcessingStepDescriptor descriptor = new ProcessingStepDescriptor("id", "ns,cl,id1,1.0", true); - IArtifactKey key = new ArtifactKey("cl", "id1", new Version("1.1")); + IProcessingStepDescriptor descriptor = new ProcessingStepDescriptor("id", "ns,cl,id1,1.0", true); + IArtifactKey key = new ArtifactKey("cl", "id1", Version.create("1.1")); ArtifactDescriptor context = new ArtifactDescriptor(key); patcher.initialize(descriptor, context); diff --git a/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/JarDeltaProcessorTest.java b/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/JarDeltaProcessorTest.java index c2d251db0..8654d61e8 100644 --- a/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/JarDeltaProcessorTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.optimizers/src/org/eclipse/equinox/p2/tests/artifact/processors/JarDeltaProcessorTest.java @@ -11,7 +11,11 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.processors; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; + +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; import java.io.*; import java.util.zip.ZipInputStream; @@ -20,11 +24,10 @@ import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.artifact.processors.jardelta.JarDeltaProcessorStep; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.tests.optimizers.TestData; public class JarDeltaProcessorTest extends TestCase { @@ -40,8 +43,8 @@ public class JarDeltaProcessorTest extends TestCase { public void testProcessing() throws IOException { IArtifactRepository repoMock = ArtifactRepositoryMock.getMock("testData/optimizers/testdata_1.0.0.1.jar"); ProcessingStep step = new MockableJarDeltaProcessorStep(repoMock); - ProcessingStepDescriptor stepDescriptor = new ProcessingStepDescriptor("id", "ns,cl,id1,1.0.0.1", true); - IArtifactKey key = new ArtifactKey("cl", "id1", new Version("1.0.0.2")); + IProcessingStepDescriptor stepDescriptor = new ProcessingStepDescriptor("id", "ns,cl,id1,1.0.0.1", true); + IArtifactKey key = new ArtifactKey("cl", "id1", Version.create("1.0.0.2")); ArtifactDescriptor descriptor = new ArtifactDescriptor(key); step.initialize(stepDescriptor, descriptor); ByteArrayOutputStream destination = new ByteArrayOutputStream(); diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/All p2 UI tests.launch b/bundles/org.eclipse.equinox.p2.tests.ui/All p2 UI tests.launch index 319a62192..3d7b444d3 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/All p2 UI tests.launch +++ b/bundles/org.eclipse.equinox.p2.tests.ui/All p2 UI tests.launch @@ -1,4 +1,4 @@ - + @@ -39,7 +39,9 @@ - + + + @@ -51,18 +53,20 @@ - - + + - + + + - + diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.tests.ui/META-INF/MANIFEST.MF index e6da76398..36f1650b0 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.tests.ui/META-INF/MANIFEST.MF @@ -6,8 +6,7 @@ Bundle-Localization: plugin Bundle-SymbolicName: org.eclipse.equinox.p2.tests.ui Bundle-Version: 1.0.0.qualifier Bundle-RequiredExecutionEnvironment: J2SE-1.4 -Require-Bundle: org.eclipse.equinox.p2.tests;bundle-version="1.1.0", - org.eclipse.core.runtime;bundle-version="3.4.100", +Require-Bundle: org.eclipse.core.runtime;bundle-version="3.4.100", org.eclipse.ui;bundle-version="3.5.0", org.eclipse.equinox.p2.metadata;bundle-version="1.0.0", org.eclipse.equinox.p2.metadata.repository;bundle-version="1.0.100", @@ -18,4 +17,6 @@ Require-Bundle: org.eclipse.equinox.p2.tests;bundle-version="1.1.0", org.eclipse.equinox.p2.director;bundle-version="1.0.100", org.eclipse.equinox.p2.artifact.repository;bundle-version="1.0.100", org.junit;bundle-version="3.8.0", - org.eclipse.equinox.p2.repository;bundle-version="1.0.0" + org.eclipse.equinox.p2.repository;bundle-version="1.0.0", + org.eclipse.equinox.p2.tests;bundle-version="1.2.0" +Import-Package: org.eclipse.equinox.p2.operations diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/AbstractProvisioningUITest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/AbstractProvisioningUITest.java index 152aa9cf3..1c763fe31 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/AbstractProvisioningUITest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/AbstractProvisioningUITest.java @@ -10,29 +10,31 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; + +import org.eclipse.equinox.p2.metadata.IUpdateDescriptor; import java.io.File; import java.net.URI; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.*; +import org.eclipse.equinox.internal.p2.ui.model.ProfileElement; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner; -import org.eclipse.equinox.internal.provisional.p2.ui.model.ProfileElement; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProfileModificationOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProfileModificationJob; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; +import org.eclipse.equinox.p2.ui.Policy; +import org.eclipse.equinox.p2.ui.ProvisioningUI; /** * Abstract class to set up the colocated UI test repo @@ -59,25 +61,30 @@ public abstract class AbstractProvisioningUITest extends AbstractProvisioningTes protected IInstallableUnit upgrade; protected IInstallableUnit uninstalled; protected IInstallableUnit category; + private ProvisioningUI ui; protected void setUp() throws Exception { super.setUp(); - ProvisioningOperationRunner.suppressRestart(true); + ui = ProvisioningUI.getDefaultUI(); + ui = new ProvisioningUI(ui.getSession(), TESTPROFILE, ui.getPolicy()); + ui.getOperationRunner().suppressRestart(true); + // to squelch repo error reporting + ui.getPolicy().setRepositoriesVisible(false); profile = createProfile(TESTPROFILE); profileElement = new ProfileElement(null, TESTPROFILE); - install((top1 = createIU(TOPLEVELIU, new Version("1.0.0"))), true, false); + install((top1 = createIU(TOPLEVELIU, Version.create("1.0.0"))), true, false); install((top2 = createIU(TOPLEVELIU2)), true, false); install((nested = createIU(NESTEDIU)), false, false); install((locked = createIU(LOCKEDIU)), true, true); uninstalled = createIU(UNINSTALLEDIU); IUpdateDescriptor update = MetadataFactory.createUpdateDescriptor(TOPLEVELIU, new VersionRange("[1.0.0, 1.0.0]"), 0, "update description"); - upgrade = createIU(TOPLEVELIU, new Version(2, 0, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, false, update, NO_REQUIRES); + upgrade = createIU(TOPLEVELIU, Version.createOSGi(2, 0, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, false, update, NO_REQUIRES); - category = createNamedIU(CATEGORYIU, CATEGORYIU, new Version("1.0.0"), true); + category = createNamedIU(CATEGORYIU, CATEGORYIU, Version.create("1.0.0"), true); createTestMetdataRepository(new IInstallableUnit[] {top1, top2, uninstalled, upgrade}); - metaManager = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.context, IMetadataRepositoryManager.class.getName()); - artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.context, IArtifactRepositoryManager.class.getName()); + metaManager = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.context, IMetadataRepositoryManager.SERVICE_NAME); + artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.context, IArtifactRepositoryManager.SERVICE_NAME); File site = new File(TestActivator.getTestDataFolder().toString(), TEST_REPO_PATH); testRepoLocation = site.toURI(); metaManager.addRepository(testRepoLocation); @@ -99,22 +106,32 @@ public abstract class AbstractProvisioningUITest extends AbstractProvisioningTes return false; } + protected ProvisioningSession getSession() { + return ui.getSession(); + } + + protected ProvisioningUI getProvisioningUI() { + return ui; + } + + protected Policy getPolicy() { + return ui.getPolicy(); + } + protected IStatus install(IInstallableUnit iu, boolean root, boolean lock) throws ProvisionException { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {iu}); if (root) { - String rootProp = Policy.getDefault().getQueryContext().getVisibleInstalledIUProperty(); - if (rootProp != null) - req.setInstallableUnitProfileProperty(iu, rootProp, Boolean.toString(true)); + req.setInstallableUnitProfileProperty(iu, IProfile.PROP_PROFILE_ROOT_IU, Boolean.toString(true)); } if (lock) { - req.setInstallableUnitProfileProperty(iu, IInstallableUnit.PROP_PROFILE_LOCKED_IU, new Integer(IInstallableUnit.LOCK_UNINSTALL | IInstallableUnit.LOCK_UPDATE).toString()); + req.setInstallableUnitProfileProperty(iu, IProfile.PROP_PROFILE_LOCKED_IU, new Integer(IProfile.LOCK_UNINSTALL | IProfile.LOCK_UPDATE).toString()); } // Use an empty provisioning context to prevent repo access - ProvisioningPlan plan = ProvisioningUtil.getProvisioningPlan(req, new ProvisioningContext(new URI[] {}), getMonitor()); + IProvisioningPlan plan = getSession().getPlanner().getProvisioningPlan(req, new ProvisioningContext(new URI[] {}), getMonitor()); if (plan.getStatus().getSeverity() == IStatus.ERROR || plan.getStatus().getSeverity() == IStatus.CANCEL) return plan.getStatus(); - return ProvisioningUtil.performProvisioningPlan(plan, new DefaultPhaseSet(), profile, new ProvisioningContext(), getMonitor()); + return getSession().performProvisioningPlan(plan, new DefaultPhaseSet(), new ProvisioningContext(), getMonitor()); } protected IInstallableUnit createNamedIU(String id, String name, Version version, boolean isCategory) { @@ -123,13 +140,13 @@ public abstract class AbstractProvisioningUITest extends AbstractProvisioningTes iu.setVersion(version); iu.setProperty(IInstallableUnit.PROP_NAME, name); if (isCategory) - iu.setProperty(IInstallableUnit.PROP_TYPE_CATEGORY, Boolean.toString(true)); + iu.setProperty(InstallableUnitDescription.PROP_TYPE_CATEGORY, Boolean.toString(true)); return MetadataFactory.createInstallableUnit(iu); } - protected ProfileModificationOperation getLongTestOperation() { - return new ProfileModificationOperation("Test Operation", TESTPROFILE, null, null) { - protected IStatus doExecute(IProgressMonitor monitor) { + protected ProfileModificationJob getLongTestOperation() { + return new ProfileModificationJob("Test Operation", getSession(), TESTPROFILE, null, null) { + public IStatus runModal(IProgressMonitor monitor) { while (true) { // spin unless cancelled if (monitor.isCanceled()) diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/ElementUtilsTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/ElementUtilsTest.java index 81260cd65..c15ef96f2 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/ElementUtilsTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/ElementUtilsTest.java @@ -13,19 +13,17 @@ package org.eclipse.equinox.p2.tests.ui.actions; import java.net.URI; import java.net.URISyntaxException; -import java.util.*; +import java.util.ArrayList; +import java.util.List; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.IJobChangeListener; import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.model.ElementUtils; -import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.model.MetadataRepositories; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.model.*; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; @@ -59,34 +57,37 @@ public class ElementUtilsTest extends ProfileModificationActionTest { assertEquals(getMixedIUsAndElements().length, ElementUtils.elementsToIUs(getMixedIUsAndElements()).length); } - public void testUpdateUsingElements() throws ProvisionException, URISyntaxException { + public void testUpdateUsingElements() throws URISyntaxException { + ProvisioningSession session = getSession(); // Two visible repos, one is added, the other is not URI known1 = new URI("http://example.com/known1"); URI known2 = new URI("http://example.com/known2"); - ProvisioningUtil.addMetadataRepository(known1, false); + IMetadataRepositoryManager manager = session.getMetadataRepositoryManager(); + manager.addRepository(known1); // Add system repos that should not be known or affected by ElementUtils // One is an enabled system repo, one is disabled system repo URI uri = new URI("http://example.com/1"); URI uri2 = new URI("http://example.com/2"); - ProvisioningUtil.addMetadataRepository(uri, false); - ProvisioningUtil.setMetadataRepositoryProperty(uri, IRepository.PROP_SYSTEM, Boolean.toString(true)); - ProvisioningUtil.addMetadataRepository(uri2, false); - ProvisioningUtil.addArtifactRepository(uri2, false); - ProvisioningUtil.setMetadataRepositoryProperty(uri2, IRepository.PROP_SYSTEM, Boolean.toString(true)); - ProvisioningUtil.setColocatedRepositoryEnablement(uri2, false); + manager.addRepository(uri); + manager.setRepositoryProperty(uri, IRepository.PROP_SYSTEM, Boolean.toString(true)); + manager.addRepository(uri2); + session.getArtifactRepositoryManager().addRepository(uri2); + manager.setRepositoryProperty(uri2, IRepository.PROP_SYSTEM, Boolean.toString(true)); + manager.setEnabled(uri2, false); + session.getArtifactRepositoryManager().setEnabled(uri2, false); // The elements reflect all visible sites, but not system sites - MetadataRepositories root = new MetadataRepositories(Policy.getDefault()); + MetadataRepositories root = new MetadataRepositories(getProvisioningUI()); List children = new ArrayList(); - children.addAll(Arrays.asList(root.getChildren(root))); + children.add(new MetadataRepositoryElement(null, known1, true)); // Add known2, this is as if a user added it in the pref page children.add(new MetadataRepositoryElement(null, known2, true)); MetadataRepositoryElement[] elements = (MetadataRepositoryElement[]) children.toArray(new MetadataRepositoryElement[children.size()]); // Add a visible repo not known by the elements URI uri3 = new URI("http://example.com/3"); - ProvisioningUtil.addMetadataRepository(uri3, false); + manager.addRepository(uri3); // Now update the repo using the elements. // We expect known2 to get added because it was in the elements @@ -140,8 +141,8 @@ public class ElementUtilsTest extends ProfileModificationActionTest { display.sleep(); } - URI[] enabled = ProvisioningUtil.getMetadataRepositories(IRepositoryManager.REPOSITORIES_ALL); - URI[] disabled = ProvisioningUtil.getMetadataRepositories(IRepositoryManager.REPOSITORIES_DISABLED); + URI[] enabled = session.getMetadataRepositoryManager().getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); + URI[] disabled = session.getMetadataRepositoryManager().getKnownRepositories(IRepositoryManager.REPOSITORIES_DISABLED); boolean foundKnown1 = false; boolean foundKnown2 = false; @@ -180,11 +181,11 @@ public class ElementUtilsTest extends ProfileModificationActionTest { assertTrue("1.4", foundKnown2); // Enabled visible repo in elements was added // cleanup - ProvisioningUtil.removeMetadataRepository(known1); - ProvisioningUtil.removeMetadataRepository(known2); - ProvisioningUtil.removeMetadataRepository(uri); - ProvisioningUtil.removeMetadataRepository(uri2); - ProvisioningUtil.removeArtifactRepository(uri2); - ProvisioningUtil.removeMetadataRepository(uri3); + manager.removeRepository(known1); + manager.removeRepository(known2); + manager.removeRepository(uri); + manager.removeRepository(uri2); + session.getArtifactRepositoryManager().removeRepository(uri2); + manager.removeRepository(uri3); } } diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/InstallActionTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/InstallActionTest.java index 8a61940ec..aea471405 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/InstallActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/InstallActionTest.java @@ -11,11 +11,10 @@ package org.eclipse.equinox.p2.tests.ui.actions; +import org.eclipse.equinox.internal.p2.ui.actions.InstallAction; import org.eclipse.equinox.internal.p2.ui.model.AvailableIUElement; import org.eclipse.equinox.internal.p2.ui.model.IIUElement; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.InstallAction; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; /** * @since 3.5 @@ -25,7 +24,7 @@ public class InstallActionTest extends ProfileModificationActionTest { class TestInstallAction extends InstallAction { TestInstallAction(Object[] sel) { - super(Policy.getDefault(), InstallActionTest.this.getSelectionProvider(sel), profile.getProfileId()); + super(InstallActionTest.this.getProvisioningUI(), InstallActionTest.this.getSelectionProvider(sel), profile.getProfileId()); } public IInstallableUnit[] getSelectedIUs() { diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/ProfileModificationActionTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/ProfileModificationActionTest.java index 7f487e0bb..5600fb3cb 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/ProfileModificationActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/ProfileModificationActionTest.java @@ -11,8 +11,7 @@ package org.eclipse.equinox.p2.tests.ui.actions; import org.eclipse.equinox.internal.p2.ui.model.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.model.InstalledIUElement; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; /** * Abstract class to set up different IU selection combinations diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/RemoveColocatedRepositoryActionTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/RemoveColocatedRepositoryActionTest.java index 0f7f2c5b5..687fe0952 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/RemoveColocatedRepositoryActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/RemoveColocatedRepositoryActionTest.java @@ -10,16 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.actions; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.RemoveColocatedRepositoryAction; +import org.eclipse.equinox.internal.p2.ui.actions.RemoveColocatedRepositoryAction; public class RemoveColocatedRepositoryActionTest extends ColocatedRepositoryActionTest { public void testEmptySelection() { - RemoveColocatedRepositoryAction action = new RemoveColocatedRepositoryAction(getSelectionProvider(getEmptySelection())); + RemoveColocatedRepositoryAction action = new RemoveColocatedRepositoryAction(getProvisioningUI(), getSelectionProvider(getEmptySelection())); assertFalse("Should not be enabled with empty selection", action.isEnabled()); } public void testInvalidSelection() { - RemoveColocatedRepositoryAction action = new RemoveColocatedRepositoryAction(getSelectionProvider(getInvalidSelection())); + RemoveColocatedRepositoryAction action = new RemoveColocatedRepositoryAction(getProvisioningUI(), getSelectionProvider(getInvalidSelection())); assertFalse("Should not be enabled with invalid selection", action.isEnabled()); } @@ -27,7 +27,7 @@ public class RemoveColocatedRepositoryActionTest extends ColocatedRepositoryActi assertTrue(managerContains(metaManager, testRepoLocation)); assertTrue(managerContains(artifactManager, testRepoLocation)); - RemoveColocatedRepositoryAction action = new RemoveColocatedRepositoryAction(getSelectionProvider(getValidRepoSelection())); + RemoveColocatedRepositoryAction action = new RemoveColocatedRepositoryAction(getProvisioningUI(), getSelectionProvider(getValidRepoSelection())); assertTrue("Should be enabled", action.isEnabled()); action.run(); diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/UninstallActionTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/UninstallActionTest.java index 655eb85df..8a7f9d9aa 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/UninstallActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/UninstallActionTest.java @@ -11,9 +11,8 @@ package org.eclipse.equinox.p2.tests.ui.actions; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.UninstallAction; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.actions.UninstallAction; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; /** * @since 3.5 @@ -22,7 +21,7 @@ import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; public class UninstallActionTest extends ProfileModificationActionTest { class TestUninstallAction extends UninstallAction { TestUninstallAction(Object[] sel) { - super(Policy.getDefault(), UninstallActionTest.this.getSelectionProvider(sel), profile.getProfileId()); + super(UninstallActionTest.this.getProvisioningUI(), UninstallActionTest.this.getSelectionProvider(sel), profile.getProfileId()); } public IInstallableUnit[] getSelectedIUs() { diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/UpdateActionTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/UpdateActionTest.java index 6901e2fd5..fa3ca5e56 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/UpdateActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/actions/UpdateActionTest.java @@ -11,9 +11,8 @@ package org.eclipse.equinox.p2.tests.ui.actions; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.UpdateAction; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.actions.UpdateAction; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; /** * @since 3.5 @@ -22,7 +21,7 @@ import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; public class UpdateActionTest extends ProfileModificationActionTest { class TestUpdateAction extends UpdateAction { TestUpdateAction(Object[] sel) { - super(Policy.getDefault(), UpdateActionTest.this.getSelectionProvider(sel), profile.getProfileId(), true); + super(UpdateActionTest.this.getProvisioningUI(), UpdateActionTest.this.getSelectionProvider(sel), profile.getProfileId(), true); } public IInstallableUnit[] getSelectedIUs() { diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/IUPropertyPagesTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/IUPropertyPagesTest.java index 0965029a8..52b85ae92 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/IUPropertyPagesTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/IUPropertyPagesTest.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.dialogs; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.p2.metadata.ILicense; import java.net.URI; import java.net.URISyntaxException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.internal.provisional.p2.metadata.*; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.ui.AbstractProvisioningUITest; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.internal.dialogs.PropertyDialog; @@ -66,11 +68,11 @@ public class IUPropertyPagesTest extends AbstractProvisioningUITest { private IInstallableUnit getIU() throws URISyntaxException { InstallableUnitDescription iuDescription = new InstallableUnitDescription(); iuDescription.setId("TestIU"); - iuDescription.setVersion(new Version(1, 0, 0)); + iuDescription.setVersion(Version.createOSGi(1, 0, 0)); iuDescription.setProperty(IInstallableUnit.PROP_PROVIDER, "Test Cases"); iuDescription.setProperty(IInstallableUnit.PROP_DESCRIPTION, "A description"); iuDescription.setProperty(IInstallableUnit.PROP_NAME, "The Biggest Baddest Test IU"); - iuDescription.setLicense(MetadataFactory.createLicense(new URI("http://example.com"), "This is an example license")); + iuDescription.setLicenses(new ILicense[] {MetadataFactory.createLicense(new URI("http://example.com"), "This is an example license")}); iuDescription.setCopyright(MetadataFactory.createCopyright(new URI("http://example.com"), "This is an example copyright")); return MetadataFactory.createInstallableUnit(iuDescription); } diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/InstallWizardTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/InstallWizardTest.java index ac51fb301..107e3ec19 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/InstallWizardTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/InstallWizardTest.java @@ -10,23 +10,23 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.dialogs; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.p2.metadata.IProvidedCapability; + +import org.eclipse.equinox.p2.metadata.ILicense; -import java.util.HashSet; -import org.eclipse.core.runtime.jobs.Job; import org.eclipse.equinox.internal.p2.metadata.License; +import org.eclipse.equinox.internal.p2.ui.ProvUI; import org.eclipse.equinox.internal.p2.ui.dialogs.*; import org.eclipse.equinox.internal.p2.ui.model.IIUElement; import org.eclipse.equinox.internal.p2.ui.viewers.DeferredQueryContentProvider; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.*; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.IUViewQueryContext; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.InstallOperation; +import org.eclipse.equinox.p2.operations.ProfileModificationJob; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.WizardDialog; @@ -40,24 +40,31 @@ public class InstallWizardTest extends WizardTest { private static final String SELECTION_PAGE = "IUSelectionPage"; private static final String AVAILABLE_SOFTWARE_PAGE = "AvailableSoftwarePage"; - private static final String BROKEN_IU = "RCP_Browser_Example.feature.group"; private static final String MAIN_IU = "MainIU"; - public void testInstallWizardResolved() throws ProvisionException { + IInstallableUnit toInstall; + + protected void setUp() throws Exception { + super.setUp(); InstallableUnitDescription iu = new MetadataFactory.InstallableUnitDescription(); iu.setId(MAIN_IU); - iu.setVersion(new Version(1, 0, 0)); + iu.setProperty(InstallableUnitDescription.PROP_TYPE_GROUP, "true"); + iu.setVersion(Version.createOSGi(1, 0, 0)); iu.setSingleton(true); - iu.setLicense(new License(null, "There is a license to accept!")); + iu.setLicenses(new ILicense[] {new License(null, "There is a license to accept!", null)}); iu.setCapabilities(new IProvidedCapability[] {MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, MAIN_IU, iu.getVersion())}); - IInstallableUnit toInstall = MetadataFactory.createInstallableUnit(iu); - ProfileChangeRequest request = new ProfileChangeRequest(profile); - request.addInstallableUnits(new IInstallableUnit[] {toInstall}); - PlannerResolutionOperation op = getResolvedOperation(request); - PreselectedIUInstallWizard wizard = new PreselectedIUInstallWizard(Policy.getDefault(), TESTPROFILE, new IInstallableUnit[] {toInstall}, op, null); + toInstall = MetadataFactory.createInstallableUnit(iu); + createTestMetdataRepository(new IInstallableUnit[] {toInstall}); + } + + public void testInstallWizardResolved() { + InstallOperation op = new InstallOperation(getSession(), new IInstallableUnit[] {toInstall}); + op.setProfileId(TESTPROFILE); + PreselectedIUInstallWizard wizard = new PreselectedIUInstallWizard(getProvisioningUI(), op, new IInstallableUnit[] {toInstall}, null); ProvisioningWizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); dialog.setBlockOnOpen(false); dialog.open(); + ProfileModificationJob longOp = null; try { SelectableIUsPage page1 = (SelectableIUsPage) wizard.getPage(SELECTION_PAGE); @@ -66,16 +73,31 @@ public class InstallWizardTest extends WizardTest { // simulate the next button by getting next page and showing IWizardPage page = page1.getNextPage(); dialog.showPage(page); + // we should be ok + assertTrue("1.1", page.isPageComplete()); + + // if another operation is scheduled for this profile, we should not be allowed to proceed + longOp = getLongTestOperation(); + getProvisioningUI().schedule(longOp, StatusManager.LOG); + // causes recalculation of plan and status + wizard.recomputePlan(dialog); + // can't move to next page while op is running + assertFalse("1.2", page.isPageComplete()); + longOp.cancel(); + + // op is no longer running, recompute plan + wizard.recomputePlan(dialog); + // license needs approval - assertFalse("1.1", wizard.canFinish()); + assertFalse("1.4", wizard.canFinish()); // finish button should be disabled - while (dialog.getShell().getDisplay().readAndDispatch()) { - // run event loop - } + dialog.updateButtons(); Button finishButton = dialog.testGetButton(IDialogConstants.FINISH_ID); - assertFalse("1.2", finishButton.isEnabled()); + assertFalse("1.5", finishButton.isEnabled()); } finally { dialog.getShell().close(); + if (longOp != null) + longOp.cancel(); } } @@ -83,66 +105,63 @@ public class InstallWizardTest extends WizardTest { * Tests the wizard */ public void testInstallWizardUnresolved() { - Policy policy = Policy.getDefault(); - IUViewQueryContext context = policy.getQueryContext(); - context.setViewType(IUViewQueryContext.AVAILABLE_VIEW_FLAT); - QueryableMetadataRepositoryManager manager = new QueryableMetadataRepositoryManager(context, false); - manager.loadAll(getMonitor()); - InstallWizard wizard = new InstallWizard(policy, TESTPROFILE, null, null, manager); + LoadMetadataRepositoryJob job = new LoadMetadataRepositoryJob(getProvisioningUI()); + getPolicy().setGroupByCategory(false); + job.runModal(getMonitor()); + InstallWizard wizard = new InstallWizard(getProvisioningUI(), null, null, job); WizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); dialog.create(); dialog.setBlockOnOpen(false); dialog.open(); + ProfileModificationJob longOp = null; + try { AvailableIUsPage page1 = (AvailableIUsPage) wizard.getPage(AVAILABLE_SOFTWARE_PAGE); // test initial wizard state - assertTrue(page1.getSelectedIUs().length == 0); - assertFalse(page1.isPageComplete()); + assertTrue("1.0", page1.getSelectedIUs().length == 0); + assertFalse("1.1", page1.isPageComplete()); // Start reaching in... AvailableIUGroup group = page1.testGetAvailableIUGroup(); group.setRepositoryFilter(AvailableIUGroup.AVAILABLE_ALL, null); // Now manipulate the tree itself. we are reaching way in. + // We are trying to select everything in the repo apart from the IU we know is broken DeferredQueryContentProvider provider = (DeferredQueryContentProvider) group.getCheckboxTreeViewer().getContentProvider(); provider.setSynchronous(true); group.getCheckboxTreeViewer().refresh(); group.getCheckboxTreeViewer().expandAll(); Tree tree = (Tree) group.getCheckboxTreeViewer().getControl(); TreeItem[] items = tree.getItems(); - HashSet ids = new HashSet(); - ids.add(BROKEN_IU); for (int i = 0; i < items.length; i++) { Object element = items[i].getData(); if (element != null && element instanceof IIUElement) { IInstallableUnit iu = ((IIUElement) element).getIU(); - if (iu != null && !ids.contains(iu.getId())) { - ids.add(iu.getId()); + if (iu != null && iu.getId().equals(MAIN_IU)) { group.getCheckboxTreeViewer().setChecked(element, true); } } } // must be done this way to force notification of listeners group.setChecked(group.getCheckboxTreeViewer().getCheckedElements()); + assertTrue("2.0", group.getCheckedLeafIUs().length > 0); + assertTrue("2.1", page1.isPageComplete()); + // simulate the user clicking next IWizardPage page = wizard.getNextPage(page1); - assertTrue(page instanceof IResolutionErrorReportingPage); - IResolutionErrorReportingPage page2 = (IResolutionErrorReportingPage) page; - assertTrue(group.getCheckedLeafIUs().length > 0); - dialog.showPage(page2); + dialog.showPage(page); + assertTrue("3.0", page.isPageComplete()); // if another operation is scheduled for this profile, we should not be allowed to proceed - Job job = ProvisioningOperationRunner.schedule(getLongTestOperation(), StatusManager.LOG); - assertTrue(page1.isPageComplete()); - + longOp = getLongTestOperation(); + getProvisioningUI().schedule(longOp, StatusManager.LOG); // causes recalculation of plan and status - dialog.showPage(page1); - wizard.getNextPage(page1); - assertTrue(page1.isPageComplete()); - assertFalse(page2.isPageComplete()); - job.cancel(); + wizard.recomputePlan(dialog); + // can't move to next page while op is running + assertFalse("3.1", page.isPageComplete()); + longOp.cancel(); // this doesn't test much, it's just calling group API to flesh out NPE's, etc. group.getCheckedLeafIUs(); @@ -152,6 +171,8 @@ public class InstallWizardTest extends WizardTest { } finally { dialog.close(); + if (longOp != null) + longOp.cancel(); } } } diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/InstallationHistoryPageTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/InstallationHistoryPageTest.java index c52dfb8b7..dbaaac69b 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/InstallationHistoryPageTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/InstallationHistoryPageTest.java @@ -13,10 +13,10 @@ package org.eclipse.equinox.p2.tests.ui.dialogs; import java.lang.reflect.Field; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.jobs.*; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.RevertProfilePage; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.ProvElementContentProvider; +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.internal.p2.ui.viewers.ProvElementContentProvider; import org.eclipse.equinox.p2.tests.ui.AbstractProvisioningUITest; +import org.eclipse.equinox.p2.ui.RevertProfilePage; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.viewers.AbstractTableViewer; import org.eclipse.swt.SWT; diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/InstalledSoftwarePageTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/InstalledSoftwarePageTest.java index ba43c86bc..cc4e0b7bf 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/InstalledSoftwarePageTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/InstalledSoftwarePageTest.java @@ -10,9 +10,9 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.dialogs; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.InstalledSoftwarePage; +import org.eclipse.equinox.internal.p2.ui.ProvUI; import org.eclipse.equinox.p2.tests.ui.AbstractProvisioningUITest; +import org.eclipse.equinox.p2.ui.InstalledSoftwarePage; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/RepositoryManipulationPageTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/RepositoryManipulationPageTest.java index c607fad49..6336fb8dc 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/RepositoryManipulationPageTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/RepositoryManipulationPageTest.java @@ -10,8 +10,8 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.dialogs; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.RepositoryManipulationPage; import org.eclipse.equinox.p2.tests.ui.AbstractProvisioningUITest; +import org.eclipse.equinox.p2.ui.RepositoryManipulationPage; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/UninstallWizardTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/UninstallWizardTest.java index 3509da276..079a8bccc 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/UninstallWizardTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/UninstallWizardTest.java @@ -10,18 +10,11 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.dialogs; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.equinox.internal.p2.ui.dialogs.ResolutionResultsWizardPage; -import org.eclipse.equinox.internal.p2.ui.dialogs.SelectableIUsPage; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.ProvisioningWizardDialog; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.UninstallWizard; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.internal.p2.ui.dialogs.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProfileModificationJob; +import org.eclipse.equinox.p2.operations.UninstallOperation; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.ui.statushandlers.StatusManager; @@ -36,17 +29,17 @@ public class UninstallWizardTest extends WizardTest { * Tests the wizard when the uninstall is preresolved. * This is the normal SDK workflow. */ - public void testUninstallWizardResolved() throws ProvisionException { + public void testUninstallWizardResolved() { - ProfileChangeRequest req = new ProfileChangeRequest(profile); IInstallableUnit[] iusInvolved = new IInstallableUnit[] {top1, top2}; - req.removeInstallableUnits(iusInvolved); - PlannerResolutionOperation op = getResolvedOperation(req); - UninstallWizard wizard = new UninstallWizard(Policy.getDefault(), TESTPROFILE, iusInvolved, op); + UninstallOperation op = getProvisioningUI().getUninstallOperation(iusInvolved, null); + op.resolveModal(getMonitor()); + UninstallWizard wizard = new UninstallWizard(getProvisioningUI(), op, iusInvolved, null); WizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); dialog.setBlockOnOpen(false); dialog.create(); dialog.open(); + ProfileModificationJob longOp = null; try { SelectableIUsPage page1 = (SelectableIUsPage) wizard.getPage(SELECTION_PAGE); @@ -57,16 +50,18 @@ public class UninstallWizardTest extends WizardTest { assertTrue(page2.isPageComplete()); // if another operation is scheduled for this profile, we should not be allowed to proceed - Job job = ProvisioningOperationRunner.schedule(getLongTestOperation(), StatusManager.LOG); + longOp = getLongTestOperation(); + getProvisioningUI().schedule(longOp, StatusManager.LOG); assertTrue(page1.isPageComplete()); // causes recalculation of plan and status - wizard.getNextPage(page1); + wizard.recomputePlan(dialog); // can't move to next page while op is running assertFalse(page1.isPageComplete()); - job.cancel(); - + longOp.cancel(); } finally { dialog.getShell().close(); + if (longOp != null) + longOp.cancel(); } } @@ -76,7 +71,8 @@ public class UninstallWizardTest extends WizardTest { */ public void testUninstallWizardUnresolved() { // This test is pretty useless right now but at least it opens the wizard - UninstallWizard wizard = new UninstallWizard(Policy.getDefault(), TESTPROFILE, new IInstallableUnit[] {top1, top2}, null); + UninstallOperation operation = getProvisioningUI().getUninstallOperation(new IInstallableUnit[] {top1, top2}, null); + UninstallWizard wizard = new UninstallWizard(getProvisioningUI(), operation, new IInstallableUnit[] {top1, top2}, null); WizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); dialog.setBlockOnOpen(false); dialog.create(); @@ -84,20 +80,11 @@ public class UninstallWizardTest extends WizardTest { try { SelectableIUsPage page1 = (SelectableIUsPage) wizard.getPage(SELECTION_PAGE); - assertFalse(page1.isPageComplete()); - // Will cause computation of a plan. - ResolutionResultsWizardPage page2 = (ResolutionResultsWizardPage) wizard.getNextPage(page1); - dialog.showPage(page2); - assertTrue(page2.isPageComplete()); - - // if another operation is scheduled for this profile, we should not be allowed to proceed - Job job = ProvisioningOperationRunner.schedule(getLongTestOperation(), StatusManager.LOG); assertTrue(page1.isPageComplete()); - // causes recalculation of plan and status - wizard.getNextPage(page1); - // can't move to next page while op is running - assertFalse(page1.isPageComplete()); - job.cancel(); + // Should be able to resolve a plan + wizard.recomputePlan(dialog); + // Still ok + assertTrue(page1.isPageComplete()); } finally { dialog.getShell().close(); diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/UpdateWizardTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/UpdateWizardTest.java index 7ec1dc401..e7a51619c 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/UpdateWizardTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/UpdateWizardTest.java @@ -10,25 +10,21 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.dialogs; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; + +import org.eclipse.equinox.p2.metadata.IProvidedCapability; +import org.eclipse.equinox.p2.metadata.IUpdateDescriptor; + +import org.eclipse.equinox.p2.metadata.ILicense; -import org.eclipse.core.runtime.jobs.Job; import org.eclipse.equinox.internal.p2.metadata.License; -import org.eclipse.equinox.internal.p2.ui.dialogs.ResolutionResultsWizardPage; -import org.eclipse.equinox.internal.p2.ui.dialogs.SelectableIUsPage; -import org.eclipse.equinox.internal.p2.ui.model.AvailableUpdateElement; -import org.eclipse.equinox.internal.provisional.p2.core.*; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.internal.p2.ui.dialogs.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.ProvisioningWizardDialog; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.UpdateWizard; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.*; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.WizardDialog; @@ -49,41 +45,39 @@ public class UpdateWizardTest extends WizardTest { super.setUp(); InstallableUnitDescription iu = new MetadataFactory.InstallableUnitDescription(); iu.setId(MAIN_IU); - iu.setVersion(new Version(1, 0, 0)); + iu.setVersion(Version.createOSGi(1, 0, 0)); iu.setSingleton(true); iu.setCapabilities(new IProvidedCapability[] {MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, MAIN_IU, iu.getVersion())}); main = MetadataFactory.createInstallableUnit(iu); install(main, true, false); IUpdateDescriptor update = MetadataFactory.createUpdateDescriptor(MAIN_IU, new VersionRange("[1.0.0, 1.0.0]"), 0, "update description"); - mainUpgrade1 = createIU(MAIN_IU, new Version(2, 0, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, true, update, NO_REQUIRES); + mainUpgrade1 = createIU(MAIN_IU, Version.createOSGi(2, 0, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, true, update, NO_REQUIRES); update = MetadataFactory.createUpdateDescriptor(MAIN_IU, new VersionRange("[1.0.0, 1.0.0]"), 0, "update description"); - mainUpgrade2 = createIU(MAIN_IU, new Version(3, 0, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, true, update, NO_REQUIRES); + mainUpgrade2 = createIU(MAIN_IU, Version.createOSGi(3, 0, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, true, update, NO_REQUIRES); iu = new MetadataFactory.InstallableUnitDescription(); iu.setId(MAIN_IU); - iu.setVersion(new Version(4, 0, 0)); + iu.setVersion(Version.createOSGi(4, 0, 0)); iu.setSingleton(true); iu.setUpdateDescriptor(update); - iu.setLicense(new License(null, "Update Wizard Test License to Accept")); + iu.setLicenses(new ILicense[] {new License(null, "Update Wizard Test License to Accept", null)}); iu.setCapabilities(new IProvidedCapability[] {MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, MAIN_IU, iu.getVersion())}); mainUpgradeWithLicense = MetadataFactory.createInstallableUnit(iu); + createTestMetdataRepository(new IInstallableUnit[] {main, mainUpgrade1, mainUpgrade2, mainUpgradeWithLicense}); + } /** * Tests the wizard when a prior resolution has been done. * This is the SDK */ - public void testUpdateWizardResolved() throws ProvisionException { - IUElementListRoot root = new IUElementListRoot(); - AvailableUpdateElement element = new AvailableUpdateElement(root, upgrade, top1, TESTPROFILE, true); - root.setChildren(new Object[] {element}); - ProfileChangeRequest request = new ProfileChangeRequest(profile); - request.removeInstallableUnits(new IInstallableUnit[] {top1}); - request.addInstallableUnits(new IInstallableUnit[] {upgrade}); - PlannerResolutionOperation op = getResolvedOperation(request); - UpdateWizard wizard = new UpdateWizard(Policy.getDefault(), TESTPROFILE, root, new Object[] {element}, op, null); + public void testUpdateWizardResolved() { + UpdateOperation op = getProvisioningUI().getUpdateOperation(new IInstallableUnit[] {main}, null); + op.resolveModal(getMonitor()); + UpdateWizard wizard = new UpdateWizard(getProvisioningUI(), op, op.getSelectedUpdates(), null); WizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); dialog.setBlockOnOpen(false); dialog.open(); + ProfileModificationJob longOp = null; try { SelectableIUsPage page1 = (SelectableIUsPage) wizard.getPage(SELECTION_PAGE); @@ -94,28 +88,25 @@ public class UpdateWizardTest extends WizardTest { assertTrue(page2.isPageComplete()); // if another operation is scheduled for this profile, we should not be allowed to proceed - Job job = ProvisioningOperationRunner.schedule(getLongTestOperation(), StatusManager.LOG); - assertTrue(page1.isPageComplete()); + longOp = getLongTestOperation(); + getProvisioningUI().schedule(longOp, StatusManager.LOG); + assertTrue(page2.isPageComplete()); // causes recalculation of plan and status - wizard.getNextPage(page1); + wizard.recomputePlan(dialog); // can't move to next page while op is running - assertFalse(page1.isPageComplete()); - job.cancel(); - + assertFalse(page2.isPageComplete()); + longOp.cancel(); } finally { dialog.getShell().close(); + if (longOp != null) + longOp.cancel(); } } - public void testUpdateWizardResolvedWithLicense() throws ProvisionException { - IUElementListRoot root = new IUElementListRoot(); - AvailableUpdateElement element = new AvailableUpdateElement(root, mainUpgradeWithLicense, main, TESTPROFILE, true); - root.setChildren(new Object[] {element}); - ProfileChangeRequest request = new ProfileChangeRequest(profile); - request.removeInstallableUnits(new IInstallableUnit[] {main}); - request.addInstallableUnits(new IInstallableUnit[] {mainUpgradeWithLicense}); - PlannerResolutionOperation op = getResolvedOperation(request); - UpdateWizard wizard = new UpdateWizard(Policy.getDefault(), TESTPROFILE, root, new Object[] {element}, op, null); + public void testUpdateWizardResolvedWithLicense() { + UpdateOperation op = getProvisioningUI().getUpdateOperation(new IInstallableUnit[] {main}, null); + op.resolveModal(getMonitor()); + UpdateWizard wizard = new UpdateWizard(getProvisioningUI(), op, op.getSelectedUpdates(), null); ProvisioningWizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); dialog.setBlockOnOpen(false); dialog.open(); @@ -143,18 +134,12 @@ public class UpdateWizardTest extends WizardTest { /** * Tests the wizard when a prior resolution has been done, but is in error. */ - public void testUpdateWizardResolvedError() throws ProvisionException { - IUElementListRoot root = new IUElementListRoot(); - AvailableUpdateElement element = new AvailableUpdateElement(root, mainUpgrade1, main, TESTPROFILE, true); - AvailableUpdateElement element2 = new AvailableUpdateElement(root, mainUpgrade2, main, TESTPROFILE, true); - root.setChildren(new Object[] {element, element2}); - ProfileChangeRequest request = new ProfileChangeRequest(profile); - request.removeInstallableUnits(new IInstallableUnit[] {main}); - request.addInstallableUnits(new IInstallableUnit[] {mainUpgrade1, mainUpgrade2}); - PlannerResolutionOperation op = getResolvedOperation(request); - UpdateWizard wizard = new UpdateWizard(Policy.getDefault(), TESTPROFILE, root, new Object[] {element, element2}, op, null); - wizard.setSkipSelectionsPage(true); - WizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); + public void testUpdateWizardResolvedError() { + UpdateOperation op = getProvisioningUI().getUpdateOperation(new IInstallableUnit[] {main}, null); + op.resolveModal(getMonitor()); + op.setSelectedUpdates(op.getPossibleUpdates()); + UpdateWizard wizard = new UpdateWizard(getProvisioningUI(), op, op.getSelectedUpdates(), null); + ProvisioningWizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); dialog.setBlockOnOpen(false); dialog.open(); @@ -169,17 +154,12 @@ public class UpdateWizardTest extends WizardTest { * Tests the wizard when we have a successful resolution and want to open * directly on the resolution page */ - public void testUpdateWizardResolvedSkipSelections() throws ProvisionException { - IUElementListRoot root = new IUElementListRoot(); - AvailableUpdateElement element = new AvailableUpdateElement(root, mainUpgrade1, main, TESTPROFILE, true); - root.setChildren(new Object[] {element}); - ProfileChangeRequest request = new ProfileChangeRequest(profile); - request.removeInstallableUnits(new IInstallableUnit[] {main}); - request.addInstallableUnits(new IInstallableUnit[] {mainUpgrade1}); - PlannerResolutionOperation op = getResolvedOperation(request); - UpdateWizard wizard = new UpdateWizard(Policy.getDefault(), TESTPROFILE, root, new Object[] {element}, op, null); + public void testUpdateWizardResolvedSkipSelections() { + UpdateOperation op = getProvisioningUI().getUpdateOperation(new IInstallableUnit[] {main}, null); + op.resolveModal(getMonitor()); + UpdateWizard wizard = new UpdateWizard(getProvisioningUI(), op, op.getSelectedUpdates(), null); wizard.setSkipSelectionsPage(true); - WizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); + ProvisioningWizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); dialog.setBlockOnOpen(false); dialog.open(); @@ -196,31 +176,21 @@ public class UpdateWizardTest extends WizardTest { * This is not the SDK workflow, but should be supported. */ public void testUpdateWizardUnresolved() { - IUElementListRoot root = new IUElementListRoot(); - AvailableUpdateElement element = new AvailableUpdateElement(root, upgrade, top1, TESTPROFILE, true); - root.setChildren(new Object[] {element}); - - UpdateWizard wizard = new UpdateWizard(Policy.getDefault(), TESTPROFILE, root, new Object[] {element}, null, null); + Update update = new Update(main, mainUpgrade1); + UpdateOperation op = getProvisioningUI().getUpdateOperation(new IInstallableUnit[] {main}, null); + UpdateWizard wizard = new UpdateWizard(getProvisioningUI(), op, new Object[] {update}, null); WizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); dialog.setBlockOnOpen(false); dialog.open(); try { SelectableIUsPage page1 = (SelectableIUsPage) wizard.getPage(SELECTION_PAGE); - assertFalse(page1.isPageComplete()); - // Will cause computation of a plan. - ResolutionResultsWizardPage page2 = (ResolutionResultsWizardPage) wizard.getNextPage(page1); - dialog.showPage(page2); - assertTrue(page2.isPageComplete()); - - // if another operation is scheduled for this profile, we should not be allowed to proceed - Job job = ProvisioningOperationRunner.schedule(getLongTestOperation(), StatusManager.LOG); + // Page 1 should have selections + assertTrue(page1.isPageComplete()); + // Should be able to resolve an unresolved operation + wizard.recomputePlan(dialog); + // Everything is still good assertTrue(page1.isPageComplete()); - // causes recalculation of plan and status - wizard.getNextPage(page1); - // can't move to next page while op is running - assertFalse(page1.isPageComplete()); - job.cancel(); } finally { dialog.getShell().close(); @@ -230,17 +200,12 @@ public class UpdateWizardTest extends WizardTest { /** * Tests the wizard when multiple versions are available. */ - public void testBug277554MultipleVersions() throws ProvisionException { - IUElementListRoot root = new IUElementListRoot(); - AvailableUpdateElement element = new AvailableUpdateElement(root, mainUpgrade1, main, TESTPROFILE, true); - AvailableUpdateElement element2 = new AvailableUpdateElement(root, mainUpgrade2, main, TESTPROFILE, true); - root.setChildren(new Object[] {element, element2}); - ProfileChangeRequest request = new ProfileChangeRequest(profile); - request.removeInstallableUnits(new IInstallableUnit[] {main}); - request.addInstallableUnits(new IInstallableUnit[] {mainUpgrade2}); - PlannerResolutionOperation op = getResolvedOperation(request); - UpdateWizard wizard = new UpdateWizard(Policy.getDefault(), TESTPROFILE, root, new Object[] {element2}, op, null); - WizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); + public void testBug277554MultipleVersions() { + + UpdateOperation op = getProvisioningUI().getUpdateOperation(new IInstallableUnit[] {main}, null); + op.resolveModal(getMonitor()); + UpdateWizard wizard = new UpdateWizard(getProvisioningUI(), op, op.getSelectedUpdates(), null); + ProvisioningWizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); dialog.setBlockOnOpen(false); dialog.open(); @@ -248,7 +213,7 @@ public class UpdateWizardTest extends WizardTest { SelectableIUsPage page1 = (SelectableIUsPage) wizard.getPage(SELECTION_PAGE); // should already have a plan assertTrue("1.0", page1.isPageComplete()); - assertEquals("1.1", page1.getCheckedIUElements().length, 1); + assertEquals("1.1", 1, page1.getCheckedIUElements().length); ResolutionResultsWizardPage page2 = (ResolutionResultsWizardPage) wizard.getNextPage(page1); dialog.showPage(page2); // should only have one root item in the resolution page diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/WizardTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/WizardTest.java index f312c6b0a..630b6c789 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/WizardTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/dialogs/WizardTest.java @@ -10,22 +10,11 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.dialogs; -import java.net.URI; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; import org.eclipse.equinox.p2.tests.ui.AbstractProvisioningUITest; /** - * Tests for the install wizard + * Generic wizard test methods */ public abstract class WizardTest extends AbstractProvisioningUITest { - protected PlannerResolutionOperation getResolvedOperation(ProfileChangeRequest request) throws ProvisionException { - PlannerResolutionOperation op = new PlannerResolutionOperation("Test resolve operation", request.getProfile().getProfileId(), request, new ProvisioningContext(new URI[] {}), new MultiStatus(ProvUIActivator.PLUGIN_ID, 0, "This is just a test multistatus", null), true); - op.execute(getMonitor()); - return op; - } + } diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/AddColocatedRepositoryOperationTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/AddColocatedRepositoryOperationTest.java deleted file mode 100644 index 9dc820ded..000000000 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/AddColocatedRepositoryOperationTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.tests.ui.operations; - -import java.net.URI; -import java.util.Arrays; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.AddColocatedRepositoryOperation; -import org.eclipse.equinox.p2.tests.TestData; -import org.eclipse.equinox.p2.tests.ui.AbstractProvisioningUITest; - -/** - * Tests for {@link AddColocatedRepositoryOperation}. - */ -public class AddColocatedRepositoryOperationTest extends AbstractProvisioningUITest { - public void testAddSingleRepository() { - URI repoLocation = null; - try { - repoLocation = TestData.getFile("artifactRepo", "").toURI(); - } catch (Exception e) { - fail("0.99", e); - } - AddColocatedRepositoryOperation op = new AddColocatedRepositoryOperation("label", repoLocation); - assertTrue("1.0", op.runInBackground()); - - try { - IStatus result = op.execute(getMonitor()); - assertTrue("1.1", result.isOK()); - } catch (ProvisionException e) { - fail("1.99", e); - } - - URI[] repos = metaManager.getKnownRepositories(0); - assertTrue("2.0", Arrays.asList(repos).contains(repoLocation)); - assertTrue("2.1", metaManager.isEnabled(repoLocation)); - - repos = artifactManager.getKnownRepositories(0); - assertTrue("3.0", Arrays.asList(repos).contains(repoLocation)); - assertTrue("3.1", artifactManager.isEnabled(repoLocation)); - } -} diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/AddProfileOperationTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/AddProfileOperationTest.java deleted file mode 100644 index e03afd230..000000000 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/AddProfileOperationTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.tests.ui.operations; - -import java.util.HashMap; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.AddProfileOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.p2.tests.ui.AbstractProvisioningUITest; - -/** - * Tests for {@link AddProfileOperation}. - */ -public class AddProfileOperationTest extends AbstractProvisioningUITest { - public static final String TEST_PROP_KEY = "TEST_PROP_KEY"; - public static final String TEST_PROP_VALUE = "TEST_PROP_VALUE"; - - /** - * Tests a simple profile addition that should succeed - */ - public void testAddSimple() { - HashMap properties = new HashMap(); - properties.put(TEST_PROP_KEY, TEST_PROP_VALUE); - String profileId = "add-simple"; - profilesToRemove.add(profileId); - AddProfileOperation op = new AddProfileOperation("label", profileId, properties); - - try { - IStatus result = op.execute(getMonitor()); - assertTrue("1.2", result.isOK()); - } catch (ProvisionException e) { - fail("0.99", e); - } - - IProfile p = null; - try { - p = ProvisioningUtil.getProfile(profileId); - } catch (ProvisionException e) { - fail("2.99", e); - return; - } - assertNotNull("3.0", p); - assertEquals("3.1", TEST_PROP_VALUE, p.getProperty(TEST_PROP_KEY)); - } -} diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/AllTests.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/AllTests.java index b5a272419..49a26d748 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/AllTests.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/AllTests.java @@ -19,11 +19,7 @@ public class AllTests extends TestCase { public static Test suite() { TestSuite suite = new TestSuite(AllTests.class.getName()); - suite.addTestSuite(AddColocatedRepositoryOperationTest.class); - suite.addTestSuite(AddProfileOperationTest.class); - suite.addTestSuite(RemoveProfilesOperationTest.class); suite.addTestSuite(SizingTest.class); - suite.addTestSuite(ProvisioningUtilTest.class); return suite; } } diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/ProvisioningUtilTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/ProvisioningUtilTest.java deleted file mode 100644 index 8ad4f121d..000000000 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/ProvisioningUtilTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.tests.ui.operations; - -import java.net.URI; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.p2.tests.ui.AbstractProvisioningUITest; - -/** - * - */ -public class ProvisioningUtilTest extends AbstractProvisioningUITest { - public void testArtifactRepos() throws ProvisionException { - URI[] artifactRepos = ProvisioningUtil.getArtifactRepositories(IRepositoryManager.REPOSITORIES_ALL); - for (int i = 0; i < artifactRepos.length; i++) - assertTrue(artifactRepos[i].toString() + " should be enabled", ProvisioningUtil.getArtifactRepositoryEnablement(artifactRepos[i])); - - artifactRepos = ProvisioningUtil.getArtifactRepositories(IRepositoryManager.REPOSITORIES_DISABLED); - for (int i = 0; i < artifactRepos.length; i++) - assertFalse(artifactRepos[i].toString() + " should be disabled", ProvisioningUtil.getArtifactRepositoryEnablement(artifactRepos[i])); - - artifactRepos = ProvisioningUtil.getArtifactRepositories(IRepositoryManager.REPOSITORIES_NON_SYSTEM); - for (int i = 0; i < artifactRepos.length; i++) - assertEquals("Expected non system repo " + artifactRepos[i].toString(), ProvisioningUtil.getArtifactRepositoryProperty(artifactRepos[i], IRepository.PROP_SYSTEM), Boolean.toString(false)); - - artifactRepos = ProvisioningUtil.getArtifactRepositories(IRepositoryManager.REPOSITORIES_LOCAL); - // TODO need to understand why this is failing - // ProvisioningUtil.refreshArtifactRepositories(artifactRepos, getMonitor()); - - } - - public void testMetadataRepos() throws ProvisionException { - URI[] metadataRepos = ProvisioningUtil.getMetadataRepositories(IRepositoryManager.REPOSITORIES_ALL); - for (int i = 0; i < metadataRepos.length; i++) - assertTrue(metadataRepos[i].toString() + " should be enabled", ProvisioningUtil.getMetadataRepositoryEnablement(metadataRepos[i])); - - metadataRepos = ProvisioningUtil.getMetadataRepositories(IRepositoryManager.REPOSITORIES_DISABLED); - for (int i = 0; i < metadataRepos.length; i++) - assertFalse(metadataRepos[i].toString() + " should be disabled", ProvisioningUtil.getMetadataRepositoryEnablement(metadataRepos[i])); - - metadataRepos = ProvisioningUtil.getMetadataRepositories(IRepositoryManager.REPOSITORIES_NON_SYSTEM); - for (int i = 0; i < metadataRepos.length; i++) - assertEquals("Expected non system repo " + metadataRepos[i].toString(), ProvisioningUtil.getMetadataRepositoryProperty(metadataRepos[i], IRepository.PROP_SYSTEM), Boolean.toString(false)); - - metadataRepos = ProvisioningUtil.getMetadataRepositories(IRepositoryManager.REPOSITORIES_LOCAL); - ProvisioningUtil.refreshMetadataRepositories(metadataRepos, getMonitor()); - - } -} diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/RemoveColocatedRepositoryOperationTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/RemoveColocatedRepositoryOperationTest.java deleted file mode 100644 index 46ef3f618..000000000 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/RemoveColocatedRepositoryOperationTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.tests.ui.operations; - -import java.net.URI; -import java.util.Arrays; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.AddColocatedRepositoryOperation; -import org.eclipse.equinox.p2.tests.TestData; -import org.eclipse.equinox.p2.tests.ui.AbstractProvisioningUITest; - -/** - * Tests for {@link AddColocatedRepositoryOperation}. - */ -public class RemoveColocatedRepositoryOperationTest extends AbstractProvisioningUITest { - public void testRemoveSingleRepository() { - URI repoLocation = null; - try { - repoLocation = TestData.getFile("artifactRepo", "").toURI(); - } catch (Exception e) { - fail("0.99", e); - } - AddColocatedRepositoryOperation op = new AddColocatedRepositoryOperation("label", repoLocation); - assertTrue("1.1", op.runInBackground()); - - try { - IStatus result = op.execute(getMonitor()); - assertTrue("1.2", result.isOK()); - } catch (ProvisionException e) { - fail("1.99", e); - } - - URI[] repos = metaManager.getKnownRepositories(0); - assertTrue("2.0", Arrays.asList(repos).contains(repoLocation)); - assertTrue("2.1", metaManager.isEnabled(repoLocation)); - - repos = artifactManager.getKnownRepositories(0); - assertTrue("3.0", Arrays.asList(repos).contains(repoLocation)); - assertTrue("3.1", artifactManager.isEnabled(repoLocation)); - } -} diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/RemoveProfilesOperationTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/RemoveProfilesOperationTest.java deleted file mode 100644 index cdef7d3c2..000000000 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/RemoveProfilesOperationTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.p2.tests.ui.operations; - -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.RemoveProfilesOperation; -import org.eclipse.equinox.p2.tests.ui.AbstractProvisioningUITest; - -/** - * Tests for {@link RemoveProfilesOperation} - */ -public class RemoveProfilesOperationTest extends AbstractProvisioningUITest { - public void testRemoveExisting() { - String profileId = "testRemoveNonExisting"; - IProfile p = createProfile(profileId); - RemoveProfilesOperation op = new RemoveProfilesOperation("label", new String[] {profileId}); - - try { - op.execute(getMonitor()); - } catch (ProvisionException e) { - fail("0.99", e); - } - - try { - p = ProvisioningUtil.getProfile(profileId); - } catch (ProvisionException e) { - fail("1.99", e); - } - assertNull("2.0", p); - } - - public void testRemoveNonExisting() { - String profileId = "testRemoveNonExisting"; - IProfile p = createProfile(profileId); - try { - ProvisioningUtil.removeProfile(profileId, getMonitor()); - } catch (ProvisionException e) { - fail("0.99", e); - } - RemoveProfilesOperation op = new RemoveProfilesOperation("label", new String[] {profileId}); - - //Currently the profile registry does not mind if we try to delete a profile that doesn't exist, so - //the UI classes don't test for it. - try { - op.execute(getMonitor()); - } catch (ProvisionException e) { - //expected - } - - try { - p = ProvisioningUtil.getProfile(profileId); - } catch (ProvisionException e) { - fail("2.99", e); - } - assertNull("1.0", p); - } -} diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/SizingTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/SizingTest.java index 669c7b3b8..8b605be07 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/SizingTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/operations/SizingTest.java @@ -10,14 +10,10 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.operations; -import org.eclipse.equinox.internal.p2.ui.model.IIUElement; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProvisioningSession; import org.eclipse.equinox.p2.tests.ui.AbstractProvisioningUITest; /** @@ -26,21 +22,12 @@ import org.eclipse.equinox.p2.tests.ui.AbstractProvisioningUITest; public class SizingTest extends AbstractProvisioningUITest { public void testEmptySizing() { String profileId = "testEmptySizing"; - IProfile profile = createProfile(profileId); - ProfileChangeRequest request = new ProfileChangeRequest(profile); - ProvisioningPlan plan = null; - try { - plan = ProvisioningUtil.getProvisioningPlan(request, new ProvisioningContext(), getMonitor()); - } catch (ProvisionException e) { - fail("0.99", e); - return; - } - long size = IIUElement.SIZE_NOTAPPLICABLE; - try { - size = ProvisioningUtil.getSize(plan, profileId, new ProvisioningContext(), getMonitor()); - } catch (ProvisionException e) { - fail("1.99", e); - } + IProfile testProfile = createProfile(profileId); + ProfileChangeRequest request = new ProfileChangeRequest(testProfile); + IProvisioningPlan plan = null; + plan = getSession().getPlanner().getProvisioningPlan(request, new ProvisioningContext(), getMonitor()); + long size = ProvisioningSession.SIZE_NOTAPPLICABLE; + size = getSession().getSize(plan, new ProvisioningContext(), getMonitor()); assertEquals("1.0", 0, size); } @@ -50,22 +37,13 @@ public class SizingTest extends AbstractProvisioningUITest { public void testSimpleSizing() { IInstallableUnit f1 = createIU("f1", DEFAULT_VERSION, true); String profileId = "testSimpleSizing"; - IProfile profile = createProfile(profileId); - ProfileChangeRequest request = new ProfileChangeRequest(profile); + IProfile testProfile = createProfile(profileId); + ProfileChangeRequest request = new ProfileChangeRequest(testProfile); request.addInstallableUnits(new IInstallableUnit[] {f1}); - ProvisioningPlan plan = null; - try { - plan = ProvisioningUtil.getProvisioningPlan(request, new ProvisioningContext(), getMonitor()); - } catch (ProvisionException e) { - fail("0.99", e); - return; - } - long size = IIUElement.SIZE_NOTAPPLICABLE; - try { - size = ProvisioningUtil.getSize(plan, profileId, new ProvisioningContext(), getMonitor()); - } catch (ProvisionException e) { - fail("1.99", e); - } + IProvisioningPlan plan = null; + plan = getSession().getPlanner().getProvisioningPlan(request, new ProvisioningContext(), getMonitor()); + long size = ProvisioningSession.SIZE_NOTAPPLICABLE; + size = getSession().getSize(plan, new ProvisioningContext(), getMonitor()); assertEquals("1.0", 0, size); } } diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/planning/UpdatePlanning.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/planning/UpdatePlanning.java index 6a65a2d7c..827dabf0c 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/planning/UpdatePlanning.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/planning/UpdatePlanning.java @@ -10,17 +10,23 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.planning; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; -import java.util.*; -import org.eclipse.equinox.internal.p2.ui.model.AvailableUpdateElement; -import org.eclipse.equinox.internal.provisional.p2.core.*; +import org.eclipse.equinox.p2.metadata.IRequirementChange; +import org.eclipse.equinox.p2.metadata.IUpdateDescriptor; + +import org.eclipse.equinox.p2.metadata.IInstallableUnitPatch; + +import java.util.Arrays; +import java.util.HashSet; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.UpdateWizard; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.Update; +import org.eclipse.equinox.p2.operations.UpdateOperation; import org.eclipse.equinox.p2.tests.ui.AbstractProvisioningUITest; public class UpdatePlanning extends AbstractProvisioningUITest { @@ -32,29 +38,31 @@ public class UpdatePlanning extends AbstractProvisioningUITest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0")); + a1 = createIU("A", Version.create("1.0.0")); IUpdateDescriptor update = MetadataFactory.createUpdateDescriptor("A", new VersionRange("[1.0.0, 1.0.0]"), 0, "update description"); - a120WithDifferentId = createIU("UpdateA", new Version(1, 2, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, false, update, NO_REQUIRES); - a130 = createIU("A", new Version(1, 3, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, false, update, NO_REQUIRES); - a140WithDifferentId = createIU("UpdateForA", new Version(1, 4, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, false, update, NO_REQUIRES); + a120WithDifferentId = createIU("UpdateA", Version.createOSGi(1, 2, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, false, update, NO_REQUIRES); + a130 = createIU("A", Version.createOSGi(1, 3, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, false, update, NO_REQUIRES); + a140WithDifferentId = createIU("UpdateForA", Version.createOSGi(1, 4, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, false, update, NO_REQUIRES); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequiredCapability lifeCycle = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"), null, false, false); - firstPatchForA1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle); - secondPatchForA1 = createIUPatch("P", new Version("2.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle); - thirdPatchForA1 = createIUPatch("P2", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle); + firstPatchForA1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle); + secondPatchForA1 = createIUPatch("P", Version.create("2.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle); + thirdPatchForA1 = createIUPatch("P2", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle); IRequirementChange change2 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequiredCapability lifeCycle2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 3.2.0]"), null, false, false); - patchFora2 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change2}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle2); + patchFora2 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change2}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle2); // Ensure that all versions, not just the latest, are considered by the UI - Policy.getDefault().getQueryContext().setShowLatestVersionsOnly(false); + getPolicy().setShowLatestVersionsOnly(false); } public void testChooseUpdateOverPatch() throws ProvisionException { createTestMetdataRepository(new IInstallableUnit[] {a1, a120WithDifferentId, a130, firstPatchForA1, patchFora2}); install(a1, true, false); - ProfileChangeRequest request = UpdateWizard.createProfileChangeRequest(new IInstallableUnit[] {a1}, profile.getProfileId(), null, null, getMonitor()); + UpdateOperation op = getProvisioningUI().getUpdateOperation(new IInstallableUnit[] {a1}, null); + op.resolveModal(getMonitor()); + ProfileChangeRequest request = op.getProfileChangeRequest(); assertTrue("1.0", request.getAddedInstallableUnits().length == 1); assertTrue("1.1", request.getAddedInstallableUnits()[0].equals(a130)); assertTrue("1.2", request.getRemovedInstallableUnits().length == 1); @@ -64,10 +72,20 @@ public class UpdatePlanning extends AbstractProvisioningUITest { public void testForcePatchOverUpdate() throws ProvisionException { createTestMetdataRepository(new IInstallableUnit[] {a1, a120WithDifferentId, a130, firstPatchForA1, patchFora2}); install(a1, true, false); - AvailableUpdateElement patch = new AvailableUpdateElement(null, firstPatchForA1, a1, profile.getProfileId(), false); - ArrayList initialSelections = new ArrayList(1); - initialSelections.add(patch); - ProfileChangeRequest request = UpdateWizard.createProfileChangeRequest(new IInstallableUnit[] {a1}, profile.getProfileId(), null, initialSelections, getMonitor()); + UpdateOperation op = getProvisioningUI().getUpdateOperation(new IInstallableUnit[] {a1}, null); + op.resolveModal(getMonitor()); + Update[] updates = op.getPossibleUpdates(); + Update firstPatch = null; + for (int i = 0; i < updates.length; i++) { + if (updates[i].replacement.equals(firstPatchForA1)) { + firstPatch = updates[i]; + break; + } + } + assertNotNull(".99", firstPatch); + op.setSelectedUpdates(new Update[] {firstPatch}); + op.resolveModal(getMonitor()); + ProfileChangeRequest request = op.getProfileChangeRequest(); assertTrue("1.0", request.getAddedInstallableUnits().length == 1); assertTrue("1.1", request.getAddedInstallableUnits()[0].equals(firstPatchForA1)); assertTrue("1.2", request.getRemovedInstallableUnits().length == 0); @@ -77,36 +95,47 @@ public class UpdatePlanning extends AbstractProvisioningUITest { createTestMetdataRepository(new IInstallableUnit[] {a1, a120WithDifferentId, a130, firstPatchForA1, patchFora2}); install(a1, true, false); install(firstPatchForA1, true, false); - IUElementListRoot root = new IUElementListRoot(); - ProfileChangeRequest request = UpdateWizard.createProfileChangeRequest(new IInstallableUnit[] {a1}, profile.getProfileId(), root, null, getMonitor()); + UpdateOperation op = getProvisioningUI().getUpdateOperation(new IInstallableUnit[] {a1}, null); + op.resolveModal(getMonitor()); + ProfileChangeRequest request = op.getProfileChangeRequest(); // update was favored, that would happen even if patch was not installed assertTrue("1.0", request.getAddedInstallableUnits().length == 1); assertTrue("1.1", request.getAddedInstallableUnits()[0].equals(a130)); // the patch is not being shown to the user because we figured out it was already installed // The elements showing are a130 and a120WithDifferentId - assertEquals("1.2", 2, root.getChildren(root).length); + assertEquals("1.2", 2, op.getPossibleUpdates().length); } public void testChooseNotTheNewest() throws ProvisionException { createTestMetdataRepository(new IInstallableUnit[] {a1, a120WithDifferentId, a130, firstPatchForA1, patchFora2}); install(a1, true, false); - AvailableUpdateElement notTheNewest = new AvailableUpdateElement(null, a120WithDifferentId, a1, profile.getProfileId(), false); - ArrayList initialSelections = new ArrayList(1); - initialSelections.add(notTheNewest); - IUElementListRoot root = new IUElementListRoot(); - ProfileChangeRequest request = UpdateWizard.createProfileChangeRequest(new IInstallableUnit[] {a1}, profile.getProfileId(), root, initialSelections, getMonitor()); + UpdateOperation op = getProvisioningUI().getUpdateOperation(new IInstallableUnit[] {a1}, null); + op.resolveModal(getMonitor()); + Update[] updates = op.getPossibleUpdates(); + Update notNewest = null; + for (int i = 0; i < updates.length; i++) { + if (updates[i].replacement.equals(a120WithDifferentId)) { + notNewest = updates[i]; + break; + } + } + assertNotNull(".99", notNewest); + op.setSelectedUpdates(new Update[] {notNewest}); + op.resolveModal(getMonitor()); + ProfileChangeRequest request = op.getProfileChangeRequest(); // selected was favored assertTrue("1.0", request.getAddedInstallableUnits().length == 1); assertTrue("1.1", request.getAddedInstallableUnits()[0].equals(a120WithDifferentId)); // The two updates and the patch were recognized - assertEquals("1.2", 3, root.getChildren(root).length); + assertEquals("1.2", 3, op.getPossibleUpdates().length); } public void testChooseLatestPatches() throws ProvisionException { createTestMetdataRepository(new IInstallableUnit[] {a1, firstPatchForA1, secondPatchForA1, thirdPatchForA1}); install(a1, true, false); - IUElementListRoot root = new IUElementListRoot(); - ProfileChangeRequest request = UpdateWizard.createProfileChangeRequest(new IInstallableUnit[] {a1}, profile.getProfileId(), root, null, getMonitor()); + UpdateOperation op = getProvisioningUI().getUpdateOperation(new IInstallableUnit[] {a1}, null); + op.resolveModal(getMonitor()); + ProfileChangeRequest request = op.getProfileChangeRequest(); // the latest two patches were selected HashSet chosen = new HashSet(); assertTrue("1.0", request.getAddedInstallableUnits().length == 2); @@ -114,18 +143,19 @@ public class UpdatePlanning extends AbstractProvisioningUITest { assertTrue("1.1", chosen.contains(secondPatchForA1)); assertTrue("1.2", chosen.contains(thirdPatchForA1)); - assertEquals("1.2", 3, root.getChildren(root).length); + assertEquals("1.2", 3, op.getPossibleUpdates().length); } public void testLatestHasDifferentId() throws ProvisionException { createTestMetdataRepository(new IInstallableUnit[] {a1, firstPatchForA1, secondPatchForA1, thirdPatchForA1, a120WithDifferentId, a130, a140WithDifferentId}); install(a1, true, false); - IUElementListRoot root = new IUElementListRoot(); - ProfileChangeRequest request = UpdateWizard.createProfileChangeRequest(new IInstallableUnit[] {a1}, profile.getProfileId(), root, null, getMonitor()); + UpdateOperation op = getProvisioningUI().getUpdateOperation(new IInstallableUnit[] {a1}, null); + op.resolveModal(getMonitor()); + ProfileChangeRequest request = op.getProfileChangeRequest(); // update 140 was recognized as the latest even though it had a different id assertTrue("1.0", request.getAddedInstallableUnits().length == 1); assertTrue("1.1", request.getAddedInstallableUnits()[0].equals(a140WithDifferentId)); // All three patches and all three updates can be chosen - assertEquals("1.2", 6, root.getChildren(root).length); + assertEquals("1.2", 6, op.getPossibleUpdates().length); } } diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AbstractQueryTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AbstractQueryTest.java index 9724a889e..0b8edfe2a 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AbstractQueryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AbstractQueryTest.java @@ -10,12 +10,13 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.query; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.MatchQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.IUViewQueryContext; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.MatchQuery; +import org.eclipse.equinox.p2.repository.IRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; +import org.eclipse.equinox.p2.ui.ProvisioningUI; /** * Abstract class to set up the mock query provider @@ -26,24 +27,25 @@ public abstract class AbstractQueryTest extends AbstractProvisioningTest { // use test query provider // This is really not how the default policy should be used in practice, // but we need to reset it for the tests. - Policy.getDefault().setQueryProvider(new MockQueryProvider(getMockQuery())); + ProvUI.setQueryProvider(new MockQueryProvider(getMockQuery(), ProvisioningUI.getDefaultUI())); // some of the test repos are set up as system repos so we need to // query all repos, not just non-system repos // TODO consider evolving these tests to distinguish between system // and non-system - IUViewQueryContext queryContext = new IUViewQueryContext(IUViewQueryContext.AVAILABLE_VIEW_BY_REPO); - queryContext.setArtifactRepositoryFlags(IRepositoryManager.REPOSITORIES_ALL); - queryContext.setMetadataRepositoryFlags(IRepositoryManager.REPOSITORIES_ALL); - Policy.getDefault().setQueryContext(queryContext); + RepositoryTracker manipulator = ProvisioningUI.getDefaultUI().getRepositoryTracker(); + manipulator.setArtifactRepositoryFlags(IRepositoryManager.REPOSITORIES_ALL); + manipulator.setMetadataRepositoryFlags(IRepositoryManager.REPOSITORIES_ALL); } protected void tearDown() throws Exception { super.tearDown(); - Policy.getDefault().setQueryProvider(null); - Policy.getDefault().setQueryContext(null); + RepositoryTracker manipulator = ProvisioningUI.getDefaultUI().getRepositoryTracker(); + manipulator.setArtifactRepositoryFlags(IRepositoryManager.REPOSITORIES_NON_SYSTEM); + manipulator.setMetadataRepositoryFlags(IRepositoryManager.REPOSITORIES_NON_SYSTEM); + ProvUI.setQueryProvider(null); } - protected Query getMockQuery() { + protected IQuery getMockQuery() { return new MatchQuery() { public boolean isMatch(Object candidate) { return true; diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AllTests.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AllTests.java index e81fbde80..0fd24d7c5 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AllTests.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AllTests.java @@ -22,7 +22,7 @@ public class AllTests extends TestCase { suite.addTestSuite(AnyRequiredCapabilityTest.class); suite.addTestSuite(AvailableIUWrapperTest.class); suite.addTestSuite(CategoryElementWrapperTest.class); - suite.addTestSuite(IUPropertyUtilsTest.class); + suite.addTestSuite(TranslationSupportTests.class); suite.addTestSuite(LatestIUVersionElementWrapperTest.class); suite.addTestSuite(QueryDescriptorTest.class); suite.addTestSuite(QueryableMetadataRepositoryManagerTest.class); diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AnyRequiredCapabilityTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AnyRequiredCapabilityTest.java index 61b6f2d98..b07ca1574 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AnyRequiredCapabilityTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AnyRequiredCapabilityTest.java @@ -13,31 +13,26 @@ package org.eclipse.equinox.p2.tests.ui.query; import java.net.URI; import java.util.ArrayList; import java.util.List; -import org.eclipse.equinox.internal.p2.ui.query.AnyRequiredCapabilityQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.QueryableMetadataRepositoryManager; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; +import org.eclipse.equinox.p2.metadata.query.ExpressionQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.TestData; +import org.eclipse.equinox.p2.ui.ProvisioningUI; -/** - * Tests for {@link AnyRequiredCapabilityQuery}. - */ public class AnyRequiredCapabilityTest extends AbstractQueryTest { public void testMatchOtherObjects() { - IRequiredCapability[] requires = createRequiredCapabilities("org.eclipse.equinox.p2.iu", "test.bundle", null); - AnyRequiredCapabilityQuery query = new AnyRequiredCapabilityQuery(requires); + IRequirement requires = MetadataFactory.createRequiredCapability("org.eclipse.equinox.p2.iu", "test.bundle", ANY_VERSION, null, false, false); IInstallableUnit match = createIU("test.bundle"); IInstallableUnit noMatch = createIU("another.bundle"); List items = new ArrayList(); items.add(match); items.add(noMatch); - items.add(new Object()); - items.add(requires); - Collector result = query.perform(items.iterator(), new Collector()); - assertEquals("1.0", 1, result.size()); + IQueryResult result = new ExpressionQuery(IInstallableUnit.class, requires.getMatches()).perform(items.iterator()); + assertEquals("1.0", 1, queryResultSize(result)); assertEquals("1.1", match, result.iterator().next()); } @@ -51,11 +46,10 @@ public class AnyRequiredCapabilityTest extends AbstractQueryTest { } IMetadataRepositoryManager metadataRepositoryManager = getMetadataRepositoryManager(); metadataRepositoryManager.addRepository(location); - QueryableMetadataRepositoryManager manager = new QueryableMetadataRepositoryManager(Policy.getDefault().getQueryContext(), false); - IRequiredCapability[] requires = createRequiredCapabilities("org.eclipse.equinox.p2.iu", "test.bundle", null); - AnyRequiredCapabilityQuery query = new AnyRequiredCapabilityQuery(requires); - Collector result = manager.query(query, new Collector(), getMonitor()); - assertEquals("1.0", 1, result.size()); + QueryableMetadataRepositoryManager manager = new QueryableMetadataRepositoryManager(ProvisioningUI.getDefaultUI(), false); + IRequirement requires = MetadataFactory.createRequiredCapability("org.eclipse.equinox.p2.iu", "test.bundle", ANY_VERSION, null, false, false); + IQueryResult result = manager.query(new ExpressionQuery(IInstallableUnit.class, requires.getMatches()), getMonitor()); + assertEquals("1.0", 1, queryResultSize(result)); IInstallableUnit iu = (IInstallableUnit) result.iterator().next(); assertEquals("1.1", "test.bundle", iu.getId()); } diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AvailableIUWrapperTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AvailableIUWrapperTest.java index 7c7a0a127..79e3f86c1 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AvailableIUWrapperTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/AvailableIUWrapperTest.java @@ -11,15 +11,18 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.query; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.util.*; +import org.eclipse.equinox.internal.p2.metadata.query.IUPropertyQuery; import org.eclipse.equinox.internal.p2.ui.model.CategoryElement; import org.eclipse.equinox.internal.p2.ui.model.IIUElement; import org.eclipse.equinox.internal.p2.ui.query.AvailableIUWrapper; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.Collector; +import org.eclipse.equinox.p2.query.IQuery; import org.eclipse.equinox.p2.tests.MockQueryable; /** @@ -75,8 +78,8 @@ public class AvailableIUWrapperTest extends AbstractQueryTest { AvailableIUWrapper wrapper = createWrapper(true); Collector collector = new Collector(); Map properties = new HashMap(); - properties.put(IInstallableUnit.PROP_TYPE_CATEGORY, "true"); - IInstallableUnit category = createIU("category", new Version(1, 0, 0), NO_REQUIRES, properties, false); + properties.put(InstallableUnitDescription.PROP_TYPE_CATEGORY, "true"); + IInstallableUnit category = createIU("category", Version.createOSGi(1, 0, 0), NO_REQUIRES, properties, false); IInstallableUnit unit = createIU("basicIU"); collector.accept(category); collector.accept(unit); @@ -104,8 +107,8 @@ public class AvailableIUWrapperTest extends AbstractQueryTest { AvailableIUWrapper wrapper = createWrapper(false); Collector collector = new Collector(); Map properties = new HashMap(); - properties.put(IInstallableUnit.PROP_TYPE_CATEGORY, "true"); - IInstallableUnit category = createIU("category", new Version(1, 0, 0), NO_REQUIRES, properties, false); + properties.put(InstallableUnitDescription.PROP_TYPE_CATEGORY, "true"); + IInstallableUnit category = createIU("category", Version.createOSGi(1, 0, 0), NO_REQUIRES, properties, false); IInstallableUnit unit = createIU("basicIU"); collector.accept(category); collector.accept(unit); @@ -149,7 +152,7 @@ public class AvailableIUWrapperTest extends AbstractQueryTest { assertEquals("1.2", notInstalled, getIU(iuElement)); } - protected Query getMockQuery() { + protected IQuery getMockQuery() { return new IUPropertyQuery("key", "value"); } } diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/CategoryElementWrapperTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/CategoryElementWrapperTest.java index 8e5378257..4a2470e71 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/CategoryElementWrapperTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/CategoryElementWrapperTest.java @@ -10,16 +10,18 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.query; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.util.Collection; import java.util.Iterator; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.p2.ui.model.CategoryElement; import org.eclipse.equinox.internal.p2.ui.model.EmptyElementExplanation; import org.eclipse.equinox.internal.p2.ui.query.CategoryElementWrapper; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.Collector; import org.eclipse.equinox.p2.tests.MockQueryable; /** @@ -36,7 +38,7 @@ public class CategoryElementWrapperTest extends AbstractQueryTest { iu.setId(id); iu.setVersion(version); iu.setProperty(IInstallableUnit.PROP_NAME, name); - iu.setProperty(IInstallableUnit.PROP_TYPE_CATEGORY, Boolean.toString(true)); + iu.setProperty(InstallableUnitDescription.PROP_TYPE_CATEGORY, Boolean.toString(true)); return MetadataFactory.createInstallableUnit(iu); } @@ -84,7 +86,7 @@ public class CategoryElementWrapperTest extends AbstractQueryTest { assertEquals("1.6", 1, results.size()); //adding a nested category shouldn't affected size - IRequiredCapability[] required = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "category1", null); + IRequiredCapability[] required = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "category1"); IInstallableUnit nested = createIU("Nested", required); collector.accept(nested); results = wrapper.getElements(collector); diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/IUPropertyUtilsTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/IUPropertyUtilsTest.java deleted file mode 100644 index 2d4980245..000000000 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/IUPropertyUtilsTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * EclipseSource - bug fixing - *******************************************************************************/ -package org.eclipse.equinox.p2.tests.ui.query; - -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; - -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Locale; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.engine.Profile; -import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitFragmentDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.IUPropertyUtils; -import org.eclipse.equinox.p2.tests.TestActivator; - -/** - * Tests for {@link IUPropertyUtils}. - */ -public class IUPropertyUtilsTest extends AbstractQueryTest { - public void testFeatureProperties() { - IMetadataRepositoryManager repoMan = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.class.getName()); - File site = getTestData("0.1", "/testData/metadataRepo/externalized"); - URI location = site.toURI(); - IMetadataRepository repository; - try { - repository = repoMan.loadRepository(location, getMonitor()); - } catch (ProvisionException e) { - fail("1.99", e); - return; - } - Collector result = repository.query(new InstallableUnitQuery("test.feature.feature.group"), new Collector(), getMonitor()); - assertTrue("1.0", !result.isEmpty()); - IInstallableUnit unit = (IInstallableUnit) result.iterator().next(); - - ICopyright copyright = org.eclipse.equinox.internal.provisional.p2.ui.IUPropertyUtils.getCopyright(unit); - assertEquals("1.1", "Test Copyright", copyright.getBody()); - ILicense license = IUPropertyUtils.getLicense(unit); - assertEquals("1.2", "Test License", license.getBody()); - // assertEquals("1.3", "license.html", license.getURL().toExternalForm()); - String name = IUPropertyUtils.getIUProperty(unit, IInstallableUnit.PROP_NAME); - assertEquals("1.4", "Test Feature Name", name); - String description = IUPropertyUtils.getIUProperty(unit, IInstallableUnit.PROP_DESCRIPTION); - assertEquals("1.5", "Test Description", description); - String provider = IUPropertyUtils.getIUProperty(unit, IInstallableUnit.PROP_PROVIDER); - assertEquals("1.6", "Test Provider Name", provider); - } - - public void testLocalizedLicense() throws URISyntaxException { - SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName()); - Profile profile = (Profile) profileRegistry.getProfile(IProfileRegistry.SELF); - profileRegistry.lockProfile(profile); - String germanLicense = "German License"; - String canadianFRLicense = "Canadian French License"; - - // Create a IU that has a license, but the license body is simply %license. This will be filled in by - // a fragment - InstallableUnitDescription iuDescription = new InstallableUnitDescription(); - iuDescription.setId("some IU"); - iuDescription.setVersion(new Version(1, 0, 0)); - iuDescription.setLicense(MetadataFactory.createLicense(new URI("http://example.com"), "%license")); - IInstallableUnit iu = MetadataFactory.createInstallableUnit(iuDescription); - - // Create a bunch of fragments which spec our IU as their host - // These fragments don't contribute language information - for (int i = 0; i < 10; i++) { - InstallableUnitFragmentDescription installableUnitFragmentDescription = new InstallableUnitFragmentDescription(); - installableUnitFragmentDescription.setId("fragment number: " + i); - installableUnitFragmentDescription.setVersion(new Version(1, 0, 0)); - installableUnitFragmentDescription.setHost(new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "some IU", ANY_VERSION, null, false, false)}); - installableUnitFragmentDescription.setProperty(IInstallableUnit.PROP_TYPE_FRAGMENT, "true"); - IInstallableUnitFragment iuFragment = MetadataFactory.createInstallableUnitFragment(installableUnitFragmentDescription); - profile.addInstallableUnit(iuFragment); - } - - // Create fragment with a German license - InstallableUnitFragmentDescription installableUnitFragmentDescription = new InstallableUnitFragmentDescription(); - IProvidedCapability providedCapability = MetadataFactory.createProvidedCapability("org.eclipse.equinox.p2.localization", "de", new Version(1, 0, 0)); - ArrayList list = new ArrayList(); - list.add(providedCapability); - installableUnitFragmentDescription.addProvidedCapabilities(list); - installableUnitFragmentDescription.setId("german fragment"); - installableUnitFragmentDescription.setVersion(new Version(1, 0, 0)); - installableUnitFragmentDescription.setHost(new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "some IU", ANY_VERSION, null, false, false)}); - installableUnitFragmentDescription.setProperty(IInstallableUnit.PROP_TYPE_FRAGMENT, "true"); - installableUnitFragmentDescription.setProperty("de.license", germanLicense); - IInstallableUnitFragment iuFragment = MetadataFactory.createInstallableUnitFragment(installableUnitFragmentDescription); - profile.addInstallableUnit(iuFragment); - - // Create a French fragment with an fr_CA license - installableUnitFragmentDescription = new InstallableUnitFragmentDescription(); - providedCapability = MetadataFactory.createProvidedCapability("org.eclipse.equinox.p2.localization", "fr", new Version(1, 0, 0)); - list = new ArrayList(); - list.add(providedCapability); - installableUnitFragmentDescription.addProvidedCapabilities(list); - installableUnitFragmentDescription.setId("cnd french fragment"); - installableUnitFragmentDescription.setVersion(new Version(1, 0, 0)); - installableUnitFragmentDescription.setHost(new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "some IU", ANY_VERSION, null, false, false)}); - installableUnitFragmentDescription.setProperty(IInstallableUnit.PROP_TYPE_FRAGMENT, "true"); - installableUnitFragmentDescription.setProperty("fr_CA.license", canadianFRLicense); - iuFragment = MetadataFactory.createInstallableUnitFragment(installableUnitFragmentDescription); - - profile.addInstallableUnit(iuFragment); - profile.addInstallableUnit(iu); - - profileRegistry.updateProfile(profile); - profileRegistry.unlockProfile(profile); - - ILicense license = IUPropertyUtils.getLicense(iu, Locale.GERMAN); - assertEquals("1.0", germanLicense, license.getBody()); - license = IUPropertyUtils.getLicense(iu, Locale.CANADA_FRENCH); - assertEquals("1.1", canadianFRLicense, license.getBody()); - } - - public void testBasicIU() { - IInstallableUnit unit = createIU("f1"); - - assertNull("1.1", IUPropertyUtils.getCopyright(unit)); - assertNull("1.2", IUPropertyUtils.getLicense(unit)); - assertNull("1.3", IUPropertyUtils.getIUProperty(unit, IInstallableUnit.PROP_NAME)); - assertNull("1.4", IUPropertyUtils.getIUProperty(unit, IInstallableUnit.PROP_DESCRIPTION)); - assertNull("1.5", IUPropertyUtils.getIUProperty(unit, IInstallableUnit.PROP_PROVIDER)); - } -} diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/LatestIUVersionElementWrapperTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/LatestIUVersionElementWrapperTest.java index 28a540bf6..a98519434 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/LatestIUVersionElementWrapperTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/LatestIUVersionElementWrapperTest.java @@ -11,13 +11,14 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.query; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import org.eclipse.equinox.internal.p2.metadata.query.LatestIUVersionQuery; import org.eclipse.equinox.internal.p2.ui.model.IIUElement; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.LatestIUVersionQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQueryResult; /** * Tests for {@link LatestIUVersionQuery}. This has all the tests of the superclass, @@ -34,42 +35,29 @@ public class LatestIUVersionElementWrapperTest extends AvailableIUWrapperTest { return ((IIUElement) collected).getIU(); } - /** - * Tests collecting items that LatestIUVersionElementQuery should - * discard. - */ - public void testCollectObject() { - LatestIUVersionQuery latestIuVersionElementQuery = new LatestIUVersionQuery(); - Object object = new Object(); - List list = new ArrayList(); - list.add(object); - Collector collector = latestIuVersionElementQuery.perform(list.iterator(), new Collector()); - assertEquals("1.0", 0, collector.size()); - } - /** * Tests that only the latest version is collected. */ public void testCollectLatestIU() { LatestIUVersionQuery latestIuVersionElementQuery = new LatestIUVersionQuery(); - IInstallableUnit unit1 = createIU("f1", new Version(1, 0, 0)); - IInstallableUnit unit2 = createIU("f1", new Version(1, 0, 1)); + IInstallableUnit unit1 = createIU("f1", Version.createOSGi(1, 0, 0)); + IInstallableUnit unit2 = createIU("f1", Version.createOSGi(1, 0, 1)); List listOfIUs = new ArrayList(); listOfIUs.add(unit1); listOfIUs.add(unit2); - Collector collector = latestIuVersionElementQuery.perform(listOfIUs.iterator(), new Collector()); - assertEquals("1.0", 1, collector.size()); + IQueryResult collector = latestIuVersionElementQuery.perform(listOfIUs.iterator()); + assertEquals("1.0", 1, queryResultSize(collector)); IInstallableUnit collectedIU = getIU(collector.iterator().next()); assertEquals("1.1", unit2, collectedIU); } public void testMultipleIUsAndVersions() { LatestIUVersionQuery latestIuVersionElementQuery = new LatestIUVersionQuery(); - IInstallableUnit unit1 = createIU("A", new Version(1, 0, 0)); - IInstallableUnit unit2 = createIU("A", new Version(1, 0, 1)); - IInstallableUnit unit3 = createIU("B", new Version(1, 0, 1)); - IInstallableUnit unit4 = createIU("B", new Version(0, 1, 1)); - IInstallableUnit unit5 = createIU("C", new Version(0, 1, 1)); + IInstallableUnit unit1 = createIU("A", Version.createOSGi(1, 0, 0)); + IInstallableUnit unit2 = createIU("A", Version.createOSGi(1, 0, 1)); + IInstallableUnit unit3 = createIU("B", Version.createOSGi(1, 0, 1)); + IInstallableUnit unit4 = createIU("B", Version.createOSGi(0, 1, 1)); + IInstallableUnit unit5 = createIU("C", Version.createOSGi(0, 1, 1)); // We should get unit 2, unit 3 and unit 5 List listOfIUs = new ArrayList(); @@ -78,14 +66,13 @@ public class LatestIUVersionElementWrapperTest extends AvailableIUWrapperTest { listOfIUs.add(unit3); listOfIUs.add(unit4); listOfIUs.add(unit5); - Collector collector = latestIuVersionElementQuery.perform(listOfIUs.iterator(), new Collector()); + IQueryResult collector = latestIuVersionElementQuery.perform(listOfIUs.iterator()); // Should be 3 units - assertEquals("1.0", 3, collector.size()); - Collection reslts = collector.toCollection(); - assertTrue("1.2", reslts.contains(unit2)); - assertTrue("1.3", reslts.contains(unit3)); - assertTrue("1.4", reslts.contains(unit5)); + assertEquals("1.0", 3, queryResultSize(collector)); + assertContains("1.2", collector, unit2); + assertContains("1.3", collector, unit3); + assertContains("1.4", collector, unit5); } } diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/MockQueryProvider.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/MockQueryProvider.java index 56469c088..e00efe369 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/MockQueryProvider.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/MockQueryProvider.java @@ -10,22 +10,22 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.query; -import org.eclipse.equinox.internal.p2.ui.DefaultQueryProvider; +import org.eclipse.equinox.internal.p2.ui.ElementQueryDescriptor; +import org.eclipse.equinox.internal.p2.ui.QueryProvider; import org.eclipse.equinox.internal.p2.ui.model.QueriedElement; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; -import org.eclipse.equinox.internal.provisional.p2.ui.ElementQueryDescriptor; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.p2.query.Collector; +import org.eclipse.equinox.p2.query.IQuery; import org.eclipse.equinox.p2.tests.MockQueryable; +import org.eclipse.equinox.p2.ui.ProvisioningUI; /** * A fake query provider for unit testing. */ -public class MockQueryProvider extends DefaultQueryProvider { - private Query query; +public class MockQueryProvider extends QueryProvider { + private IQuery query; - public MockQueryProvider(Query query) { - super(Policy.getDefault()); + public MockQueryProvider(IQuery query, ProvisioningUI ui) { + super(ui); this.query = query; } diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/QueryDescriptorTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/QueryDescriptorTest.java index 4cd2be85b..745e45f88 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/QueryDescriptorTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/QueryDescriptorTest.java @@ -12,9 +12,9 @@ package org.eclipse.equinox.p2.tests.ui.query; import java.util.*; import junit.framework.TestCase; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.ui.ElementQueryDescriptor; -import org.eclipse.equinox.internal.provisional.p2.ui.ElementWrapper; +import org.eclipse.equinox.internal.p2.ui.ElementQueryDescriptor; +import org.eclipse.equinox.internal.p2.ui.ElementWrapper; +import org.eclipse.equinox.p2.query.*; /** * Tests the Query Descriptor @@ -24,8 +24,9 @@ public class QueryDescriptorTest extends TestCase { class SimpleQueryable implements IQueryable { List elements = Arrays.asList(new String[] {"a", "b", "c", "d", "e"}); - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - return query.perform(elements.iterator(), collector); + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + Collector collector = new Collector(); + return query.perform(elements.iterator()); } } @@ -98,7 +99,7 @@ public class QueryDescriptorTest extends TestCase { } public void testCompoundDescriptorAND() { - Query query = CompoundQuery.createCompoundQuery(new Query[] {new SimpleMatchQuery(), new SimpleMatchQuery2()}, true); + IQuery query = CompoundQuery.createCompoundQuery(new IQuery[] {new SimpleMatchQuery(), new SimpleMatchQuery2()}, true); ElementQueryDescriptor eqDescriptor = new ElementQueryDescriptor(new SimpleQueryable(), query, new Collector(), new StringWrapper()); Collection collection = eqDescriptor.performQuery(null); assertEquals("1.0", 1, collection.size()); @@ -106,7 +107,7 @@ public class QueryDescriptorTest extends TestCase { } public void testCompoundDescriptorOR() { - Query query = CompoundQuery.createCompoundQuery(new Query[] {new SimpleMatchQuery(), new SimpleMatchQuery2()}, false); + IQuery query = CompoundQuery.createCompoundQuery(new IQuery[] {new SimpleMatchQuery(), new SimpleMatchQuery2()}, false); ElementQueryDescriptor eqDescriptor = new ElementQueryDescriptor(new SimpleQueryable(), query, new Collector(), new StringWrapper()); Collection collection = eqDescriptor.performQuery(null); assertEquals("1.0", 3, collection.size()); diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/QueryableArtifactRepositoryManagerTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/QueryableArtifactRepositoryManagerTest.java index 11094605e..4f2fd7e7e 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/QueryableArtifactRepositoryManagerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/QueryableArtifactRepositoryManagerTest.java @@ -11,11 +11,11 @@ package org.eclipse.equinox.p2.tests.ui.query; import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.ui.QueryableArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.RepositoryLocationQuery; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.QueryableArtifactRepositoryManager; +import org.eclipse.equinox.internal.p2.ui.RepositoryLocationQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.ui.ProvisioningUI; public class QueryableArtifactRepositoryManagerTest extends AbstractQueryTest { private static final String repositoryOne = "http://one.lan"; @@ -43,12 +43,11 @@ public class QueryableArtifactRepositoryManagerTest extends AbstractQueryTest { public void testQuery() { QueryableArtifactRepositoryManager manager = getQueryableManager(); - Collector result = new Collector(); - manager.query(new RepositoryLocationQuery(), result, getMonitor()); - assertTrue(result.size() == repoCount); + IQueryResult result = manager.locationsQueriable().query(new RepositoryLocationQuery(), getMonitor()); + assertTrue(queryResultSize(result) == repoCount); } private QueryableArtifactRepositoryManager getQueryableManager() { - return new QueryableArtifactRepositoryManager(Policy.getDefault().getQueryContext(), false); + return new QueryableArtifactRepositoryManager(ProvisioningUI.getDefaultUI(), false); } } diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/QueryableMetadataRepositoryManagerTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/QueryableMetadataRepositoryManagerTest.java index 71e545d20..7d9d033f5 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/QueryableMetadataRepositoryManagerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/QueryableMetadataRepositoryManagerTest.java @@ -10,22 +10,29 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ui.query; +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; + import java.io.File; import java.net.URI; import java.util.Collection; import org.eclipse.core.tests.harness.CancelingProgressMonitor; -import org.eclipse.equinox.internal.p2.ui.DefaultQueryProvider; +import org.eclipse.equinox.internal.p2.metadata.query.IUPropertyQuery; +import org.eclipse.equinox.internal.p2.ui.*; import org.eclipse.equinox.internal.p2.ui.model.AvailableIUElement; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.model.MetadataRepositories; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.IUViewQueryContext; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositories; +import org.eclipse.equinox.internal.p2.ui.query.IUViewQueryContext; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProvisioningJob; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.TestData; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; +import org.eclipse.equinox.p2.ui.ProvisioningUI; /** * Tests for {@link QueryableMetadataRepositoryManager}. @@ -34,6 +41,16 @@ public class QueryableMetadataRepositoryManagerTest extends AbstractQueryTest { /** * Tests querying against a non-existent repository */ + + ProvisioningUI ui; + ProvisioningSession session; + + protected void setUp() throws Exception { + ui = ProvisioningUI.getDefaultUI(); + session = ui.getSession(); + super.setUp(); + } + public void testBrokenRepository() { URI brokenRepo; try { @@ -47,7 +64,8 @@ public class QueryableMetadataRepositoryManagerTest extends AbstractQueryTest { QueryableMetadataRepositoryManager manager = getQueryableManager(); assertTrue("1.0", !manager.areRepositoriesLoaded()); - manager.loadAll(getMonitor()); + ProvisioningJob loadJob = new LoadMetadataRepositoryJob(ui); + loadJob.runModal(getMonitor()); //false because the broken repository is not loaded assertTrue("1.1", !manager.areRepositoriesLoaded()); @@ -69,7 +87,8 @@ public class QueryableMetadataRepositoryManagerTest extends AbstractQueryTest { QueryableMetadataRepositoryManager manager = getQueryableManager(); assertTrue("1.0", !manager.areRepositoriesLoaded()); - manager.loadAll(new CancelingProgressMonitor()); + ProvisioningJob loadJob = new LoadMetadataRepositoryJob(ui); + loadJob.runModal(new CancelingProgressMonitor()); //should not be loaded due to cancelation assertTrue("1.1", !manager.areRepositoriesLoaded()); @@ -91,12 +110,8 @@ public class QueryableMetadataRepositoryManagerTest extends AbstractQueryTest { metadataRepositoryManager.addRepository(broken); QueryableMetadataRepositoryManager manager = getQueryableManager(); - Collector result = manager.query(new InstallableUnitQuery("test.bundle", new Version(1, 0, 0)), new Collector(), new CancelingProgressMonitor()); - assertEquals("1.0", 0, result.size()); - - //null query collects repository URLs - result = manager.query(null, new Collector(), new CancelingProgressMonitor()); - assertEquals("2.0", 0, result.size()); + IQueryResult result = manager.query(new InstallableUnitQuery("test.bundle", Version.createOSGi(1, 0, 0)), new CancelingProgressMonitor()); + assertTrue("1.0", result.isEmpty()); } public void testExistingRepository() { @@ -112,10 +127,12 @@ public class QueryableMetadataRepositoryManagerTest extends AbstractQueryTest { QueryableMetadataRepositoryManager manager = getQueryableManager(); assertTrue("1.0", !manager.areRepositoriesLoaded()); - manager.loadAll(getMonitor()); + ProvisioningJob loadJob = new LoadMetadataRepositoryJob(ui); + loadJob.runModal(getMonitor()); - //we can never be sure that repositories are loaded because the repository manager cache can be flushed at any time - // assertTrue("1.1", manager.areRepositoriesLoaded()); + // the provisioning job retains references to the repos so they should + // not get garbage collected. + assertTrue("1.1", manager.areRepositoriesLoaded()); } /** @@ -137,7 +154,8 @@ public class QueryableMetadataRepositoryManagerTest extends AbstractQueryTest { // not loaded yet assertFalse("1.0", manager.areRepositoriesLoaded()); - manager.loadAll(getMonitor()); + ProvisioningJob loadJob = new LoadMetadataRepositoryJob(ui); + loadJob.runModal(getMonitor()); // the repositories have been loaded. Because the non-existent // repository has been noticed and recorded as missing, it @@ -161,24 +179,23 @@ public class QueryableMetadataRepositoryManagerTest extends AbstractQueryTest { metadataRepositoryManager.addRepository(broken); QueryableMetadataRepositoryManager manager = getQueryableManager(); - Collector result = manager.query(new InstallableUnitQuery("test.bundle", new Version(1, 0, 0)), new Collector(), getMonitor()); - assertEquals("1.0", 1, result.size()); + IQueryResult result = manager.query(new InstallableUnitQuery("test.bundle", Version.createOSGi(1, 0, 0)), getMonitor()); + assertEquals("1.0", 1, queryResultSize(result)); IInstallableUnit iu = (IInstallableUnit) result.iterator().next(); assertEquals("1.1", "test.bundle", iu.getId()); //RepoLocationQuery collects repository URLs - result = manager.query(new RepositoryLocationQuery(), new Collector(), getMonitor()); - assertEquals("2.0", 3, result.size()); - Collection resultCollection = result.toCollection(); - assertTrue("2.1", resultCollection.contains(existing)); - assertTrue("2.1", resultCollection.contains(nonExisting)); - assertTrue("2.1", resultCollection.contains(broken)); + result = manager.locationsQueriable().query(new RepositoryLocationQuery(), getMonitor()); + assertEquals("2.0", 3, queryResultSize(result)); + assertContains("2.1", result, existing); + assertContains("2.1", result, nonExisting); + assertContains("2.1", result, broken); // null IUPropertyQuery collects all IUs - result = manager.query(new InstallableUnitQuery((String) null), new Collector(), getMonitor()); - int iuCount = result.size(); - result = manager.query(new IUPropertyQuery(null, null), new Collector(), getMonitor()); - assertEquals("2.2", iuCount, result.size()); + result = manager.query(new InstallableUnitQuery((String) null), getMonitor()); + int iuCount = queryResultSize(result); + result = manager.query(new IUPropertyQuery(null, null), getMonitor()); + assertEquals("2.2", iuCount, queryResultSize(result)); } public void testNonLatestInMultipleRepositories() { @@ -198,8 +215,8 @@ public class QueryableMetadataRepositoryManagerTest extends AbstractQueryTest { IUViewQueryContext context = new IUViewQueryContext(IUViewQueryContext.AVAILABLE_VIEW_FLAT); context.setShowLatestVersionsOnly(false); - MetadataRepositories rootElement = new MetadataRepositories(context, Policy.getDefault(), manager); - DefaultQueryProvider queryProvider = new DefaultQueryProvider(Policy.getDefault()); + MetadataRepositories rootElement = new MetadataRepositories(context, ui, manager); + QueryProvider queryProvider = new QueryProvider(ui); ElementQueryDescriptor queryDescriptor = queryProvider.getQueryDescriptor(rootElement); Collection collection = queryDescriptor.performQuery(null); assertEquals("1.0", 5, collection.size()); @@ -222,14 +239,13 @@ public class QueryableMetadataRepositoryManagerTest extends AbstractQueryTest { IUViewQueryContext context = new IUViewQueryContext(IUViewQueryContext.AVAILABLE_VIEW_FLAT); context.setShowLatestVersionsOnly(true); - MetadataRepositories rootElement = new MetadataRepositories(context, Policy.getDefault(), manager); - manager.setQueryContext(context); - DefaultQueryProvider queryProvider = new DefaultQueryProvider(Policy.getDefault()); + MetadataRepositories rootElement = new MetadataRepositories(context, ui, manager); + QueryProvider queryProvider = new QueryProvider(ui); ElementQueryDescriptor queryDescriptor = queryProvider.getQueryDescriptor(rootElement); Collection collection = queryDescriptor.performQuery(null); assertEquals("1.0", 1, collection.size()); AvailableIUElement next = (AvailableIUElement) collection.iterator().next(); - assertEquals("1.1", new Version(3, 0, 0), next.getIU().getVersion()); + assertEquals("1.1", Version.createOSGi(3, 0, 0), next.getIU().getVersion()); } /** @@ -240,19 +256,22 @@ public class QueryableMetadataRepositoryManagerTest extends AbstractQueryTest { try { location = TestData.getFile("metadataRepo", "good").toURI(); } catch (Exception e) { - fail("0.99", e); + fail("0.98", e); return; } IMetadataRepositoryManager metadataRepositoryManager = getMetadataRepositoryManager(); metadataRepositoryManager.removeRepository(location); metadataRepositoryManager.addRepository(location); - QueryableMetadataRepositoryManager manager = getQueryableManager(); - manager.loadAll(getMonitor()); + try { + ui.loadMetadataRepository(location, false, getMonitor()); + } catch (ProvisionException e) { + fail("0.99", e); + } assertEquals("1.0", "Good Test Repository", metadataRepositoryManager.getRepositoryProperty(location, IRepository.PROP_NICKNAME)); } private QueryableMetadataRepositoryManager getQueryableManager() { - return new QueryableMetadataRepositoryManager(Policy.getDefault().getQueryContext(), false); + return new QueryableMetadataRepositoryManager(ui, false); } } diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/TranslationSupportTests.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/TranslationSupportTests.java new file mode 100644 index 000000000..e7600a856 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/query/TranslationSupportTests.java @@ -0,0 +1,159 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * EclipseSource - bug fixing + *******************************************************************************/ +package org.eclipse.equinox.p2.tests.ui.query; + +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.p2.metadata.IProvidedCapability; + +import org.eclipse.equinox.p2.metadata.IInstallableUnitFragment; +import org.eclipse.equinox.p2.metadata.ILicense; + +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; + +import java.io.File; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.internal.p2.engine.Profile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.p2.metadata.TranslationSupport; +import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitFragmentDescription; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.ICopyright; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.tests.TestActivator; + +/** + * Tests for {@link TranslationSupport}. + */ +public class TranslationSupportTests extends AbstractQueryTest { + Profile profile; + IQueryable oldTranslationSource; + + protected void setUp() throws Exception { + super.setUp(); + profile = (Profile) createProfile("testLocalizedLicense"); + oldTranslationSource = TranslationSupport.getInstance().setTranslationSource(profile); + } + + protected void tearDown() throws Exception { + super.tearDown(); + TranslationSupport.getInstance().setTranslationSource(oldTranslationSource); + } + + public void testFeatureProperties() { + IMetadataRepositoryManager repoMan = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); + File site = getTestData("0.1", "/testData/metadataRepo/externalized"); + URI location = site.toURI(); + IMetadataRepository repository; + try { + repository = repoMan.loadRepository(location, getMonitor()); + } catch (ProvisionException e) { + fail("1.99", e); + return; + } + IQueryResult result = repository.query(new InstallableUnitQuery("test.feature.feature.group"), getMonitor()); + assertTrue("1.0", !result.isEmpty()); + IInstallableUnit unit = (IInstallableUnit) result.iterator().next(); + + ICopyright copyright = unit.getCopyright(null); + assertEquals("1.1", "Test Copyright", copyright.getBody()); + ILicense license = unit.getLicenses(null)[0]; + assertEquals("1.2", "Test License", license.getBody()); + // assertEquals("1.3", "license.html", license.getURL().toExternalForm()); + String name = unit.getProperty(IInstallableUnit.PROP_NAME, null); + assertEquals("1.4", "Test Feature Name", name); + String description = unit.getProperty(IInstallableUnit.PROP_DESCRIPTION, null); + assertEquals("1.5", "Test Description", description); + String provider = unit.getProperty(IInstallableUnit.PROP_PROVIDER, null); + assertEquals("1.6", "Test Provider Name", provider); + } + + public void testLocalizedLicense() throws URISyntaxException { + String germanLicense = "German License"; + String canadianFRLicense = "Canadian French License"; + + // Create a IU that has a license, but the license body is simply %license. This will be filled in by + // a fragment + InstallableUnitDescription iuDescription = new InstallableUnitDescription(); + iuDescription.setId("some IU"); + iuDescription.setVersion(Version.createOSGi(1, 0, 0)); + iuDescription.setLicenses(new ILicense[] {MetadataFactory.createLicense(new URI("http://example.com"), "%license")}); + iuDescription.addProvidedCapabilities(Collections.singleton(MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, "some IU", Version.createOSGi(1, 0, 0)))); + IInstallableUnit iu = MetadataFactory.createInstallableUnit(iuDescription); + + // Create a bunch of fragments which spec our IU as their host + // These fragments don't contribute language information + for (int i = 0; i < 10; i++) { + InstallableUnitFragmentDescription installableUnitFragmentDescription = new InstallableUnitFragmentDescription(); + installableUnitFragmentDescription.setId("fragment number: " + i); + installableUnitFragmentDescription.setVersion(Version.createOSGi(1, 0, 0)); + installableUnitFragmentDescription.setHost(new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "some IU", ANY_VERSION, null, false, false)}); + installableUnitFragmentDescription.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, "true"); + IInstallableUnitFragment iuFragment = MetadataFactory.createInstallableUnitFragment(installableUnitFragmentDescription); + profile.addInstallableUnit(iuFragment); + } + + // Create fragment with a German license + InstallableUnitFragmentDescription installableUnitFragmentDescription = new InstallableUnitFragmentDescription(); + IProvidedCapability providedCapability = MetadataFactory.createProvidedCapability("org.eclipse.equinox.p2.localization", "de", Version.createOSGi(1, 0, 0)); + ArrayList list = new ArrayList(); + list.add(providedCapability); + installableUnitFragmentDescription.addProvidedCapabilities(list); + installableUnitFragmentDescription.setId("german fragment"); + installableUnitFragmentDescription.setVersion(Version.createOSGi(1, 0, 0)); + installableUnitFragmentDescription.setHost(new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "some IU", ANY_VERSION, null, false, false)}); + installableUnitFragmentDescription.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, "true"); + installableUnitFragmentDescription.setProperty("de.license", germanLicense); + IInstallableUnitFragment iuFragment = MetadataFactory.createInstallableUnitFragment(installableUnitFragmentDescription); + profile.addInstallableUnit(iuFragment); + + // Create a French fragment with an fr_CA license + installableUnitFragmentDescription = new InstallableUnitFragmentDescription(); + providedCapability = MetadataFactory.createProvidedCapability("org.eclipse.equinox.p2.localization", "fr", Version.createOSGi(1, 0, 0)); + list = new ArrayList(); + list.add(providedCapability); + installableUnitFragmentDescription.addProvidedCapabilities(list); + installableUnitFragmentDescription.setId("cnd french fragment"); + installableUnitFragmentDescription.setVersion(Version.createOSGi(1, 0, 0)); + installableUnitFragmentDescription.setHost(new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "some IU", ANY_VERSION, null, false, false)}); + installableUnitFragmentDescription.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, "true"); + installableUnitFragmentDescription.setProperty("fr_CA.license", canadianFRLicense); + iuFragment = MetadataFactory.createInstallableUnitFragment(installableUnitFragmentDescription); + + profile.addInstallableUnit(iuFragment); + profile.addInstallableUnit(iu); + + ILicense license = iu.getLicenses(Locale.GERMAN.toString())[0]; + assertEquals("1.0", germanLicense, license.getBody()); + license = iu.getLicenses(Locale.CANADA_FRENCH.toString())[0]; + assertEquals("1.1", canadianFRLicense, license.getBody()); + } + + public void testBasicIU() { + IInstallableUnit unit = createIU("f1"); + + assertNull("1.1", unit.getCopyright(null)); + assertEquals("1.2", 0, unit.getLicenses(null).length);; + assertNull("1.3", unit.getProperty(IInstallableUnit.PROP_NAME, null)); + assertNull("1.4", unit.getProperty(IInstallableUnit.PROP_DESCRIPTION, null)); + assertNull("1.5", unit.getProperty(IInstallableUnit.PROP_PROVIDER, null)); + } +} diff --git a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/repohandling/SiteImportExportTest.java b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/repohandling/SiteImportExportTest.java index 48c8c6c76..1948e5a87 100644 --- a/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/repohandling/SiteImportExportTest.java +++ b/bundles/org.eclipse.equinox.p2.tests.ui/src/org/eclipse/equinox/p2/tests/ui/repohandling/SiteImportExportTest.java @@ -11,8 +11,8 @@ package org.eclipse.equinox.p2.tests.ui.repohandling; import java.io.File; +import org.eclipse.equinox.internal.p2.ui.UpdateManagerCompatibility; import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement; -import org.eclipse.equinox.internal.provisional.p2.ui.UpdateManagerCompatibility; import org.eclipse.equinox.p2.tests.ui.AbstractProvisioningUITest; public class SiteImportExportTest extends AbstractProvisioningUITest { diff --git a/bundles/org.eclipse.equinox.p2.tests.verifier/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.tests.verifier/.settings/org.eclipse.jdt.core.prefs index 5f61adc2c..d282a1283 100644 --- a/bundles/org.eclipse.equinox.p2.tests.verifier/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.tests.verifier/.settings/org.eclipse.jdt.core.prefs @@ -10,7 +10,7 @@ org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate diff --git a/bundles/org.eclipse.equinox.p2.tests.verifier/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.tests.verifier/META-INF/MANIFEST.MF index b2d2d8cf5..9f81de57d 100644 --- a/bundles/org.eclipse.equinox.p2.tests.verifier/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.tests.verifier/META-INF/MANIFEST.MF @@ -7,7 +7,8 @@ Bundle-Activator: org.eclipse.equinox.internal.p2.tests.verifier.Activator Require-Bundle: org.eclipse.core.runtime Bundle-ActivationPolicy: lazy Import-Package: org.eclipse.equinox.internal.p2.core.helpers, - org.eclipse.equinox.internal.provisional.p2.engine, - org.eclipse.equinox.internal.provisional.p2.metadata.query + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.query Bundle-RequiredExecutionEnvironment: J2SE-1.4 Export-Package: org.eclipse.equinox.internal.p2.tests.verifier;x-internal:=true diff --git a/bundles/org.eclipse.equinox.p2.tests.verifier/src/org/eclipse/equinox/internal/p2/tests/verifier/VerifierApplication.java b/bundles/org.eclipse.equinox.p2.tests.verifier/src/org/eclipse/equinox/internal/p2/tests/verifier/VerifierApplication.java index 84108df3d..27e7482d9 100644 --- a/bundles/org.eclipse.equinox.p2.tests.verifier/src/org/eclipse/equinox/internal/p2/tests/verifier/VerifierApplication.java +++ b/bundles/org.eclipse.equinox.p2.tests.verifier/src/org/eclipse/equinox/internal/p2/tests/verifier/VerifierApplication.java @@ -19,10 +19,10 @@ import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.osgi.framework.internal.core.Constants; import org.eclipse.osgi.service.resolver.*; import org.eclipse.osgi.util.NLS; @@ -296,7 +296,7 @@ public class VerifierApplication implements IApplication { IProfile profile = registry.getProfile(IProfileRegistry.SELF); if (profile == null) return createError("SELF profile not available in profile registry."); //$NON-NLS-1$ - Collector results = profile.query(new InstallableUnitQuery(Activator.PLUGIN_ID), new Collector(), null); + IQueryResult results = profile.query(new InstallableUnitQuery(Activator.PLUGIN_ID), null); if (results.isEmpty()) return createError(NLS.bind("IU for {0} not found in SELF profile.", Activator.PLUGIN_ID)); //$NON-NLS-1$ return Status.OK_STATUS; diff --git a/bundles/org.eclipse.equinox.p2.tests/.externalToolBuilders/New_Builder.launch b/bundles/org.eclipse.equinox.p2.tests/.externalToolBuilders/New_Builder.launch new file mode 100644 index 000000000..b4809f0a4 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/.externalToolBuilders/New_Builder.launch @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/bundles/org.eclipse.equinox.p2.tests/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.tests/.settings/org.eclipse.jdt.core.prefs index 5f61adc2c..47ca55680 100644 --- a/bundles/org.eclipse.equinox.p2.tests/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.tests/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Fri Dec 12 15:45:18 EST 2008 +#Mon Dec 28 06:14:12 CET 2009 eclipse.preferences.version=1 instance/org.eclipse.core.net/org.eclipse.core.net.hasMigrated=true org.eclipse.jdt.core.builder.cleanOutputFolder=clean @@ -10,7 +10,7 @@ org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate diff --git a/bundles/org.eclipse.equinox.p2.tests/All p2 Tests.launch b/bundles/org.eclipse.equinox.p2.tests/All p2 Tests.launch index 4d9062037..3cd757414 100644 --- a/bundles/org.eclipse.equinox.p2.tests/All p2 Tests.launch +++ b/bundles/org.eclipse.equinox.p2.tests/All p2 Tests.launch @@ -1,4 +1,4 @@ - + @@ -52,12 +52,12 @@ - + - + - + diff --git a/bundles/org.eclipse.equinox.p2.tests/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.tests/META-INF/MANIFEST.MF index 564a94b70..438d9ea7c 100644 --- a/bundles/org.eclipse.equinox.p2.tests/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.tests/META-INF/MANIFEST.MF @@ -8,20 +8,20 @@ Bundle-Version: 1.2.0.qualifier Import-Package: javax.xml.parsers, org.eclipse.ant.core, org.eclipse.ecf.filetransfer, - org.eclipse.equinox.internal.p2.artifact.mirror, org.eclipse.equinox.internal.p2.artifact.processors.md5, org.eclipse.equinox.internal.p2.artifact.processors.pack200, org.eclipse.equinox.internal.p2.artifact.repository, org.eclipse.equinox.internal.p2.artifact.repository.simple, + org.eclipse.equinox.internal.p2.core, org.eclipse.equinox.internal.p2.core.helpers, org.eclipse.equinox.internal.p2.director, org.eclipse.equinox.internal.p2.director.app, - org.eclipse.equinox.internal.p2.engine, org.eclipse.equinox.internal.p2.extensionlocation, org.eclipse.equinox.internal.p2.jarprocessor, org.eclipse.equinox.internal.p2.jarprocessor.verifier, org.eclipse.equinox.internal.p2.metadata, - org.eclipse.equinox.internal.p2.metadata.mirror, + org.eclipse.equinox.internal.p2.metadata.expression, + org.eclipse.equinox.internal.p2.metadata.query, org.eclipse.equinox.internal.p2.metadata.repository, org.eclipse.equinox.internal.p2.metadata.repository.io, org.eclipse.equinox.internal.p2.persistence, @@ -31,26 +31,24 @@ Import-Package: javax.xml.parsers, org.eclipse.equinox.internal.p2.touchpoint.natives, org.eclipse.equinox.internal.p2.touchpoint.natives.actions, org.eclipse.equinox.internal.p2.update, - org.eclipse.equinox.internal.p2.updatesite, - org.eclipse.equinox.internal.p2.updatesite.artifact, - org.eclipse.equinox.internal.p2.updatesite.metadata, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing, org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.core.eventbus, - org.eclipse.equinox.internal.provisional.p2.core.location, org.eclipse.equinox.internal.provisional.p2.director, org.eclipse.equinox.internal.provisional.p2.directorywatcher, - org.eclipse.equinox.internal.provisional.p2.engine, - org.eclipse.equinox.internal.provisional.p2.engine.phases, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, org.eclipse.equinox.internal.provisional.p2.repository, - org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository, - org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.spi.p2.repository, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.internal.repository.comparator, org.eclipse.equinox.p2.internal.repository.tools, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.expression, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.ql, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository.artifact.spi, + org.eclipse.equinox.p2.repository.metadata.spi, + org.eclipse.equinox.p2.repository.spi, org.eclipse.equinox.spi.p2.publisher, org.eclipse.internal.provisional.equinox.p2.jarprocessor, org.eclipse.osgi.service.datalocation, @@ -80,10 +78,15 @@ Require-Bundle: org.eclipse.equinox.p2.metadata.generator, org.eclipse.equinox.p2.updatechecker;bundle-version="1.0.0", org.eclipse.equinox.simpleconfigurator.manipulator;bundle-version="1.0.100", org.eclipse.equinox.p2.repository;bundle-version="1.0.0", - org.eclipse.equinox.p2.tests.verifier;bundle-version="1.0.0" + org.eclipse.equinox.p2.tests.verifier;bundle-version="1.0.0", + org.eclipse.equinox.security;bundle-version="1.0.0", + org.eclipse.equinox.p2.engine;bundle-version="2.0.0", + org.eclipse.equinox.p2.ql, + org.eclipse.equinox.p2.updatesite;bundle-version="1.0.200" Bundle-ActivationPolicy: lazy Eclipse-RegisterBuddy: org.eclipse.equinox.p2.artifact.repository -Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4 Export-Package: org.eclipse.equinox.p2.tests, org.eclipse.equinox.p2.tests.artifact.repository, org.eclipse.equinox.p2.tests.artifact.repository.processing, diff --git a/bundles/org.eclipse.equinox.p2.tests/build.properties b/bundles/org.eclipse.equinox.p2.tests/build.properties index 1518f3c93..63bbf4dba 100644 --- a/bundles/org.eclipse.equinox.p2.tests/build.properties +++ b/bundles/org.eclipse.equinox.p2.tests/build.properties @@ -18,5 +18,7 @@ bin.includes = META-INF/,\ plugin.properties,\ test.xml customCallBack=foo.xml -javacWarnings..=-raw,-unchecked,-varargsCast src.includes = about.html +javacWarnings..=-raw,-unchecked,-varargsCast +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.tests/rawData/Test Data Generator.launch b/bundles/org.eclipse.equinox.p2.tests/rawData/Test Data Generator.launch index ad9a6a439..8db6aec9a 100644 --- a/bundles/org.eclipse.equinox.p2.tests/rawData/Test Data Generator.launch +++ b/bundles/org.eclipse.equinox.p2.tests/rawData/Test Data Generator.launch @@ -16,10 +16,9 @@ - + - - + diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractAntProvisioningTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractAntProvisioningTest.java index e72c223e8..0a82e05d9 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractAntProvisioningTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractAntProvisioningTest.java @@ -17,12 +17,14 @@ import java.util.*; import org.eclipse.ant.core.AntRunner; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.p2.metadata.InstallableUnit; import org.eclipse.equinox.internal.p2.persistence.XMLWriter; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.repository.artifact.ArtifactKeyQuery; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; public class AbstractAntProvisioningTest extends AbstractProvisioningTest { protected static final String TYPE_ARTIFACT = "A"; @@ -246,11 +248,11 @@ public class AbstractAntProvisioningTest extends AbstractProvisioningTest { assertContains(message, destination, source); } - protected static void assertArtifactKeyContentEquals(String message, Collector ius, URI artifactRepositoryLocation) { + protected void assertArtifactKeyContentEquals(String message, IQueryResult ius, URI artifactRepositoryLocation) { try { IArtifactRepository repo = getArtifactRepositoryManager().loadRepository(artifactRepositoryLocation, null); List fromIUs = getArtifactKeys(ius); - List fromRepo = Arrays.asList(repo.getArtifactKeys()); + Iterator fromRepo = repo.query(ArtifactKeyQuery.ALL_KEYS, null).iterator(); assertContains(message, fromIUs, fromRepo); assertContains(message, fromRepo, fromIUs); } catch (ProvisionException e) { @@ -259,28 +261,11 @@ public class AbstractAntProvisioningTest extends AbstractProvisioningTest { } - protected static void assertContains(String message, IQueryable source, IQueryable destination) { - Collector sourceCollector = source.query(InstallableUnitQuery.ANY, new Collector(), null); - Iterator it = sourceCollector.iterator(); + protected static List getArtifactKeys(IQueryResult ius) { + List keys = new ArrayList(); - while (it.hasNext()) { - IInstallableUnit sourceIU = (IInstallableUnit) it.next(); - Collector destinationCollector = destination.query(new InstallableUnitQuery(sourceIU), new Collector(), null); - assertEquals(message, 1, destinationCollector.size()); - assertTrue(message, sourceIU.equals(destinationCollector.iterator().next())); - } - } - - protected static void assertContains(String message, List fromIUs, List fromRepo) { - for (Iterator iter = fromIUs.iterator(); iter.hasNext();) - assertTrue(message, fromRepo.contains(iter.next())); - } - - protected static List getArtifactKeys(Collector ius) { - List keys = new ArrayList(ius.size()); - - for (Iterator iter = ius.iterator(); iter.hasNext();) - keys.addAll(Arrays.asList(((InstallableUnit) iter.next()).getArtifacts())); + for (Iterator iter = ius.iterator(); iter.hasNext();) + keys.addAll(iter.next().getArtifacts()); return keys; } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractProvisioningTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractProvisioningTest.java index 76f090a7d..1b6ef6158 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractProvisioningTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractProvisioningTest.java @@ -19,23 +19,29 @@ import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.core.helpers.URLUtil; import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.core.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil; +import org.eclipse.equinox.p2.metadata.query.FragmentQuery; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.publisher.PublisherInfo; import org.eclipse.equinox.p2.publisher.eclipse.*; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.service.datalocation.Location; import org.eclipse.osgi.service.resolver.BundleDescription; +import org.osgi.framework.*; /** * Base class for provisioning tests with convenience methods used by multiple tests. @@ -71,6 +77,7 @@ public abstract class AbstractProvisioningTest extends TestCase { protected List profilesToRemove = new ArrayList(); private File testFolder = null; + protected Object previousSelfValue = null; public static void assertEmptyProfile(IProfile profile) { assertNotNull("The profile should not be null", profile); @@ -199,7 +206,7 @@ public abstract class AbstractProvisioningTest extends TestCase { InstallableUnitFragmentDescription fragment = new InstallableUnitFragmentDescription(); fragment.setId(name); fragment.setVersion(DEFAULT_VERSION); - fragment.setProperty(IInstallableUnit.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); + fragment.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); fragment.setTouchpointType(TOUCHPOINT_OSGI); fragment.addTouchpointData(NO_TP_DATA); fragment.setHost(BUNDLE_REQUIREMENT); @@ -225,7 +232,7 @@ public abstract class AbstractProvisioningTest extends TestCase { } public static IDirector createDirector() { - return (IDirector) ServiceHelper.getService(TestActivator.getContext(), IDirector.class.getName()); + return (IDirector) ServiceHelper.getService(TestActivator.getContext(), IDirector.SERVICE_NAME); } /** @@ -263,8 +270,8 @@ public abstract class AbstractProvisioningTest extends TestCase { /** * Creates and returns a correctly formatted LDAP filter with the given key and value. */ - protected static String createFilter(String filterKey, String filterValue) { - return "(" + filterKey + '=' + filterValue + ')'; + protected static Filter createFilter(String filterKey, String filterValue) { + return ExpressionUtil.parseLDAP("(" + filterKey + '=' + filterValue + ')'); } /** @@ -304,6 +311,10 @@ public abstract class AbstractProvisioningTest extends TestCase { * assume default values, and the default self capability is also added to the IU. */ public static IInstallableUnit createIU(String name, String filter, IProvidedCapability[] additionalProvides) { + return createIU(name, ExpressionUtil.parseLDAP(filter), additionalProvides); + } + + public static IInstallableUnit createIU(String name, Filter filter, IProvidedCapability[] additionalProvides) { return createIU(name, DEFAULT_VERSION, filter, NO_REQUIRES, additionalProvides, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false); } @@ -356,6 +367,10 @@ public abstract class AbstractProvisioningTest extends TestCase { * assume default values, and the default self capability is also added to the IU. */ public static IInstallableUnit createIU(String name, Version version, String filter, IProvidedCapability[] additionalProvides) { + return createIU(name, version, ExpressionUtil.parseLDAP(filter), additionalProvides); + } + + public static IInstallableUnit createIU(String name, Version version, Filter filter, IProvidedCapability[] additionalProvides) { return createIU(name, version, filter, NO_REQUIRES, additionalProvides, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false); } @@ -363,7 +378,7 @@ public abstract class AbstractProvisioningTest extends TestCase { * Create a basic InstallableUnit with the given attributes. All other attributes * assume default values, and the default self capability is also added to the IU. */ - public static IInstallableUnit createIU(String name, Version version, String filter, IRequiredCapability[] required, IProvidedCapability[] additionalProvides, Map properties, ITouchpointType tpType, ITouchpointData tpData, boolean singleton) { + public static IInstallableUnit createIU(String name, Version version, Filter filter, IRequiredCapability[] required, IProvidedCapability[] additionalProvides, Map properties, ITouchpointType tpType, ITouchpointData tpData, boolean singleton) { return createIU(name, version, filter, required, additionalProvides, properties, tpType, tpData, singleton, null, null); } @@ -371,7 +386,7 @@ public abstract class AbstractProvisioningTest extends TestCase { return createIUPatch(name, version, null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, singleton, null, changes, scope, lifeCycle, NO_REQUIRES); } - public static IInstallableUnitPatch createIUPatch(String name, Version version, String filter, IRequiredCapability[] required, IProvidedCapability[] additionalProvides, Map properties, ITouchpointType tpType, ITouchpointData tpData, boolean singleton, IUpdateDescriptor update, IRequirementChange[] reqChanges, IRequiredCapability[][] scope, IRequiredCapability lifeCycle, IRequiredCapability[] metaRequirements) { + public static IInstallableUnitPatch createIUPatch(String name, Version version, Filter filter, IRequiredCapability[] required, IProvidedCapability[] additionalProvides, Map properties, ITouchpointType tpType, ITouchpointData tpData, boolean singleton, IUpdateDescriptor update, IRequirementChange[] reqChanges, IRequiredCapability[][] scope, IRequiredCapability lifeCycle, IRequiredCapability[] metaRequirements) { InstallableUnitPatchDescription iu = new MetadataFactory.InstallableUnitPatchDescription(); iu.setId(name); iu.setVersion(version); @@ -400,7 +415,7 @@ public abstract class AbstractProvisioningTest extends TestCase { return MetadataFactory.createInstallableUnitPatch(iu); } - public static IInstallableUnit createIU(String name, Version version, String filter, IRequiredCapability[] required, IProvidedCapability[] additionalProvides, Map properties, ITouchpointType tpType, ITouchpointData tpData, boolean singleton, IUpdateDescriptor update, IRequiredCapability[] metaRequirements) { + public static IInstallableUnit createIU(String name, Version version, Filter filter, IRequiredCapability[] required, IProvidedCapability[] additionalProvides, Map properties, ITouchpointType tpType, ITouchpointData tpData, boolean singleton, IUpdateDescriptor update, IRequiredCapability[] metaRequirements) { InstallableUnitDescription iu = new MetadataFactory.InstallableUnitDescription(); iu.setId(name); iu.setVersion(version); @@ -444,47 +459,45 @@ public abstract class AbstractProvisioningTest extends TestCase { InstallableUnitFragmentDescription fragment = new InstallableUnitFragmentDescription(); fragment.setId(name); fragment.setVersion(version); - fragment.setProperty(IInstallableUnit.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); + fragment.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); fragment.setRequiredCapabilities(required); fragment.setTouchpointType(tpType); if (tpData != null) fragment.addTouchpointData(tpData); if (host != null) { VersionRange hostRange = new VersionRange(host.getVersion(), true, host.getVersion(), true); - fragment.setHost(new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, host.getId(), hostRange, null, false, false)}); + fragment.setHost(new IRequirement[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, host.getId(), hostRange, null, false, false)}); } fragment.setCapabilities(new IProvidedCapability[] {getSelfCapability(name, version)}); return MetadataFactory.createInstallableUnitFragment(fragment); } public static void changeVersion(InstallableUnitDescription desc, Version newVersion) { - IProvidedCapability[] capabilities = desc.getProvidedCapabilities(); - for (int i = 0; i < capabilities.length; i++) { - if (desc.getVersion().equals(capabilities[i].getVersion())) - capabilities[i] = MetadataFactory.createProvidedCapability(capabilities[i].getNamespace(), capabilities[i].getName(), newVersion); + List capabilities = new ArrayList(desc.getProvidedCapabilities()); + for (int i = 0; i < capabilities.size(); i++) { + IProvidedCapability pc = capabilities.get(i); + if (desc.getVersion().equals(pc.getVersion())) + capabilities.set(i, MetadataFactory.createProvidedCapability(pc.getNamespace(), pc.getName(), newVersion)); } desc.setVersion(newVersion); + desc.setCapabilities(capabilities.toArray(new IProvidedCapability[capabilities.size()])); } public static MetadataFactory.InstallableUnitDescription createIUDescriptor(IInstallableUnit prototype) { InstallableUnitDescription desc = new MetadataFactory.InstallableUnitDescription(); - desc.setArtifacts(prototype.getArtifacts()); - IProvidedCapability originalCapabilities[] = prototype.getProvidedCapabilities(); - IProvidedCapability newCapabilities[] = new IProvidedCapability[originalCapabilities.length]; - for (int i = 0; i < originalCapabilities.length; i++) { - newCapabilities[i] = MetadataFactory.createProvidedCapability(originalCapabilities[i].getNamespace(), originalCapabilities[i].getName(), originalCapabilities[i].getVersion()); - } - desc.setCapabilities(newCapabilities); + Collection originalArtifacts = prototype.getArtifacts(); + desc.setArtifacts(originalArtifacts.toArray(new IArtifactKey[originalArtifacts.size()])); + Collection originalCapabilities = prototype.getProvidedCapabilities(); + desc.setCapabilities(originalCapabilities.toArray(new IProvidedCapability[originalCapabilities.size()])); desc.setCopyright(prototype.getCopyright()); desc.setFilter(prototype.getFilter()); desc.setId(prototype.getId()); - desc.setLicense(prototype.getLicense()); - IRequiredCapability[] originalRequirements = prototype.getRequiredCapabilities(); - IRequiredCapability[] newRequirements = new IRequiredCapability[originalRequirements.length]; - for (int i = 0; i < newRequirements.length; i++) { - newRequirements[i] = MetadataFactory.createRequiredCapability(originalRequirements[i].getNamespace(), originalRequirements[i].getName(), originalRequirements[i].getRange(), originalRequirements[i].getFilter(), originalRequirements[i].isOptional(), originalRequirements[i].isMultiple(), originalRequirements[i].isGreedy()); - } - desc.setRequiredCapabilities(prototype.getRequiredCapabilities()); + Collection originalLicenses = prototype.getLicenses(); + desc.setLicenses(originalLicenses.toArray(new ILicense[originalLicenses.size()])); + Collection originalRequirements = prototype.getRequiredCapabilities(); + desc.setRequiredCapabilities(originalRequirements.toArray(new IRequirement[originalRequirements.size()])); + originalRequirements = prototype.getMetaRequiredCapabilities(); + desc.setMetaRequiredCapabilities(originalRequirements.toArray(new IRequirement[originalRequirements.size()])); desc.setSingleton(prototype.isSingleton()); desc.setTouchpointType(MetadataFactory.createTouchpointType(prototype.getTouchpointType().getId(), prototype.getTouchpointType().getVersion())); desc.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor(prototype.getUpdateDescriptor().getId(), prototype.getUpdateDescriptor().getRange(), prototype.getUpdateDescriptor().getSeverity(), prototype.getUpdateDescriptor().getDescription())); @@ -499,20 +512,29 @@ public abstract class AbstractProvisioningTest extends TestCase { } public static IPlanner createPlanner() { - return (IPlanner) ServiceHelper.getService(TestActivator.getContext(), IPlanner.class.getName()); + return (IPlanner) ServiceHelper.getService(TestActivator.getContext(), IPlanner.SERVICE_NAME); } /** * Creates and returns a required capability with the provided attributes. */ + protected static IRequiredCapability[] createRequiredCapabilities(String namespace, String name) { + return createRequiredCapabilities(namespace, name, ANY_VERSION, (Filter) null); + } + protected static IRequiredCapability[] createRequiredCapabilities(String namespace, String name, String filter) { return createRequiredCapabilities(namespace, name, ANY_VERSION, filter); } - /** - * Creates and returns a required capability with the provided attributes. - */ + protected static IRequiredCapability[] createRequiredCapabilities(String namespace, String name, VersionRange range) { + return createRequiredCapabilities(namespace, name, range, (Filter) null); + } + protected static IRequiredCapability[] createRequiredCapabilities(String namespace, String name, VersionRange range, String filter) { + return createRequiredCapabilities(namespace, name, range, ExpressionUtil.parseLDAP(filter)); + } + + protected static IRequiredCapability[] createRequiredCapabilities(String namespace, String name, VersionRange range, Filter filter) { return new IRequiredCapability[] {MetadataFactory.createRequiredCapability(namespace, name, range, filter, false, false)}; } @@ -568,7 +590,7 @@ public abstract class AbstractProvisioningTest extends TestCase { } public static Iterator getInstallableUnits(IProfile profile2) { - return profile2.query(InstallableUnitQuery.ANY, new Collector(), null).iterator(); + return profile2.query(InstallableUnitQuery.ANY, null).iterator(); } /** @@ -581,7 +603,7 @@ public abstract class AbstractProvisioningTest extends TestCase { /** * Get the 'self' capability for an installable unit with the give id and version. */ - private static IProvidedCapability getSelfCapability(String installableUnitId, Version installableUnitVersion) { + protected static IProvidedCapability getSelfCapability(String installableUnitId, Version installableUnitVersion) { return MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, installableUnitId, installableUnitVersion); } @@ -618,6 +640,41 @@ public abstract class AbstractProvisioningTest extends TestCase { } } + public static int queryResultSize(IQueryResult queryResult) { + if (queryResult instanceof Collector) + return ((Collector) queryResult).size(); + + int cnt = 0; + Iterator itor = queryResult.iterator(); + while (itor.hasNext()) { + itor.next(); + ++cnt; + } + return cnt; + } + + public static int queryResultUniqueSize(IQueryResult queryResult) { + int cnt = 0; + Iterator itor = queryResult.iterator(); + HashSet uniqueTracker = new HashSet(); + while (itor.hasNext()) { + if (uniqueTracker.add(itor.next())) + ++cnt; + } + return cnt; + } + + public static void restartBundle(final Bundle bundle) throws BundleException { + bundle.stop(Bundle.STOP_TRANSIENT); + startBundle(bundle); + } + + public static void startBundle(final Bundle bundle) throws BundleException { + //see http://dev.eclipse.org/mhonarc/lists/equinox-dev/msg05917.html + bundle.start(Bundle.START_ACTIVATION_POLICY); + bundle.start(Bundle.START_TRANSIENT); + } + private static void write(IStatus status, int indent, PrintStream output) { indent(output, indent); output.println("Severity: " + status.getSeverity()); @@ -684,7 +741,7 @@ public abstract class AbstractProvisioningTest extends TestCase { * in the tearDown method. */ protected IProfile createProfile(String name) { - return createProfile(name, null, null); + return createProfile(name, null); } /** @@ -692,18 +749,14 @@ public abstract class AbstractProvisioningTest extends TestCase { * already exists. The returned profile will be removed automatically * in the tearDown method. */ - protected IProfile createProfile(String name, String parentId) { - return createProfile(name, parentId, null); - } - - protected IProfile createProfile(String name, String parentId, Map properties) { + protected IProfile createProfile(String name, Map properties) { //remove any existing profile with the same name - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = getProfileRegistry(); profileRegistry.removeProfile(name); profilesToRemove.add(name); //create and return a new profile try { - return profileRegistry.addProfile(name, properties, parentId); + return profileRegistry.addProfile(name, properties); } catch (ProvisionException e) { throw new IllegalArgumentException(e.getMessage()); } @@ -714,9 +767,7 @@ public abstract class AbstractProvisioningTest extends TestCase { } protected IProfile getProfile(String profileId) { - //remove any existing profile with the same name - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); - return profileRegistry.getProfile(profileId); + return getProfileRegistry().getProfile(profileId); } /** @@ -732,7 +783,7 @@ public abstract class AbstractProvisioningTest extends TestCase { */ protected IMetadataRepository createTestMetdataRepository(IInstallableUnit[] units) { IMetadataRepository repo = new TestMetadataRepository(units); - MetadataRepositoryManager repoMan = (MetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.class.getName()); + MetadataRepositoryManager repoMan = (MetadataRepositoryManager) getMetadataRepositoryManager(); assertNotNull(repoMan); repoMan.addRepository(repo); metadataRepos.add(repo); @@ -746,8 +797,22 @@ public abstract class AbstractProvisioningTest extends TestCase { return repo; } + protected static IProvisioningAgent getAgent() { + //get the global agent for the currently running system + return (IProvisioningAgent) ServiceHelper.getService(TestActivator.getContext(), IProvisioningAgent.SERVICE_NAME); + } + + protected static IAgentLocation getAgentLocation() { + //get the location of the currently running system + return (IAgentLocation) getAgent().getService(IAgentLocation.SERVICE_NAME); + } + protected static IArtifactRepositoryManager getArtifactRepositoryManager() { - return (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IArtifactRepositoryManager.class.getName()); + return (IArtifactRepositoryManager) getAgent().getService(IArtifactRepositoryManager.SERVICE_NAME); + } + + protected IProfileRegistry getProfileRegistry() { + return (IProfileRegistry) getAgent().getService(IProfileRegistry.SERVICE_NAME); } protected IMetadataRepository createMetadataRepository(URI location, Map properties) throws ProvisionException { @@ -765,17 +830,17 @@ public abstract class AbstractProvisioningTest extends TestCase { } protected IInstallableUnit getIU(IMetadataRepository repository, String name) { - Collector collector = repository.query(new InstallableUnitQuery(name), new Collector(), null); + IQueryResult queryResult = repository.query(new InstallableUnitQuery(name), null); IInstallableUnit unit = null; - if (collector.size() > 0) - unit = (IInstallableUnit) collector.iterator().next(); + if (!queryResult.isEmpty()) + unit = (IInstallableUnit) queryResult.iterator().next(); return unit; } protected static IMetadataRepositoryManager getMetadataRepositoryManager() { - return (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.class.getName()); + return (IMetadataRepositoryManager) getAgent().getService(IMetadataRepositoryManager.SERVICE_NAME); } public static String getUniqueString() { @@ -819,7 +884,7 @@ public abstract class AbstractProvisioningTest extends TestCase { protected void tearDown() throws Exception { super.tearDown(); //remove all metadata repositories created by this test - IMetadataRepositoryManager repoMan = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager repoMan = getMetadataRepositoryManager(); if (!metadataRepos.isEmpty()) { for (Iterator it = metadataRepos.iterator(); it.hasNext();) { IMetadataRepository repo = (IMetadataRepository) it.next(); @@ -837,7 +902,7 @@ public abstract class AbstractProvisioningTest extends TestCase { } } //remove all profiles created by this test - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = getProfileRegistry(); for (Iterator it = profilesToRemove.iterator(); it.hasNext();) { String toRemove = (String) it.next(); profileRegistry.removeProfile(toRemove); @@ -867,46 +932,24 @@ public abstract class AbstractProvisioningTest extends TestCase { return null; } - protected static void assertInstallOperand(ProvisioningPlan plan, IInstallableUnit iu) { - Operand[] ops = plan.getOperands(); - for (int i = 0; i < ops.length; i++) { - if (ops[i] instanceof InstallableUnitOperand) { - InstallableUnitOperand iuOp = (InstallableUnitOperand) ops[i]; - if (iu.equals(iuOp.second())) - return; - } - } - fail("Can't find " + iu + " in the plan"); + protected static void assertInstallOperand(IProvisioningPlan plan, IInstallableUnit iu) { + if (plan.getAdditions().query(new InstallableUnitQuery(iu), null).isEmpty()) + fail("Can't find " + iu + " in the plan"); } - protected static void assertUninstallOperand(ProvisioningPlan plan, IInstallableUnit iu) { - Operand[] ops = plan.getOperands(); - for (int i = 0; i < ops.length; i++) { - if (ops[i] instanceof InstallableUnitOperand) { - InstallableUnitOperand iuOp = (InstallableUnitOperand) ops[i]; - if (iu.equals(iuOp.first())) - return; - } - } - fail("Can't find " + iu + " in the plan"); - } - - protected static void assertNoOperand(ProvisioningPlan plan, IInstallableUnit iu) { - Operand[] ops = plan.getOperands(); - for (int i = 0; i < ops.length; i++) { - if (ops[i] instanceof InstallableUnitOperand) { - InstallableUnitOperand iuOp = (InstallableUnitOperand) ops[i]; - if (iuOp.second() != null && iuOp.second().equals(iu)) - fail(iu + " should not be present in this plan."); - if (iuOp.first() != null && iuOp.first().equals(iu)) - fail(iu + " should not be present in this plan."); - } - } + protected static void assertUninstallOperand(IProvisioningPlan plan, IInstallableUnit iu) { + if (plan.getRemovals().query(new InstallableUnitQuery(iu), null).isEmpty()) + fail("Can't find " + iu + " in the plan"); + } + + protected static void assertNoOperand(IProvisioningPlan plan, IInstallableUnit iu) { + if (!(plan.getRemovals().query(new InstallableUnitQuery(iu), null).isEmpty() && plan.getAdditions().query(new InstallableUnitQuery(iu), null).isEmpty())) + fail(iu + " should not be present in this plan."); } protected void setUp() throws Exception { super.setUp(); - MetadataRepositoryManager repoMan = (MetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager repoMan = getMetadataRepositoryManager(); URI[] repos = repoMan.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); for (int i = 0; i < repos.length; i++) { repoMan.removeRepository(repos[i]); @@ -920,18 +963,18 @@ public abstract class AbstractProvisioningTest extends TestCase { req.setInstallableUnitInclusionRules(ius[i], strict ? PlannerHelper.createStrictInclusionRule(ius[i]) : PlannerHelper.createOptionalInclusionRule(ius[i])); } - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); if (plan.getStatus().getSeverity() == IStatus.ERROR || plan.getStatus().getSeverity() == IStatus.CANCEL) return plan.getStatus(); - return engine.perform(profile, new DefaultPhaseSet(), plan.getOperands(), null, null); + return engine.perform(plan, null); } protected IStatus uninstall(IProfile profile, IInstallableUnit[] ius, IPlanner planner, IEngine engine) { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.removeInstallableUnits(ius); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); - return engine.perform(profile, new DefaultPhaseSet(), plan.getOperands(), null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + return engine.perform(plan, null); } protected static void assertEquals(String message, Object[] expected, Object[] actual, boolean orderImportant) { @@ -1002,15 +1045,15 @@ public abstract class AbstractProvisioningTest extends TestCase { if (!iu1.equals(iu2)) fail(message + " " + iu1 + " is not equal to " + iu2); - if (iu1.isFragment()) { - if (!iu2.isFragment()) + if (FragmentQuery.isFragment(iu1)) { + if (!FragmentQuery.isFragment(iu2)) fail(message + " " + iu1 + " is not a fragment."); try { assertEquals(message, ((IInstallableUnitFragment) iu1).getHost(), ((IInstallableUnitFragment) iu2).getHost()); } catch (AssertionFailedError failure) { fail(message + " Unequal hosts: " + failure.getMessage()); } - } else if (iu2.isFragment()) { + } else if (FragmentQuery.isFragment(iu2)) { fail(message + " " + iu2 + " is a fragment."); } @@ -1027,7 +1070,7 @@ public abstract class AbstractProvisioningTest extends TestCase { assertEquals(message, iu1.getTouchpointType(), iu2.getTouchpointType()); assertEquals(message, iu1.getTouchpointData(), iu2.getTouchpointData()); assertEquals(message, iu1.getProperties(), iu2.getProperties()); - assertEquals(message, iu1.getLicense(), iu2.getLicense()); + assertEquals(message, iu1.getLicenses(), iu2.getLicenses()); assertEquals(message, iu1.getCopyright(), iu2.getCopyright()); assertEquals(message, iu1.getUpdateDescriptor(), iu2.getUpdateDescriptor()); assertEquals(message, iu1.getFilter(), iu2.getFilter()); @@ -1136,15 +1179,15 @@ public abstract class AbstractProvisioningTest extends TestCase { * Note: NOT BICONDITIONAL! assertContains(A, B) is NOT the same as assertContains(B, A) */ protected static void assertContains(String message, IArtifactRepository sourceRepo, IArtifactRepository destinationRepo) { - IArtifactKey[] sourceKeys = sourceRepo.getArtifactKeys(); - - for (int i = 0; i < sourceKeys.length; i++) { - IArtifactDescriptor[] destinationDescriptors = destinationRepo.getArtifactDescriptors(sourceKeys[i]); + IQueryResult sourceKeys = sourceRepo.query(ArtifactKeyQuery.ALL_KEYS, null); + for (Iterator iterator = sourceKeys.iterator(); iterator.hasNext();) { + IArtifactKey key = (IArtifactKey) iterator.next(); + IArtifactDescriptor[] destinationDescriptors = destinationRepo.getArtifactDescriptors(key); if (destinationDescriptors == null || destinationDescriptors.length == 0) - fail(message + ": unmatched key: " + sourceKeys[i].toString()); + fail(message + ": unmatched key: " + key.toString()); //this implicitly verifies the keys are present - IArtifactDescriptor[] sourceDescriptors = sourceRepo.getArtifactDescriptors(sourceKeys[i]); + IArtifactDescriptor[] sourceDescriptors = sourceRepo.getArtifactDescriptors(key); assertEquals(message, sourceDescriptors, destinationDescriptors, false); //order doesn't matter } @@ -1164,13 +1207,13 @@ public abstract class AbstractProvisioningTest extends TestCase { * Note: NOT BICONDITIONAL! assertContains(A, B) is NOT the same as assertContains(B, A) */ protected static void assertContains(String message, IMetadataRepository sourceRepo, IMetadataRepository destinationRepo) { - Collector sourceCollector = sourceRepo.query(InstallableUnitQuery.ANY, new Collector(), null); + IQueryResult sourceCollector = sourceRepo.query(InstallableUnitQuery.ANY, null); Iterator it = sourceCollector.iterator(); while (it.hasNext()) { IInstallableUnit sourceIU = (IInstallableUnit) it.next(); - Collector destinationCollector = destinationRepo.query(new InstallableUnitQuery(sourceIU), new Collector(), null); - assertEquals(message, 1, destinationCollector.size()); + IQueryResult destinationCollector = destinationRepo.query(new InstallableUnitQuery(sourceIU), null); + assertEquals(message, 1, queryResultSize(destinationCollector)); assertEquals(message, sourceIU, (IInstallableUnit) destinationCollector.iterator().next()); } } @@ -1184,6 +1227,61 @@ public abstract class AbstractProvisioningTest extends TestCase { assertContains(message, repo2, repo1); } + public static void assertContains(String message, IQueryable source, IQueryable destination) { + IQueryResult sourceCollector = source.query(InstallableUnitQuery.ANY, null); + Iterator it = sourceCollector.iterator(); + + while (it.hasNext()) { + IInstallableUnit sourceIU = (IInstallableUnit) it.next(); + IQueryResult destinationCollector = destination.query(new InstallableUnitQuery(sourceIU), null); + assertEquals(message, 1, queryResultSize(destinationCollector)); + assertTrue(message, sourceIU.equals(destinationCollector.iterator().next())); + } + } + + public static void assertContains(String message, IQueryResult result, IQueryResult mustHave) { + assertContains(message, result.iterator(), mustHave.iterator()); + } + + public static void assertContains(String message, Iterator result, Iterator mustHave) { + HashSet repoSet = new HashSet(); + while (mustHave.hasNext()) + repoSet.add(mustHave.next()); + assertContains(message, result, repoSet); + } + + public static void assertContains(String message, Iterator result, Collection mustHave) { + while (result.hasNext()) + assertTrue(message, mustHave.contains(result.next())); + } + + public static void assertContains(IQueryResult result, Object value) { + assertContains(null, result, value); + } + + public static void assertNotContains(IQueryResult result, Object value) { + assertNotContains(null, result, value); + } + + public static void assertContains(String message, IQueryResult result, Object value) { + Iterator itor = result.iterator(); + while (itor.hasNext()) + if (itor.next().equals(value)) + return; + fail(message); + } + + public static void assertNotContains(String message, IQueryResult result, Object value) { + Iterator itor = result.iterator(); + while (itor.hasNext()) + if (itor.next().equals(value)) + fail(message); + } + + public static void assertContains(String message, Collection fromIUs, Iterator fromRepo) { + assertContains(message, fromIUs.iterator(), fromRepo); + } + /* * Return a boolean value indicating whether or not the given installable units * are considered to be equal. @@ -1327,4 +1425,76 @@ public abstract class AbstractProvisioningTest extends TestCase { fail(); } } + + protected int getArtifactKeyCount(URI location) { + try { + return getArtifactKeyCount(getArtifactRepositoryManager().loadRepository(location, null)); + } catch (ProvisionException e) { + fail("Failed to load repository " + URIUtil.toUnencodedString(location) + " for ArtifactDescriptor count"); + return -1; + } + } + + protected int getArtifactKeyCount(IArtifactRepository repo) { + return queryResultSize(repo.query(ArtifactKeyQuery.ALL_KEYS, null)); + } + + protected int getArtifactDescriptorCount(URI location) { + int count = 0; + try { + IArtifactRepository repo = getArtifactRepositoryManager().loadRepository(location, null); + IQueryResult descriptors = repo.descriptorQueryable().query(ArtifactDescriptorQuery.ALL_DESCRIPTORS, null); + return queryResultSize(descriptors); + } catch (ProvisionException e) { + fail("Failed to load repository " + URIUtil.toUnencodedString(location) + " for ArtifactDescriptor count"); + } + return count; + } + + public int countPlanElements(IProvisioningPlan plan) { + return queryResultSize(new CompoundQueryable(plan.getAdditions(), plan.getRemovals()).query(InstallableUnitQuery.ANY, null)); + } + + /** + * This method is used by tests that require access to the "self" profile. It spoofs + * up a fake self profile is none is already available. Tests should invoke this method + * from their {@link #setUp()} method, and invoke {@link #tearDownSelfProfile()} + * from their {@link #tearDown()} method. + */ + protected void setUpSelfProfile() { + if (System.getProperty("eclipse.p2.profile") == null) { + SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) getProfileRegistry(); + try { + Field selfField = SimpleProfileRegistry.class.getDeclaredField("self"); //$NON-NLS-1$ + selfField.setAccessible(true); + previousSelfValue = selfField.get(profileRegistry); + if (previousSelfValue == null) + selfField.set(profileRegistry, "agent"); + } catch (Throwable t) { + fail(); + } + } + createProfile("agent"); + } + + /** + * This method is used by tests that require access to the "self" profile. It cleans up + * a fake self profile is none is already available. Tests should invoke this method + * from their {@link #tearDown()} method, and invoke {@link #setUpSelfProfile()} + * from their {@link #setUp()} method. + */ + protected void tearDownSelfProfile() { + if (System.getProperty("eclipse.p2.profile") == null) { + SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) getProfileRegistry(); + try { + Field selfField = SimpleProfileRegistry.class.getDeclaredField("self"); //$NON-NLS-1$ + selfField.setAccessible(true); + Object self = selfField.get(profileRegistry); + if (self.equals("agent")) + selfField.set(profileRegistry, previousSelfValue); + } catch (Throwable t) { + // ignore as we still want to continue tidying up + } + } + } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractWrappedArtifactRepository.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractWrappedArtifactRepository.java index 81beb03d8..0343fb74b 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractWrappedArtifactRepository.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AbstractWrappedArtifactRepository.java @@ -15,9 +15,10 @@ import java.net.URI; import java.util.Map; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.artifact.*; public class AbstractWrappedArtifactRepository implements IArtifactRepository { @@ -51,10 +52,6 @@ public class AbstractWrappedArtifactRepository implements IArtifactRepository { return delegate.getArtifactDescriptors(key); } - public IArtifactKey[] getArtifactKeys() { - return delegate.getArtifactKeys(); - } - public IStatus getArtifacts(IArtifactRequest[] requests, IProgressMonitor monitor) { return delegate.getArtifacts(requests, monitor); } @@ -130,4 +127,16 @@ public class AbstractWrappedArtifactRepository implements IArtifactRepository { public Object getAdapter(Class adapter) { return delegate.getAdapter(adapter); } + + public IArtifactDescriptor createArtifactDescriptor(IArtifactKey key) { + return delegate.createArtifactDescriptor(key); + } + + public IQueryable descriptorQueryable() { + return delegate.descriptorQueryable(); + } + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return delegate.query(query, monitor); + } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AutomatedTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AutomatedTests.java index 513bbeaa1..da38e98f9 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AutomatedTests.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/AutomatedTests.java @@ -35,11 +35,13 @@ public class AutomatedTests extends TestCase { suite.addTest(org.eclipse.equinox.p2.tests.installer.AllTests.suite()); suite.addTest(org.eclipse.equinox.p2.tests.jarprocessor.AllTests.suite()); suite.addTest(org.eclipse.equinox.p2.tests.metadata.AllTests.suite()); + suite.addTest(org.eclipse.equinox.p2.tests.metadata.expression.AllTests.suite()); suite.addTest(org.eclipse.equinox.p2.tests.metadata.repository.AllTests.suite()); suite.addTest(org.eclipse.equinox.p2.tests.mirror.AllTests.suite()); suite.addTest(org.eclipse.equinox.p2.tests.omniVersion.AllTests.suite()); suite.addTest(org.eclipse.equinox.p2.tests.planner.AllTests.suite()); suite.addTest(org.eclipse.equinox.p2.tests.publisher.AllTests.suite()); + suite.addTest(org.eclipse.equinox.p2.tests.ql.AllTests.suite()); suite.addTest(org.eclipse.equinox.p2.tests.repository.AllTests.suite()); suite.addTest(org.eclipse.equinox.p2.tests.simpleconfigurator.SimpleConfiguratorTests.suite()); suite.addTest(org.eclipse.equinox.p2.tests.simpleconfigurator.manipulator.AllTests.suite()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/FailingMetadataRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/FailingMetadataRepositoryFactory.java index 5126261be..6eb7adacb 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/FailingMetadataRepositoryFactory.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/FailingMetadataRepositoryFactory.java @@ -13,9 +13,9 @@ package org.eclipse.equinox.p2.tests; import java.net.URI; import java.util.Map; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory; /** * A repository factory that always throws exceptions. The "fail" flag must be set to diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/IUPropertyUtils.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/IUPropertyUtils.java deleted file mode 100644 index f0efa0f3c..000000000 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/IUPropertyUtils.java +++ /dev/null @@ -1,231 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * EclipseSource - ongoing development - *******************************************************************************/ -package org.eclipse.equinox.p2.tests; - -import java.lang.ref.SoftReference; -import java.util.*; -import org.eclipse.equinox.internal.p2.metadata.InstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; - -public class IUPropertyUtils { - - IQueryable queryable; - - /** - * - */ - public IUPropertyUtils(IQueryable queryable) { - this.queryable = queryable; - } - - // TODO: these constants should come from API, eg. IInstallableUnit or ??? - final Locale DEFAULT_LOCALE = new Locale("df", "LT"); //$NON-NLS-1$//$NON-NLS-2$ - final String NAMESPACE_IU_LOCALIZATION = "org.eclipse.equinox.p2.localization"; //$NON-NLS-1$ - - // Cache the IU fragments that provide localizations for a given locale. - // map: locale => soft reference to a collector - private Map LocaleCollectorCache = new HashMap(2); - - // Get the license in the default locale. - public ILicense getLicense(IInstallableUnit iu) { - return getLicense(iu, getCurrentLocale()); - } - - // Get the copyright in the default locale. - public ICopyright getCopyright(IInstallableUnit iu) { - return getCopyright(iu, getCurrentLocale()); - } - - // Get a property in the default locale - public String getIUProperty(IInstallableUnit iu, String propertyKey) { - return getIUProperty(iu, propertyKey, getCurrentLocale()); - } - - public ILicense getLicense(IInstallableUnit iu, Locale locale) { - ILicense license = iu.getLicense(); - String body = (license != null ? license.getBody() : null); - if (body == null || body.length() <= 1 || body.charAt(0) != '%') - return license; - final String actualKey = body.substring(1); // Strip off the % - body = getLocalizedIUProperty(iu, actualKey, locale); - return MetadataFactory.createLicense(license.getLocation(), body); - } - - public ICopyright getCopyright(IInstallableUnit iu, Locale locale) { - ICopyright copyright = iu.getCopyright(); - String body = (copyright != null ? copyright.getBody() : null); - if (body == null || body.length() <= 1 || body.charAt(0) != '%') - return copyright; - final String actualKey = body.substring(1); // Strip off the % - body = getLocalizedIUProperty(iu, actualKey, locale); - return MetadataFactory.createCopyright(copyright.getLocation(), body); - } - - public String getIUProperty(IInstallableUnit iu, String propertyKey, Locale locale) { - String value = iu.getProperty(propertyKey); - if (value == null || value.length() <= 1 || value.charAt(0) != '%') - return value; - // else have a localizable property - final String actualKey = value.substring(1); // Strip off the % - return getLocalizedIUProperty(iu, actualKey, locale); - } - - private String getLocalizedIUProperty(IInstallableUnit iu, String actualKey, Locale locale) { - String localizedKey = makeLocalizedKey(actualKey, locale.toString()); - String localizedValue = null; - - //first check for a cached localized value - if (iu instanceof InstallableUnit) - localizedValue = ((InstallableUnit) iu).getLocalizedProperty(localizedKey); - //next check if the localized value is stored in the same IU (common case) - if (localizedValue == null) - localizedValue = iu.getProperty(localizedKey); - if (localizedValue != null) - return localizedValue; - - final List locales = buildLocaleVariants(locale); - final IInstallableUnit theUnit = iu; - - Collector localizationFragments = getLocalizationFragments(locale, locales); - - Collector hostLocalizationCollector = new Collector() { - public boolean accept(Object object) { - boolean haveHost = false; - if (object instanceof IInstallableUnitFragment) { - IInstallableUnitFragment fragment = (IInstallableUnitFragment) object; - IRequiredCapability[] hosts = fragment.getHost(); - for (int i = 0; i < hosts.length; i++) { - IRequiredCapability nextHost = hosts[i]; - if (IInstallableUnit.NAMESPACE_IU_ID.equals(nextHost.getNamespace()) && // - theUnit.getId().equals(nextHost.getName()) && // - nextHost.getRange() != null && // - nextHost.getRange().isIncluded(theUnit.getVersion())) { - haveHost = true; - break; - } - } - } - return (haveHost ? super.accept(object) : true); - } - }; - - IUPropertyQuery iuQuery = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_FRAGMENT, "true"); //$NON-NLS-1$ - Collector collected = iuQuery.perform(localizationFragments.iterator(), hostLocalizationCollector); - - if (!collected.isEmpty()) { - String translation = null; - for (Iterator iter = collected.iterator(); iter.hasNext() && translation == null;) { - IInstallableUnit localizationIU = (IInstallableUnit) iter.next(); - for (Iterator jter = locales.iterator(); jter.hasNext();) { - String localeKey = makeLocalizedKey(actualKey, (String) jter.next()); - translation = localizationIU.getProperty(localeKey); - if (translation != null) - return cacheResult(iu, localizedKey, translation); - } - } - } - - for (Iterator iter = locales.iterator(); iter.hasNext();) { - String nextLocale = (String) iter.next(); - String localeKey = makeLocalizedKey(actualKey, nextLocale); - String nextValue = iu.getProperty(localeKey); - if (nextValue != null) - return cacheResult(iu, localizedKey, nextValue); - } - - return cacheResult(iu, localizedKey, actualKey); - } - - /** - * Cache the translated property value to optimize future retrieval of the same value. - * Currently we just cache on the installable unit object in memory. In future - * we should push support for localized property retrieval into IInstallableUnit - * so we aren't required to reach around the API here. - */ - private String cacheResult(IInstallableUnit iu, String localizedKey, String localizedValue) { - if (iu instanceof InstallableUnit) - ((InstallableUnit) iu).setLocalizedProperty(localizedKey, localizedValue); - return localizedValue; - } - - /** - * Collects the installable unit fragments that contain locale data for the given locales. - */ - private synchronized Collector getLocalizationFragments(Locale locale, List localeVariants) { - SoftReference collectorRef = (SoftReference) LocaleCollectorCache.get(locale); - if (collectorRef != null) { - Collector cached = (Collector) collectorRef.get(); - if (cached != null) - return cached; - } - - final List locales = localeVariants; - - Collector localeFragmentCollector = new Collector() { - public boolean accept(Object object) { - boolean haveLocale = false; - if (object instanceof IInstallableUnitFragment) { - IInstallableUnitFragment fragment = (IInstallableUnitFragment) object; - IProvidedCapability[] provides = fragment.getProvidedCapabilities(); - for (int j = 0; j < provides.length && !haveLocale; j++) { - IProvidedCapability nextProvide = provides[j]; - if (NAMESPACE_IU_LOCALIZATION.equals(nextProvide.getNamespace())) { - String providedLocale = nextProvide.getName(); - if (providedLocale != null) { - for (Iterator iter = locales.iterator(); iter.hasNext();) { - if (providedLocale.equals(iter.next())) { - haveLocale = true; - break; - } - } - } - } - } - } - return (haveLocale ? super.accept(object) : true); - } - }; - - IUPropertyQuery iuQuery = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_FRAGMENT, "true"); //$NON-NLS-1$ - Collector collected = queryable.query(iuQuery, localeFragmentCollector, null); - LocaleCollectorCache.put(locale, new SoftReference(collected)); - return collected; - } - - /** - */ - private List buildLocaleVariants(Locale locale) { - String nl = locale.toString(); - ArrayList result = new ArrayList(4); - int lastSeparator; - while (true) { - result.add(nl); - lastSeparator = nl.lastIndexOf('_'); - if (lastSeparator == -1) - break; - nl = nl.substring(0, lastSeparator); - } - // Add the default locale (most general) - result.add(DEFAULT_LOCALE.toString()); - return result; - } - - private String makeLocalizedKey(String actualKey, String localeImage) { - return localeImage + '.' + actualKey; - } - - private Locale getCurrentLocale() { - return Locale.getDefault(); - } - -} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/MockQueryable.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/MockQueryable.java index 1f09bab10..dfe6b5d6f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/MockQueryable.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/MockQueryable.java @@ -13,7 +13,7 @@ package org.eclipse.equinox.p2.tests; import java.util.ArrayList; import java.util.Collection; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.p2.query.*; /** * A test queryable that contains a simple collection of objects. @@ -35,8 +35,8 @@ public class MockQueryable implements IQueryable { } - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - return query.perform(items.iterator(), collector); + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return query.perform(items.iterator()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestActivator.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestActivator.java index 7c51861c8..310fa1b57 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestActivator.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestActivator.java @@ -44,9 +44,9 @@ public class TestActivator implements BundleActivator { packageAdmin = (PackageAdmin) context.getService(packageAdminRef); //This is a hack because the junit plugin launch config do not allow to start bundles - getBundle("org.eclipse.equinox.p2.exemplarysetup").start(); - getBundle("org.eclipse.equinox.frameworkadmin.equinox").start(); - getBundle("org.eclipse.equinox.simpleconfigurator.manipulator").start(); + AbstractProvisioningTest.startBundle(getBundle("org.eclipse.equinox.p2.exemplarysetup")); + AbstractProvisioningTest.startBundle(getBundle("org.eclipse.equinox.frameworkadmin.equinox")); + AbstractProvisioningTest.startBundle(getBundle("org.eclipse.equinox.simpleconfigurator.manipulator")); } public void stop(BundleContext context) throws Exception { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestArtifactRepository.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestArtifactRepository.java index 6ec898f2a..aa3d7f5a1 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestArtifactRepository.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestArtifactRepository.java @@ -20,12 +20,14 @@ import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.artifact.repository.ArtifactRequest; import org.eclipse.equinox.internal.p2.repository.Transport; import org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepHandler; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryCreationException; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.AbstractArtifactRepository; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRequest; +import org.eclipse.equinox.p2.repository.artifact.spi.AbstractArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; /** * A simple artifact repository implementation used for testing purposes. @@ -107,10 +109,6 @@ public class TestArtifactRepository extends AbstractArtifactRepository { return keysToLocations.get(key); } - public IArtifactKey[] getArtifactKeys() { - return keysToLocations.keySet().toArray(new IArtifactKey[keysToLocations.keySet().size()]); - } - private IStatus getArtifact(ArtifactRequest request, IProgressMonitor monitor) { request.setSourceRepository(this); request.perform(monitor); @@ -130,7 +128,7 @@ public class TestArtifactRepository extends AbstractArtifactRepository { } } - public void initialize(URI repoURL, InputStream descriptorFile) throws RepositoryCreationException { + public void initialize(URI repoURL, InputStream descriptorFile) { location = repoURL; } @@ -194,4 +192,14 @@ public class TestArtifactRepository extends AbstractArtifactRepository { public OutputStream getOutputStream(IArtifactDescriptor descriptor) { throw new UnsupportedOperationException("Method is not implemented by this repository"); } + + public IQueryable descriptorQueryable() { + // TODO Auto-generated method stub + return null; + } + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + // TODO Auto-generated method stub + return null; + } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestMetadataRepository.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestMetadataRepository.java index 8cc075fbb..05130d887 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestMetadataRepository.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/TestMetadataRepository.java @@ -10,19 +10,21 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import junit.framework.Assert; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.AbstractMetadataRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.RepositoryReference; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.spi.AbstractMetadataRepository; +import org.eclipse.equinox.p2.repository.spi.RepositoryReference; /** * A simple metadata repository used for testing purposes. All metadata @@ -58,7 +60,7 @@ public class TestMetadataRepository extends AbstractMetadataRepository { } public IInstallableUnit find(String id, String versionString) { - Iterator result = query(new InstallableUnitQuery(id, new Version(versionString)), new Collector(), null).iterator(); + Iterator result = query(new InstallableUnitQuery(id, Version.create(versionString)), null).iterator(); return (IInstallableUnit) (result.hasNext() ? result.next() : null); } @@ -69,8 +71,8 @@ public class TestMetadataRepository extends AbstractMetadataRepository { return null; } - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - return query.perform(units.iterator(), collector); + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return query.perform(units.iterator()); } public void removeAll() { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/CompositeRepositoryTaskTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/CompositeRepositoryTaskTest.java index 0127f5869..759155a62 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/CompositeRepositoryTaskTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/CompositeRepositoryTaskTest.java @@ -18,12 +18,12 @@ import org.eclipse.core.runtime.URIUtil; import org.eclipse.equinox.internal.p2.artifact.repository.CompositeArtifactRepository; import org.eclipse.equinox.internal.p2.metadata.repository.CompositeMetadataRepository; import org.eclipse.equinox.internal.p2.repository.helpers.RepositoryHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.ICompositeRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.ICompositeRepository; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractAntProvisioningTest; public class CompositeRepositoryTaskTest extends AbstractAntProvisioningTest { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/MirrorTaskTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/MirrorTaskTest.java index e01bb1e31..23af9407f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/MirrorTaskTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/MirrorTaskTest.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.ant; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.*; import java.net.URI; @@ -21,13 +21,15 @@ import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.artifact.processors.md5.Messages; import org.eclipse.equinox.internal.p2.director.PermissiveSlicer; import org.eclipse.equinox.internal.p2.metadata.InstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.internal.repository.comparator.MD5ArtifactComparator; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractAntProvisioningTest; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; @@ -301,7 +303,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { } catch (ProvisionException e) { fail("Loading repository failed", e); } - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); AntTaskElement mirror = createMirrorTask(TYPE_METADATA); @@ -315,7 +317,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { p.setProperty("org.eclipse.update.install.features", String.valueOf(true)); PermissiveSlicer slicer = new PermissiveSlicer(repo, p, true, true, true, true, false); IQueryable result = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()); - assertEquals("Different number of IUs", result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size(), getIUCount(destinationRepo)); + assertEquals("Different number of IUs", queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())), getIUCount(destinationRepo)); try { assertIUContentEquals("IUs differ", result, getMetadataRepositoryManager().loadRepository(destinationRepo, null)); @@ -331,7 +333,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { } catch (ProvisionException e) { fail("Loading repository failed", e); } - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); AntTaskElement mirror = createMirrorTask(TYPE_METADATA); @@ -344,7 +346,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { PermissiveSlicer slicer = new PermissiveSlicer(repo, new Properties(), true, false, true, false, false); IQueryable result = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()); - assertEquals("Different number of IUs", result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size(), getIUCount(destinationRepo)); + assertEquals("Different number of IUs", queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())), getIUCount(destinationRepo)); try { assertIUContentEquals("IUs differ", result, getMetadataRepositoryManager().loadRepository(destinationRepo, null)); } catch (ProvisionException e) { @@ -359,7 +361,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { } catch (ProvisionException e) { fail("Loading repository failed", e); } - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); AntTaskElement mirror = createMirrorTask(TYPE_METADATA); @@ -373,7 +375,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { p.setProperty("org.eclipse.update.install.features", String.valueOf(true)); PermissiveSlicer slicer = new PermissiveSlicer(repo, p, false, true, true, false, false); IQueryable result = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()); - assertEquals("Different number of IUs", result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size(), getIUCount(destinationRepo)); + assertEquals("Different number of IUs", queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())), getIUCount(destinationRepo)); try { assertIUContentEquals("IUs differ", result, getMetadataRepositoryManager().loadRepository(destinationRepo, null)); } catch (ProvisionException e) { @@ -388,7 +390,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { } catch (ProvisionException e) { fail("Loading repository failed", e); } - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); AntTaskElement mirror = createMirrorTask(TYPE_METADATA); @@ -401,7 +403,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { Properties p = getSliceProperties(); PermissiveSlicer slicer = new PermissiveSlicer(repo, p, true, true, true, false, false); IQueryable result = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()); - assertEquals("Different number of IUs", result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size(), getIUCount(destinationRepo)); + assertEquals("Different number of IUs", queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())), getIUCount(destinationRepo)); try { assertIUContentEquals("IUs differ", result, getMetadataRepositoryManager().loadRepository(destinationRepo, null)); } catch (ProvisionException e) { @@ -419,7 +421,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { } catch (ProvisionException e) { fail("Loading repository failed", e); } - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); AntTaskElement mirror = createMirrorTask(TYPE_METADATA); @@ -433,7 +435,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { p.setProperty("org.eclipse.update.install.features", String.valueOf(true)); PermissiveSlicer slicer = new PermissiveSlicer(repo, p, true, true, true, false, false); IQueryable result = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()); - assertEquals("Different number of IUs", result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size(), getIUCount(destinationRepo)); + assertEquals("Different number of IUs", queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())), getIUCount(destinationRepo)); try { assertIUContentEquals("IUs differ", result, getMetadataRepositoryManager().loadRepository(destinationRepo, null)); } catch (ProvisionException e) { @@ -451,7 +453,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { } catch (ProvisionException e) { fail("Loading repository failed", e); } - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); // Create task @@ -465,7 +467,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { Properties p = getSliceProperties(); PermissiveSlicer slicer = new PermissiveSlicer(repo, p, true, true, true, false, false); IQueryable result = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()); - assertEquals("Different number of IUs", result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size(), getIUCount(destinationRepo)); + assertEquals("Different number of IUs", queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())), getIUCount(destinationRepo)); try { assertIUContentEquals("IUs differ", result, getMetadataRepositoryManager().loadRepository(destinationRepo, null)); } catch (ProvisionException e) { @@ -483,7 +485,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { } catch (ProvisionException e) { fail("Loading repository failed", e); } - Collector c = repo.query(new InstallableUnitQuery("test.feature.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("test.feature.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); // Create task @@ -498,10 +500,10 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { PermissiveSlicer slicer = new PermissiveSlicer(repo, p, true, true, true, false, false); IQueryable result = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()); - assertEquals("Different number of IUs", result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size(), getIUCount(destinationRepo)); - assertEquals("Different number of ArtifactKeys", getArtifactKeyCount(result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor())), getArtifactKeyCount(destinationRepo)); + assertEquals("Different number of IUs", queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())), getIUCount(destinationRepo)); + assertEquals("Different number of ArtifactKeys", getArtifactKeyCount(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())), getArtifactKeyCount(destinationRepo)); try { - assertArtifactKeyContentEquals("Different ArtifactKeys", result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()), destinationRepo); + assertArtifactKeyContentEquals("Different ArtifactKeys", result.query(InstallableUnitQuery.ANY, new NullProgressMonitor()), destinationRepo); assertIUContentEquals("IUs differ", result, getMetadataRepositoryManager().loadRepository(destinationRepo, null)); } catch (ProvisionException e) { fail("Failed to compare contents", e); @@ -519,7 +521,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { } catch (ProvisionException e) { fail("Loading repository failed", e); } - Collector c = repo.query(new InstallableUnitQuery("test.feature.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("test.feature.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); // Create task @@ -534,8 +536,8 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { PermissiveSlicer slicer = new PermissiveSlicer(repo, p, true, true, true, false, false); IQueryable result = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()); - assertEquals("Different number of ArtifactKeys", getArtifactKeyCount(result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor())), getArtifactKeyCount(destinationRepo)); - assertArtifactKeyContentEquals("Different ArtifactKeys", result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()), destinationRepo); + assertEquals("Different number of ArtifactKeys", getArtifactKeyCount(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())), getArtifactKeyCount(destinationRepo)); + assertArtifactKeyContentEquals("Different ArtifactKeys", result.query(InstallableUnitQuery.ANY, new NullProgressMonitor()), destinationRepo); } /* @@ -548,10 +550,10 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { } catch (ProvisionException e) { fail("Loading repository failed", e); } - Collector c = repo.query(new InstallableUnitQuery("test.feature.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("test.feature.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); - c = repo.query(new InstallableUnitQuery("RCP_Browser_Example.feature.group"), new Collector(), new NullProgressMonitor()); + c = repo.query(new InstallableUnitQuery("RCP_Browser_Example.feature.group"), new NullProgressMonitor()); IInstallableUnit iu2 = (IInstallableUnit) c.iterator().next(); // Create task @@ -567,8 +569,8 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { PermissiveSlicer slicer = new PermissiveSlicer(repo, p, true, true, true, false, false); IQueryable result = slicer.slice(new IInstallableUnit[] {iu, iu2}, new NullProgressMonitor()); - assertEquals("Different number of ArtifactKeys", getArtifactKeyCount(result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor())), getArtifactKeyCount(destinationRepo)); - assertArtifactKeyContentEquals("Different ArtifactKeys", result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()), destinationRepo); + assertEquals("Different number of ArtifactKeys", getArtifactKeyCount(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())), getArtifactKeyCount(destinationRepo)); + assertArtifactKeyContentEquals("Different ArtifactKeys", result.query(InstallableUnitQuery.ANY, new NullProgressMonitor()), destinationRepo); } /* @@ -581,7 +583,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { } catch (ProvisionException e) { fail("Loading repository failed", e); } - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.ui.examples.readmetool"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.ui.examples.readmetool"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); // Create task @@ -623,7 +625,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { */ public void testBaselineCompareUsingMD5Comparator() { //Setup create descriptors with different md5 values - IArtifactKey dupKey = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey dupKey = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); File artifact1 = getTestData("0.0", "/testData/mirror/mirrorSourceRepo1 with space/content.xml"); File artifact2 = getTestData("0.0", "/testData/mirror/mirrorSourceRepo2/content.xml"); @@ -677,6 +679,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { // Create a comparator element AntTaskElement comparator = new AntTaskElement("comparator"); + comparator.addAttribute("comparator", MD5ArtifactComparator.MD5_COMPARATOR_ID); comparator.addElement(getRepositoryElement(baselineLocation.toURI(), null)); mirror.addElement(comparator); @@ -750,38 +753,10 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { /* * Get the number of ArtifactKeys in a repository */ - protected int getArtifactKeyCount(URI location) { - try { - return getArtifactRepositoryManager().loadRepository(location, null).getArtifactKeys().length; - } catch (ProvisionException e) { - fail("Failed to load repository " + URIUtil.toUnencodedString(location) + " for ArtifactDescriptor count"); - return -1; - } - } - - /* - * Get the number of ArtifactKeys in a repository - */ - protected int getArtifactKeyCount(Collector ius) { + protected int getArtifactKeyCount(IQueryResult ius) { int count = 0; for (Iterator iter = ius.iterator(); iter.hasNext();) - count += ((InstallableUnit) iter.next()).getArtifacts().length; - return count; - } - - /* - * Get the number of ArtifactDescriptors in a repository - */ - protected int getArtifactDescriptorCount(URI location) { - int count = 0; - try { - IArtifactRepository repo = getArtifactRepositoryManager().loadRepository(location, null); - IArtifactKey[] keys = repo.getArtifactKeys(); - for (int i = 0; i < keys.length; i++) - count += repo.getArtifactDescriptors(keys[i]).length; - } catch (ProvisionException e) { - fail("Failed to load repository " + URIUtil.toUnencodedString(location) + " for ArtifactDescriptor count"); - } + count += ((InstallableUnit) iter.next()).getArtifacts().size(); return count; } @@ -790,7 +765,7 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { */ protected int getIUCount(URI location) { try { - return getMetadataRepositoryManager().loadRepository(location, null).query(InstallableUnitQuery.ANY, new Collector(), null).size(); + return queryResultSize(getMetadataRepositoryManager().loadRepository(location, null).query(InstallableUnitQuery.ANY, null)); } catch (ProvisionException e) { fail("Failed to load repository " + URIUtil.toUnencodedString(location) + " for ArtifactDescriptor count"); return -1; @@ -801,9 +776,9 @@ public class MirrorTaskTest extends AbstractAntProvisioningTest { * Add all IUs to the parent element */ protected void addAllIUs(AntTaskElement parent, IMetadataRepository repo) { - Collector collector = repo.query(InstallableUnitQuery.ANY, new Collector(), null); + IQueryResult queryResult = repo.query(InstallableUnitQuery.ANY, null); - for (Iterator iter = collector.iterator(); iter.hasNext();) { + for (Iterator iter = queryResult.iterator(); iter.hasNext();) { IInstallableUnit iu = (IInstallableUnit) iter.next(); parent.addElement(createIUElement(iu)); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/Repo2RunnableTaskTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/Repo2RunnableTaskTests.java index 93a0a334f..1fb74ff9b 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/Repo2RunnableTaskTests.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/Repo2RunnableTaskTests.java @@ -12,16 +12,15 @@ package org.eclipse.equinox.p2.tests.ant; import java.io.File; import java.net.URI; -import java.util.Collection; +import java.util.Iterator; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractAntProvisioningTest; public class Repo2RunnableTaskTests extends AbstractAntProvisioningTest { @@ -61,8 +60,8 @@ public class Repo2RunnableTaskTests extends AbstractAntProvisioningTest { IInstallableUnit iu = null; try { IMetadataRepository repo = getMetadataRepositoryManager().loadRepository(source, new NullProgressMonitor()); - Collection ius = repo.query(new InstallableUnitQuery("helloworldfeature.feature.jar"), new Collector(), new NullProgressMonitor()).toCollection(); - assertEquals("Expected number of IUs", 1, ius.size()); + IQueryResult ius = repo.query(new InstallableUnitQuery("helloworldfeature.feature.jar"), new NullProgressMonitor()); + assertEquals("Expected number of IUs", 1, queryResultSize(ius)); iu = (IInstallableUnit) ius.iterator().next(); } catch (ProvisionException e) { fail("Failed to obtain iu", e); @@ -71,7 +70,7 @@ public class Repo2RunnableTaskTests extends AbstractAntProvisioningTest { task.addElement(createIUElement(iu)); runAntTask(); - assertEquals("Number of artifact keys differs", iu.getArtifacts().length, getArtifactKeyCount(destination)); + assertEquals("Number of artifact keys differs", iu.getArtifacts().size(), getArtifactKeyCount(destination)); assertTrue("Unexpected format", expectedFormat(destination)); } @@ -117,9 +116,9 @@ public class Repo2RunnableTaskTests extends AbstractAntProvisioningTest { } catch (ProvisionException e) { fail("Failed to load repository", e); } - IArtifactKey[] keys = repo.getArtifactKeys(); - for (int i = 0; i < keys.length; i++) { - IArtifactKey key = keys[i]; + IQueryResult keys = repo.query(ArtifactKeyQuery.ALL_KEYS, null); + for (Iterator iterator = keys.iterator(); iterator.hasNext();) { + IArtifactKey key = (IArtifactKey) iterator.next(); IArtifactDescriptor[] descriptors = repo.getArtifactDescriptors(key); for (int n = 0; n < descriptors.length; n++) { IArtifactDescriptor desc = descriptors[n]; @@ -130,24 +129,12 @@ public class Repo2RunnableTaskTests extends AbstractAntProvisioningTest { else assertFalse(desc + " is a folder", isFolder); // Artifacts should not be packed - assertTrue("Artifact is still packed", !"packed".equals(desc.getProperty("format"))); + assertTrue("Artifact is still packed", !IArtifactDescriptor.FORMAT_PACKED.equals(desc.getProperty(IArtifactDescriptor.FORMAT))); } } return true; } - /* - * Count the number of ArtifactKeys in the repository at the given location - */ - protected int getArtifactKeyCount(URI location) { - try { - return getArtifactRepositoryManager().loadRepository(location, new NullProgressMonitor()).getArtifactKeys().length; - } catch (ProvisionException e) { - fail("Failed to count keys in repository", e); - return -1; - } - } - /* * Create a simple AntTaskElement for the Repo2RunnableTask */ diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/RepoTasksTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/RepoTasksTests.java index 9c274bab6..037c23683 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/RepoTasksTests.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ant/RepoTasksTests.java @@ -12,10 +12,11 @@ package org.eclipse.equinox.p2.tests.ant; import java.io.File; import java.net.URI; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.ArtifactKeyQuery; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractAntProvisioningTest; public class RepoTasksTests extends AbstractAntProvisioningTest { @@ -63,10 +64,8 @@ public class RepoTasksTests extends AbstractAntProvisioningTest { assertNull(iu); IArtifactRepository artifacts = getArtifactRepositoryManager().loadRepository(destinationRepo, null); - IArtifactKey[] keys = artifacts.getArtifactKeys(); - for (int i = 0; i < keys.length; i++) { - assertFalse(keys[i].getId().equals("anotherplugin")); - } + IQueryResult keys = artifacts.query(new ArtifactKeyQuery(null, "anotherplugin", null), null); + assertTrue(keys.isEmpty()); assertFalse(new File(getTestFolder(getName()), "plugins/anotherplugin_1.0.0.jar").exists()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/processors/ArtifactRepositoryMock.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/processors/ArtifactRepositoryMock.java index 3a65650b1..a0ab65372 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/processors/ArtifactRepositoryMock.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/processors/ArtifactRepositoryMock.java @@ -14,8 +14,8 @@ import java.io.*; import java.lang.reflect.*; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; import org.eclipse.equinox.p2.tests.TestActivator; /** diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactOutputStreamTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactOutputStreamTest.java index 141681015..2c431c266 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactOutputStreamTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactOutputStreamTest.java @@ -11,7 +11,7 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.*; import junit.framework.TestCase; @@ -19,11 +19,11 @@ import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository; import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository.ArtifactOutputStream; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; import org.eclipse.equinox.internal.provisional.p2.repository.IStateful; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class ArtifactOutputStreamTest extends TestCase { @@ -44,7 +44,7 @@ public class ArtifactOutputStreamTest extends TestCase { tempWritableLocation.mkdirs(); sar = new SimpleArtifactRepository("name", tempWritableLocation.toURI(), null); destination = new Destination(); - ak = new ArtifactKey("classifier", "id", new Version("1.0")); + ak = new ArtifactKey("classifier", "id", Version.create("1.0")); ad = new ArtifactDescriptor(ak); temp = File.createTempFile("ArtifactOutputStreamTest", ".tmp"); temp.deleteOnExit(); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactRepositoryManagerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactRepositoryManagerTest.java index 2db20ca3c..5493af202 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactRepositoryManagerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactRepositoryManagerTest.java @@ -19,11 +19,15 @@ import junit.framework.TestSuite; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.preferences.IPreferencesService; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.*; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; import org.eclipse.equinox.p2.tests.*; +import org.eclipse.equinox.security.storage.EncodingUtils; import org.osgi.framework.BundleException; import org.osgi.service.prefs.BackingStoreException; import org.osgi.service.prefs.Preferences; @@ -60,7 +64,7 @@ public class ArtifactRepositoryManagerTest extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - manager = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.context, IArtifactRepositoryManager.class.getName()); + manager = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.context, IArtifactRepositoryManager.SERVICE_NAME); } /** @@ -109,7 +113,9 @@ public class ArtifactRepositoryManagerTest extends AbstractProvisioningTest { //bash the repository preference file (don't try this at home, kids) final String REPO_BUNDLE = "org.eclipse.equinox.p2.artifact.repository"; IPreferencesService prefService = (IPreferencesService) ServiceHelper.getService(TestActivator.getContext(), IPreferencesService.class.getName()); - Preferences prefs = prefService.getRootNode().node("/profile/_SELF_/" + REPO_BUNDLE + "/repositories"); //$NON-NLS-1$ //$NON-NLS-2$ + IAgentLocation agentLocation = (IAgentLocation) getAgent().getService(IAgentLocation.SERVICE_NAME); + String locationString = EncodingUtils.encodeSlashes(agentLocation.getRootLocation().toString()); + Preferences prefs = prefService.getRootNode().node("/profile/" + locationString + "_SELF_/" + REPO_BUNDLE + "/repositories"); //$NON-NLS-1$ //$NON-NLS-2$ try { String[] children = prefs.childrenNames(); for (int i = 0; i < children.length; i++) @@ -121,14 +127,13 @@ public class ArtifactRepositoryManagerTest extends AbstractProvisioningTest { //stop and restart the artifact repository bundle (kids, if I ever catch you doing this I'm taking PackageAdmin away) try { - TestActivator.getBundle(REPO_BUNDLE).stop(); - TestActivator.getBundle(REPO_BUNDLE).start(); + restartBundle(TestActivator.getBundle(REPO_BUNDLE)); } catch (BundleException e) { fail("1.99", e); } //everybody's happy again - manager = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.context, IArtifactRepositoryManager.class.getName()); + manager = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.context, IArtifactRepositoryManager.SERVICE_NAME); assertTrue("1.0", manager.contains(location)); } @@ -157,12 +162,7 @@ public class ArtifactRepositoryManagerTest extends AbstractProvisioningTest { public void testPathWithSpaces() { File site = getTestData("Repository", "/testData/artifactRepo/simple with spaces/"); URI location = site.toURI(); - try { - IArtifactRepository repository = manager.loadRepository(location, getMonitor()); - assertEquals("1.0", 2, repository.getArtifactKeys().length); - } catch (ProvisionException e) { - fail("=.99", e); - } + assertEquals("1.0", 2, getArtifactKeyCount(location)); } /** @@ -217,12 +217,7 @@ public class ArtifactRepositoryManagerTest extends AbstractProvisioningTest { public void testUpdateSitePathWithSpaces() { File site = getTestData("Repository", "/testData/updatesite/site with spaces/"); URI location = site.toURI(); - try { - IArtifactRepository repository = manager.loadRepository(location, getMonitor()); - assertEquals("1.0", 3, repository.getArtifactKeys().length); - } catch (ProvisionException e) { - fail("=.99", e); - } + assertEquals("1.0", 3, getArtifactKeyCount(location)); } /** @@ -280,13 +275,8 @@ public class ArtifactRepositoryManagerTest extends AbstractProvisioningTest { * Tests parsing a repository with a duplicate element. See bug 255401. */ public void testDuplicateElement() { - try { - File duplicateElementXML = getTestData("testDuplicateElement", "testData/artifactRepo/duplicateElement"); - IArtifactRepository repo = getArtifactRepositoryManager().loadRepository(duplicateElementXML.toURI(), null); - assertEquals("Ensure correct number of artifact keys exist", 2, repo.getArtifactKeys().length); - } catch (ProvisionException e) { - fail("Error occured while loading repository with duplicate elements", e); - } + File duplicateElementXML = getTestData("testDuplicateElement", "testData/artifactRepo/duplicateElement"); + assertEquals("Ensure correct number of artifact keys exist", 2, getArtifactKeyCount(duplicateElementXML.toURI())); } public void testEnablement() { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactRepositoryMissingSizeData.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactRepositoryMissingSizeData.java index 14254436a..55a3045af 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactRepositoryMissingSizeData.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactRepositoryMissingSizeData.java @@ -10,21 +10,23 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.engine.phases.Sizing; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.internal.p2.engine.Phase; +import org.eclipse.equinox.internal.p2.engine.PhaseSet; +import org.eclipse.equinox.internal.p2.engine.phases.Sizing; +import org.eclipse.equinox.internal.provisional.p2.director.PlannerHelper; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; @@ -40,8 +42,8 @@ public class ArtifactRepositoryMissingSizeData extends AbstractProvisioningTest IMetadataRepositoryManager mmgr = getMetadataRepositoryManager(); metaRepo = mmgr.loadRepository((getTestData("MissingArtifact repo", testDataLocation).toURI()), null); - missingArtifactIU = (IInstallableUnit) metaRepo.query(new InstallableUnitQuery("javax.wsdl", new VersionRange("[1.5, 1.6)")), new Collector(), null).iterator().next(); - missingSizeIU = (IInstallableUnit) metaRepo.query(new InstallableUnitQuery("javax.wsdl", new VersionRange("[1.4, 1.5)")), new Collector(), null).iterator().next(); + missingArtifactIU = (IInstallableUnit) metaRepo.query(new InstallableUnitQuery("javax.wsdl", new VersionRange("[1.5, 1.6)")), null).iterator().next(); + missingSizeIU = (IInstallableUnit) metaRepo.query(new InstallableUnitQuery("javax.wsdl", new VersionRange("[1.4, 1.5)")), null).iterator().next(); IArtifactRepositoryManager mgr = getArtifactRepositoryManager(); source = mgr.loadRepository((getTestData("MissingArtifact repo", testDataLocation).toURI()), null); @@ -55,13 +57,13 @@ public class ArtifactRepositoryMissingSizeData extends AbstractProvisioningTest req.addInstallableUnits(new IInstallableUnit[] {missingArtifactIU}); req.setInstallableUnitInclusionRules(missingArtifactIU, PlannerHelper.createStrictInclusionRule(missingArtifactIU)); - ProvisioningPlan plan = createPlanner().getProvisioningPlan(req, null, null); + IProvisioningPlan plan = createPlanner().getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); Sizing sizing = new Sizing(100, ""); PhaseSet set = new SPhaseSet(sizing); - IStatus status = engine.perform(profile1, set, plan.getOperands(), null, new NullProgressMonitor()); + IStatus status = engine.perform(plan, set, new NullProgressMonitor()); if (!status.matches(IStatus.ERROR)) { fail("Incorrect status for missing artifact during Sizing."); } @@ -73,13 +75,13 @@ public class ArtifactRepositoryMissingSizeData extends AbstractProvisioningTest req.addInstallableUnits(new IInstallableUnit[] {missingSizeIU}); req.setInstallableUnitInclusionRules(missingSizeIU, PlannerHelper.createStrictInclusionRule(missingSizeIU)); - ProvisioningPlan plan = createPlanner().getProvisioningPlan(req, null, null); + IProvisioningPlan plan = createPlanner().getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); Sizing sizing = new Sizing(100, ""); PhaseSet set = new SPhaseSet(sizing); - IStatus status = engine.perform(profile1, set, plan.getOperands(), null, new NullProgressMonitor()); + IStatus status = engine.perform(plan, set, new NullProgressMonitor()); if (!status.matches(IStatus.WARNING) && status.getCode() != ProvisionException.ARTIFACT_INCOMPLETE_SIZING) { fail("Incorrect status for missing file size during Sizing"); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactRepositoryWithReferenceDescriptors.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactRepositoryWithReferenceDescriptors.java index 99bf84bb4..59be6964a 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactRepositoryWithReferenceDescriptors.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/ArtifactRepositoryWithReferenceDescriptors.java @@ -10,22 +10,22 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.ByteArrayOutputStream; import java.io.File; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactDescriptor; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class ArtifactRepositoryWithReferenceDescriptors extends AbstractProvisioningTest { IArtifactRepository repo = null; - ArtifactDescriptor descriptor1 = null; - ArtifactDescriptor descriptor2 = null; + SimpleArtifactDescriptor descriptor1 = null; + SimpleArtifactDescriptor descriptor2 = null; // // @@ -40,14 +40,14 @@ public class ArtifactRepositoryWithReferenceDescriptors extends AbstractProvisio super.setUp(); repo = createArtifactRepository(getTempFolder().toURI(), null); File fileLocation = getTestData("Artifacts for repositor with references", "testData/referenceArtifactRepo/test1 Reference.jar"); - descriptor1 = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "test1Reference", new Version("1.0.0"))); - descriptor1.setProcessingSteps(new ProcessingStepDescriptor[0]); + descriptor1 = new SimpleArtifactDescriptor(new ArtifactKey("osgi.bundle", "test1Reference", Version.create("1.0.0"))); + descriptor1.setProcessingSteps(new IProcessingStepDescriptor[0]); descriptor1.setRepositoryProperty("artifact.reference", fileLocation.toURL().toExternalForm()); descriptor1.setRepositoryProperty("file.name", fileLocation.getAbsolutePath()); descriptor1.setRepositoryProperty("file.lastModified", Long.toString(fileLocation.lastModified())); - descriptor2 = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "test1Reference", new Version("1.0.0"))); - descriptor2.setProcessingSteps(new ProcessingStepDescriptor[0]); + descriptor2 = new SimpleArtifactDescriptor(new ArtifactKey("osgi.bundle", "test1Reference", Version.create("1.0.0"))); + descriptor2.setProcessingSteps(new IProcessingStepDescriptor[0]); descriptor2.setRepositoryProperty("artifact.reference", fileLocation.toURI().toString()); descriptor2.setRepositoryProperty("file.name", fileLocation.getAbsolutePath()); descriptor2.setRepositoryProperty("file.lastModified", Long.toString(fileLocation.lastModified())); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/Bug252308.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/Bug252308.java index 12e7ccef4..d93317b0b 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/Bug252308.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/Bug252308.java @@ -10,15 +10,17 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.*; import java.lang.reflect.Method; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.artifact.repository.MirrorRequest; +import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactDescriptor; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** @@ -119,10 +121,10 @@ public class Bug252308 extends AbstractProvisioningTest { fail("failing setting up the tests", e); } - IArtifactDescriptor sourceDescriptor = getArtifactKeyFor(source, "osgi.bundle", "missingFromFileSystem", new Version(1, 0, 0))[0]; - ArtifactDescriptor targetDescriptor = new ArtifactDescriptor(sourceDescriptor); + IArtifactDescriptor sourceDescriptor = getArtifactKeyFor(source, "osgi.bundle", "missingFromFileSystem", Version.createOSGi(1, 0, 0))[0]; + SimpleArtifactDescriptor targetDescriptor = new SimpleArtifactDescriptor(sourceDescriptor); targetDescriptor.setRepositoryProperty("artifact.folder", "true"); - MirrorRequest request = new MirrorRequest(new ArtifactKey("osgi.bundle", "missingFromFileSystem", new Version(1, 0, 0)), target, null, null); + MirrorRequest request = new MirrorRequest(new ArtifactKey("osgi.bundle", "missingFromFileSystem", Version.createOSGi(1, 0, 0)), target, null, null); request.setSourceRepository(source); IStatus s = transferSingle(request, targetDescriptor, sourceDescriptor, new NullProgressMonitor()); assertTrue(s.toString(), s.getException().getClass() == FileNotFoundException.class); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/Bug265577.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/Bug265577.java index b00bcd5cd..20c87ce50 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/Bug265577.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/Bug265577.java @@ -14,15 +14,16 @@ import java.io.*; import java.net.URI; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; @@ -37,7 +38,7 @@ public class Bug265577 extends AbstractProvisioningTest { super.setUp(); profile = createProfile(Bug265577.class.getName()); - engine = (IEngine) ServiceHelper.getService(TestActivator.context, IEngine.class.getName()); + engine = (IEngine) ServiceHelper.getService(TestActivator.context, IEngine.SERVICE_NAME); // Load repositories File repoLocation = getTestData("Repository location", "/testData/bug265577/zipRepo.zip"); if (repoLocation == null) @@ -60,9 +61,9 @@ public class Bug265577 extends AbstractProvisioningTest { // Tests the response to a feature folder inside a jar public void testZippedRepoWithFolderFeature() { - Collector collector = metadataRepo.query(new InstallableUnitQuery("Field_Assist_Example.feature.jar"), new Collector(), null); - IInstallableUnit[] ius = (IInstallableUnit[]) collector.toArray(IInstallableUnit.class); - IArtifactKey key = (ius[0].getArtifacts())[0]; + IQueryResult queryResult = metadataRepo.query(new InstallableUnitQuery("Field_Assist_Example.feature.jar"), null); + IInstallableUnit[] ius = (IInstallableUnit[]) queryResult.toArray(IInstallableUnit.class); + IArtifactKey key = (ius[0].getArtifacts()).iterator().next(); IArtifactDescriptor[] descriptors = artifactRepo.getArtifactDescriptors(key); ArtifactDescriptor desc = (ArtifactDescriptor) descriptors[0]; @@ -84,9 +85,9 @@ public class Bug265577 extends AbstractProvisioningTest { // Test to retrieve a file from a zipped metadata & artifact repository public void testZippedRepo() { - Collector collector = metadataRepo.query(new InstallableUnitQuery("valid.feature.jar"), new Collector(), null); - IInstallableUnit[] ius = (IInstallableUnit[]) collector.toArray(IInstallableUnit.class); - IArtifactKey key = (ius[0].getArtifacts())[0]; + IQueryResult queryResult = metadataRepo.query(new InstallableUnitQuery("valid.feature.jar"), null); + IInstallableUnit[] ius = (IInstallableUnit[]) queryResult.toArray(IInstallableUnit.class); + IArtifactKey key = (ius[0].getArtifacts()).iterator().next(); IArtifactDescriptor[] descriptors = artifactRepo.getArtifactDescriptors(key); IArtifactDescriptor desc = descriptors[0]; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/CompositeArtifactRepositoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/CompositeArtifactRepositoryTest.java index bc794e3a5..762e6590a 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/CompositeArtifactRepositoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/CompositeArtifactRepositoryTest.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.*; import java.lang.reflect.Field; @@ -18,16 +18,19 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.*; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.artifact.processors.md5.MD5ArtifactComparator; import org.eclipse.equinox.internal.p2.artifact.repository.*; import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository; import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; import org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryState; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.internal.repository.comparator.MD5ArtifactComparator; +import org.eclipse.equinox.p2.internal.repository.tools.ArtifactRepositoryValidator; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestArtifactRepository; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; @@ -101,7 +104,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { CompositeArtifactRepository compRepo = createRepo(false); //Setup create a descriptor - IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); IArtifactDescriptor descriptor = PublisherHelper.createArtifactDescriptor(key, null); try { @@ -117,7 +120,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { CompositeArtifactRepository compRepo = createRepo(false); //Setup create a descriptor - IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); IArtifactDescriptor descriptor = PublisherHelper.createArtifactDescriptor(key, null); //Setup: create an array of descriptors @@ -137,7 +140,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { CompositeArtifactRepository compRepo = createRepo(false); //Setup create a descriptor - IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); IArtifactDescriptor descriptor = PublisherHelper.createArtifactDescriptor(key, null); try { @@ -153,7 +156,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { CompositeArtifactRepository compRepo = createRepo(false); //Setup create a key - IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); try { compRepo.removeDescriptor(key); @@ -307,7 +310,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { assertContains("Assert child2's content is in composite repo", repo2, compRepo); //checks that the destination has the correct number of keys (no extras) //FIXME will this work? - assertEquals("Assert Correct Number of Keys", repo1.getArtifactKeys().length + repo2.getArtifactKeys().length, compRepo.getArtifactKeys().length); + assertEquals("Assert Correct Number of Keys", getArtifactKeyCount(repo1) + getArtifactKeyCount(repo2), getArtifactKeyCount(compRepo)); } public void testRemoveNonexistantChild() { @@ -361,14 +364,14 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { } //get the keys - IArtifactKey[] keys = repo.getArtifactKeys(); - assertTrue("Error retreaiving artifact keys", keys.length > 0); + IQueryResult keys = repo.query(ArtifactKeyQuery.ALL_KEYS, null); + assertTrue("Error retreaiving artifact keys", !keys.isEmpty()); //test for existing key - assertTrue("Asserting key is in composite repo", compRepo.contains(keys[0])); + assertTrue("Asserting key is in composite repo", compRepo.contains((IArtifactKey) keys.iterator().next())); //Create a new key, not found in the composite repo - IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); //test for a non existing key assertFalse("Asserting key is not in composite repo", compRepo.contains(key)); } @@ -389,16 +392,16 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { } //get the descriptors - IArtifactKey[] keys = repo.getArtifactKeys(); - assertTrue("Error retreaiving artifact keys", keys.length > 0); - IArtifactDescriptor[] descriptors = repo.getArtifactDescriptors(keys[0]); + IQueryResult keys = repo.query(ArtifactKeyQuery.ALL_KEYS, null); + assertTrue("Error retreaiving artifact keys", !keys.isEmpty()); + IArtifactDescriptor[] descriptors = repo.getArtifactDescriptors((IArtifactKey) keys.iterator().next()); assertTrue("Error retreaiving artifact descriptors", descriptors.length > 0); //test for existing descriptor assertTrue("Asserting key is in composite repo", compRepo.contains(descriptors[0])); //Create a new descriptor, not found in the composite repo - IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); IArtifactDescriptor descriptor = PublisherHelper.createArtifactDescriptor(key, null); //test for a non existing descriptor assertFalse("Asserting key is not in composite repo", compRepo.contains(descriptor)); @@ -420,12 +423,13 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { fail("Error creating destination", e1); } - IArtifactKey[] keys = compRepo.getArtifactKeys(); - assertTrue("Error retreaiving artifact keys", keys.length > 0); - IArtifactDescriptor[] descriptors = compRepo.getArtifactDescriptors(keys[0]); + IQueryResult keys = compRepo.query(ArtifactKeyQuery.ALL_KEYS, null); + assertTrue("Error retreaiving artifact keys", !keys.isEmpty()); + IArtifactKey key = (IArtifactKey) keys.iterator().next(); + IArtifactDescriptor[] descriptors = compRepo.getArtifactDescriptors(key); assertTrue("Error retreaiving artifact descriptors", descriptors.length > 0); - IArtifactDescriptor newDescriptor = new ArtifactDescriptor(keys[0]); + IArtifactDescriptor newDescriptor = new ArtifactDescriptor(key); Map properties = new OrderedProperties(); properties.putAll(descriptors[0].getProperties()); properties.remove(IArtifactDescriptor.FORMAT); @@ -448,7 +452,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { fail("Error while downloading artifact", e); } //corresponding key should now be in the destination - assertTrue("Expected Key is not in destination", destinationRepo.contains(keys[0])); + assertTrue("Expected Key is not in destination", destinationRepo.contains(key)); IArtifactRepository repo = null; try { @@ -457,7 +461,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { fail("Unable to load repository for verification", e); } - IArtifactDescriptor[] srcDescriptors = repo.getArtifactDescriptors(keys[0]); + IArtifactDescriptor[] srcDescriptors = repo.getArtifactDescriptors(key); if (srcDescriptors == null) fail("Error finding descriptors for validation"); @@ -503,32 +507,34 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { } //create a request for a descriptor from repo1 - IArtifactKey[] keys1 = repo1.getArtifactKeys(); - assertTrue("Error retreaiving artifact keys", keys1.length > 0); - IArtifactDescriptor[] descriptors1 = repo1.getArtifactDescriptors(keys1[0]); + IQueryResult keys1 = repo1.query(ArtifactKeyQuery.ALL_KEYS, null); + IArtifactKey key1 = (IArtifactKey) keys1.iterator().next(); + assertTrue("Error retreaiving artifact keys", !keys1.isEmpty()); + IArtifactDescriptor[] descriptors1 = repo1.getArtifactDescriptors(key1); assertTrue("Error retreaiving artifact descriptors", descriptors1.length > 0); assertTrue("Expected key not in composite repository", compRepo.contains(descriptors1[0])); - IArtifactDescriptor newDescriptor1 = new ArtifactDescriptor(keys1[0]); + IArtifactDescriptor newDescriptor1 = new ArtifactDescriptor(key1); Map properties1 = new OrderedProperties(); properties1.putAll(descriptors1[0].getProperties()); properties1.remove(IArtifactDescriptor.FORMAT); ((ArtifactDescriptor) newDescriptor1).addProperties(properties1); // IArtifactRequest request1 = ((ArtifactRepositoryManager) getArtifactRepositoryManager()).createMirrorRequest(keys1[0], destinationRepo, (Properties) newDescriptor1.getProperties(), (Properties) destinationRepo.getProperties()); - IArtifactRequest request1 = ((ArtifactRepositoryManager) getArtifactRepositoryManager()).createMirrorRequest(keys1[0], destinationRepo, null, null); + IArtifactRequest request1 = ((ArtifactRepositoryManager) getArtifactRepositoryManager()).createMirrorRequest(key1, destinationRepo, null, null); //create a request for a descriptor from repo2 - IArtifactKey[] keys2 = repo2.getArtifactKeys(); - assertTrue("Error retreaiving artifact keys", keys2.length > 0); - IArtifactDescriptor[] descriptors2 = repo2.getArtifactDescriptors(keys2[0]); + IQueryResult keys2 = repo2.query(ArtifactKeyQuery.ALL_KEYS, null); + IArtifactKey key2 = (IArtifactKey) keys2.iterator().next(); + assertTrue("Error retreaiving artifact keys", !keys2.isEmpty()); + IArtifactDescriptor[] descriptors2 = repo2.getArtifactDescriptors(key2); assertTrue("Error retreaiving artifact descriptors", descriptors2.length > 0); assertTrue("Expected key not in composite repository", compRepo.contains(descriptors2[0])); - IArtifactDescriptor newDescriptor2 = new ArtifactDescriptor(keys2[0]); + IArtifactDescriptor newDescriptor2 = new ArtifactDescriptor(key2); Map properties2 = new OrderedProperties(); properties2.putAll(descriptors2[0].getProperties()); properties2.remove(IArtifactDescriptor.FORMAT); ((ArtifactDescriptor) newDescriptor2).addProperties(properties2); // IArtifactRequest request2 = ((ArtifactRepositoryManager) getArtifactRepositoryManager()).createMirrorRequest(keys2[0], destinationRepo, (Properties) newDescriptor2.getProperties(), (Properties) destinationRepo.getProperties()); - IArtifactRequest request2 = ((ArtifactRepositoryManager) getArtifactRepositoryManager()).createMirrorRequest(keys2[0], destinationRepo, null, null); + IArtifactRequest request2 = ((ArtifactRepositoryManager) getArtifactRepositoryManager()).createMirrorRequest(key2, destinationRepo, null, null); IArtifactRequest[] requests = new IArtifactRequest[2]; requests[0] = request1; @@ -546,8 +552,8 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { fail("Error while downloading artifacts", e); } //corresponding keys should now be in the destination - assertTrue("Expected Key is not in destination", destinationRepo.contains(keys1[0])); - assertTrue("Expected Key is not in destination", destinationRepo.contains(keys2[0])); + assertTrue("Expected Key is not in destination", destinationRepo.contains(key1)); + assertTrue("Expected Key is not in destination", destinationRepo.contains(key2)); //verify the file from repo1 File repo1File = ((SimpleArtifactRepository) repo1).getArtifactFile(descriptors1[0]); @@ -664,9 +670,9 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { assertEquals("Repository should only have 1 child", 1, compRepo.getChildren().size()); } - public void testValidate() { + public void testValidate() throws Exception { //Setup create descriptors with different md5 values - IArtifactKey dupKey = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey dupKey = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); File artifact1 = getTestData("0.0", "/testData/mirror/mirrorSourceRepo1 with space/artifacts.xml"); File artifact2 = getTestData("0.0", "/testData/mirror/mirrorSourceRepo2/artifacts.xml"); IArtifactDescriptor descriptor1 = PublisherHelper.createArtifactDescriptor(dupKey, artifact1); @@ -699,12 +705,13 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { compRepo.addChild(repo2Location.toURI()); //validate using the MD5 Comparator - assertFalse("Running verify on invalid repository", compRepo.validate(MD5ArtifactComparator.MD5_COMPARATOR_ID)); + ArtifactRepositoryValidator validator = new ArtifactRepositoryValidator(MD5ArtifactComparator.MD5_COMPARATOR_ID); + assertFalse("Running verify on invalid repository", validator.validateComposite(compRepo).isOK()); } - public void testAddChildWithValidate() { + public void testAddChildWithValidate() throws ProvisionException { //Setup create descriptors with different md5 values - IArtifactKey dupKey = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey dupKey = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); File artifact1 = getTestData("0.0", "/testData/mirror/mirrorSourceRepo1 with space/artifacts.xml"); File artifact2 = getTestData("0.0", "/testData/mirror/mirrorSourceRepo2/artifacts.xml"); IArtifactDescriptor descriptor1 = PublisherHelper.createArtifactDescriptor(dupKey, artifact1); @@ -733,10 +740,10 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { } //Add conflicting repositories - assertTrue("Adding first child with validate", compRepo.addChild(repo1Location.toURI(), MD5ArtifactComparator.MD5_COMPARATOR_ID)); - assertFalse("Adding conflicting child with validate", compRepo.addChild(repo2Location.toURI(), MD5ArtifactComparator.MD5_COMPARATOR_ID)); - - assertEquals("Asserting Composite Repository only has 1 child", 1, compRepo.getChildren().size()); + ArtifactRepositoryValidator validator = new ArtifactRepositoryValidator(MD5ArtifactComparator.MD5_COMPARATOR_ID); + assertTrue(validator.validateComposite(compRepo, repo1).isOK()); + compRepo.addChild(repo1Location.toURI()); + assertFalse(validator.validateComposite(compRepo, repo2).isOK()); } public void testEnabledAndSystemValues() { @@ -759,7 +766,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { compRepo.addChild(repo2Location.toURI()); //force composite repository to load all children - compRepo.getArtifactKeys(); + compRepo.getArtifactDescriptors(new ArtifactKey("", "", Version.emptyVersion)); assertTrue("Ensuring previously loaded repo is enabled", getArtifactRepositoryManager().isEnabled(repo1Location.toURI())); String repo1System = getArtifactRepositoryManager().getRepositoryProperty(repo1Location.toURI(), IRepository.PROP_SYSTEM); @@ -811,7 +818,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { assertContains("Assert child2's content is in composite repo", repo2, compRepo); //checks that the destination has the correct number of keys (no extras) //FIXME will this work? - assertEquals("Assert Correct Number of Keys", repo1.getArtifactKeys().length + repo2.getArtifactKeys().length, compRepo.getArtifactKeys().length); + assertEquals("Assert Correct Number of Keys", getArtifactKeyCount(repo1) + getArtifactKeyCount(repo2), getArtifactKeyCount(compRepo)); } private CompositeArtifactRepository createRepo(boolean compressed) { @@ -844,7 +851,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { URI childOne = new URI("memory:/in/memory/one"); URI childTwo = new URI("memory:/in/memory/two"); URI childThree = new URI("memory:/in/memory/three"); - CompositeArtifactRepository repository = new CompositeArtifactRepository(location, "in memory test", null); + CompositeArtifactRepository repository = createRepository(location, "in memory test"); repository.addChild(childOne); repository.addChild(childTwo); repository.addChild(childThree); @@ -872,7 +879,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { // create the composite repository and add the children URI location = new File(temp, "comp").toURI(); - CompositeArtifactRepository repository = new CompositeArtifactRepository(location, "test", null); + CompositeArtifactRepository repository = createRepository(location, "test"); try { repository.addChild(new URI("../one")); repository.addChild(new URI("../two")); @@ -883,8 +890,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { // query the number of artifacts List children = repository.getChildren(); assertEquals("2.0", 2, children.size()); - IArtifactKey[] keys = repository.getArtifactKeys(); - assertEquals("2.1", 2, keys.length); + assertEquals("2.1", 2, getArtifactKeyCount(repository)); // ensure the child URIs are stored as relative CompositeRepositoryState state = repository.toState(); @@ -903,7 +909,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { URI location = new URI("memory:/in/memory"); URI one = new URI("one"); URI two = new URI("two"); - CompositeArtifactRepository repository = new CompositeArtifactRepository(location, "in memory test", null); + CompositeArtifactRepository repository = createRepository(location, "in memory test"); repository.addChild(one); repository.addChild(two); List children = repository.getChildren(); @@ -930,7 +936,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { destination = new File(getTempFolder(), getUniqueString()); out = new FileOutputStream(destination); - CompositeArtifactRepository repository = new CompositeArtifactRepository(new URI("memory:/in/memory"), "in memory test", null); + CompositeArtifactRepository repository = createRepository(new URI("memory:/in/memory"), "in memory test"); IArtifactRepository childOne = getArtifactRepositoryManager().loadRepository(childLocation, null); TestArtifactRepository childTwo = new TestArtifactRepository(new URI("memory:/in/memory/two")); @@ -940,7 +946,7 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { repository.addChild(childOne.getLocation()); repository.addChild(childTwo.getLocation()); - IArtifactDescriptor descriptor = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "missingSize.asdf", new Version("1.5.1.v200803061910"))); + IArtifactDescriptor descriptor = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "missingSize.asdf", Version.create("1.5.1.v200803061910"))); IStatus status = repository.getArtifact(descriptor, out, new NullProgressMonitor()); // We should have a failure @@ -996,11 +1002,11 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { IArtifactRepository destination = null; BadMirrorSite child = null; CompositeArtifactRepository source = null; - IArtifactDescriptor descriptor = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "missingSize.asdf", new Version("1.5.1.v200803061910"))); + IArtifactDescriptor descriptor = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "missingSize.asdf", Version.create("1.5.1.v200803061910"))); try { destination = super.createArtifactRepository(getTempFolder().toURI(), null); child = new BadMirrorSite(new URI("memory:/in/memory/child")); - source = new CompositeArtifactRepository(new URI("memory:/in/memory/source"), "in memory test", null); + source = createRepository(new URI("memory:/in/memory/source"), "in memory test"); source.addChild(child.getLocation()); // Create mirror request @@ -1026,6 +1032,12 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { } } + protected CompositeArtifactRepository createRepository(URI location, String name) { + CompositeArtifactRepositoryFactory factory = new CompositeArtifactRepositoryFactory(); + factory.setAgent(getAgent()); + return (CompositeArtifactRepository) factory.create(location, name, CompositeArtifactRepository.REPOSITORY_TYPE, null); + } + /* * Test a child returning different bytes */ @@ -1066,8 +1078,8 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { destination = new File(getTempFolder(), getUniqueString()); out = new FileOutputStream(destination); - source = new CompositeArtifactRepository(new URI("memory:/in/memory"), "in memory test", null); - IArtifactDescriptor descriptor = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "missingSize.asdf", new Version("1.5.1.v200803061910"))); + source = createRepository(new URI("memory:/in/memory"), "in memory test"); + IArtifactDescriptor descriptor = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "missingSize.asdf", Version.create("1.5.1.v200803061910"))); // Create 'bad' child which returns an error in transfer childOne = new BadSite(new URI("memory:/in/memory/one")); @@ -1125,8 +1137,8 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { IArtifactRepository childOne = null; IArtifactRepository childTwo = null; try { - IArtifactDescriptor desc = new ArtifactDescriptor(new ArtifactKey("osgi", "a", new Version("1.0.0"))); - source = new CompositeArtifactRepository(new URI("memory:/in/memory"), "in memory test", null); + IArtifactDescriptor desc = new ArtifactDescriptor(new ArtifactKey("osgi", "a", Version.create("1.0.0"))); + source = createRepository(new URI("memory:/in/memory"), "in memory test"); childOne = createChild(); source.addChild(childOne.getLocation()); @@ -1161,8 +1173,8 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { IArtifactRepository childOne = null; IArtifactRepository childTwo = null; try { - IArtifactKey desc = new ArtifactKey("osgi", "a", new Version("1.0.0")); - source = new CompositeArtifactRepository(new URI("memory:/in/memory"), "in memory test", null); + IArtifactKey desc = new ArtifactKey("osgi", "a", Version.create("1.0.0")); + source = createRepository(new URI("memory:/in/memory"), "in memory test"); childOne = createChild(); source.addChild(childOne.getLocation()); @@ -1198,22 +1210,22 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { IArtifactRepository childTwo = null; try { - source = new CompositeArtifactRepository(new URI("memory:/in/memory"), "in memory test", null); - IArtifactKey key = new ArtifactKey("classifier", "name", new Version("1.0.0")); + source = createRepository(new URI("memory:/in/memory"), "in memory test"); + IArtifactKey key = new ArtifactKey("classifier", "name", Version.create("1.0.0")); childOne = createChild(); ((TestArtifactRepository) childOne).addArtifact(key, new byte[] {}); source.addChild(childOne.getLocation()); - assertTrue("Composite repo does not contain key", Arrays.asList(source.getArtifactKeys()).contains(key)); + assertTrue("Composite repo does not contain key", source.contains(key)); markBad(source, childOne); - assertFalse("Composite repo contains key but child is marked bad", Arrays.asList(source.getArtifactKeys()).contains(key)); + assertFalse("Composite repo contains key but child is marked bad", source.contains(key)); childTwo = createChild(); ((TestArtifactRepository) childTwo).addArtifact(key, new byte[] {}); source.addChild(childTwo.getLocation()); - assertTrue("Composite repo does not contain key, but it is available", Arrays.asList(source.getArtifactKeys()).contains(key)); + assertTrue("Composite repo does not contain key, but it is available", source.contains(key)); } catch (Exception e) { fail(e.getMessage(), e); } finally { @@ -1235,8 +1247,8 @@ public class CompositeArtifactRepositoryTest extends AbstractProvisioningTest { IArtifactRepository childTwo = null; try { - source = new CompositeArtifactRepository(new URI("memory:/in/memory"), "in memory test", null); - IArtifactKey key = new ArtifactKey("classifier", "name", new Version("1.0.0")); + source = createRepository(new URI("memory:/in/memory"), "in memory test"); + IArtifactKey key = new ArtifactKey("classifier", "name", Version.create("1.0.0")); IArtifactDescriptor desc = new ArtifactDescriptor(key); childOne = createChild(); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/CorruptedJar.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/CorruptedJar.java index b842f6242..cc5c9d171 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/CorruptedJar.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/CorruptedJar.java @@ -15,9 +15,9 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.artifact.repository.MirrorRequest; import org.eclipse.equinox.internal.p2.engine.DownloadManager; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class CorruptedJar extends AbstractProvisioningTest { @@ -45,8 +45,9 @@ public class CorruptedJar extends AbstractProvisioningTest { public void testDownloadCorruptedJar() { ProvisioningContext ctx = new ProvisioningContext(); ctx.setArtifactRepositories(new URI[] {getTestData("CorruptedJar repo", testDataLocation).toURI()}); - DownloadManager mgr = new DownloadManager(ctx); - mgr.add(new MirrorRequest(source.getArtifactKeys()[0], target, null, null)); + DownloadManager mgr = new DownloadManager(ctx, getArtifactRepositoryManager()); + IArtifactKey key = (IArtifactKey) source.query(ArtifactKeyQuery.ALL_KEYS, null).iterator().next(); + mgr.add(new MirrorRequest(key, target, null, null)); IStatus s = mgr.start(new NullProgressMonitor()); assertNotOK(s); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/FoldersRepositoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/FoldersRepositoryTest.java index 5e822f3c3..c96ce06db 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/FoldersRepositoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/FoldersRepositoryTest.java @@ -10,16 +10,19 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import java.io.FileFilter; import java.net.URL; +import java.util.Iterator; import junit.framework.TestCase; import org.eclipse.core.runtime.FileLocator; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.ServiceReference; @@ -39,7 +42,7 @@ public class FoldersRepositoryTest extends TestCase { } protected void setUp() throws Exception { - managerRef = TestActivator.getContext().getServiceReference(IArtifactRepositoryManager.class.getName()); + managerRef = TestActivator.getContext().getServiceReference(IArtifactRepositoryManager.SERVICE_NAME); manager = (IArtifactRepositoryManager) TestActivator.getContext().getService(managerRef); } @@ -81,19 +84,22 @@ public class FoldersRepositoryTest extends TestCase { String identifier = fileName.substring(0, fileName.indexOf('_')); String version = fileName.substring(fileName.indexOf('_') + 1); - ArtifactKey key = new ArtifactKey("osgi.bundle", identifier, new Version(version)); + ArtifactKey key = new ArtifactKey("osgi.bundle", identifier, Version.create(version)); ArtifactDescriptor descriptor = new ArtifactDescriptor(key); if (file.isDirectory()) descriptor.setProperty("artifact.folder", "true"); repo.addDescriptor(descriptor); } - IArtifactKey[] keys = repo.getArtifactKeys(); - assertEquals(2, keys.length); - for (int i = 0; i < keys.length; i++) { - repo.removeDescriptor(keys[i]); + IQueryResult keys = repo.query(ArtifactKeyQuery.ALL_KEYS, null); + assertEquals(2, AbstractProvisioningTest.queryResultSize(keys)); + for (Iterator iterator = keys.iterator(); iterator.hasNext();) { + IArtifactKey key = (IArtifactKey) iterator.next(); + repo.removeDescriptor(key); } - assertEquals(0, repo.getArtifactKeys().length); + + keys = repo.query(ArtifactKeyQuery.ALL_KEYS, null); + assertTrue(keys.isEmpty()); assertEquals(0, pluginsFolder.listFiles(filter).length); manager.removeRepository(repo.getLocation()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/JarURLArtifactRepositoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/JarURLArtifactRepositoryTest.java index e180583d9..99932a704 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/JarURLArtifactRepositoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/JarURLArtifactRepositoryTest.java @@ -10,15 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.net.*; import junit.framework.TestCase; import org.eclipse.core.runtime.URIUtil; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.ServiceReference; @@ -36,7 +36,7 @@ public class JarURLArtifactRepositoryTest extends TestCase { } protected void setUp() throws Exception { - managerRef = TestActivator.getContext().getServiceReference(IArtifactRepositoryManager.class.getName()); + managerRef = TestActivator.getContext().getServiceReference(IArtifactRepositoryManager.SERVICE_NAME); manager = (IArtifactRepositoryManager) TestActivator.getContext().getService(managerRef); } @@ -56,6 +56,6 @@ public class JarURLArtifactRepositoryTest extends TestCase { fail(e.getMessage()); } IArtifactRepository repo = manager.loadRepository(jarRepoLocation, null); - assertTrue(repo.contains(new ArtifactKey("osgi.bundle", "testdata", new Version("1.0.0.1")))); + assertTrue(repo.contains(new ArtifactKey("osgi.bundle", "testdata", Version.create("1.0.0.1")))); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/MD5Tests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/MD5Tests.java index 884fa123f..04e2db056 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/MD5Tests.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/MD5Tests.java @@ -10,16 +10,18 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.ByteArrayOutputStream; import java.io.File; +import java.util.Iterator; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MD5Tests extends AbstractProvisioningTest { @@ -34,25 +36,23 @@ public class MD5Tests extends AbstractProvisioningTest { } public void testCheckMD5() { - IArtifactKey[] keys = repo.getArtifactKeys(); - for (int i = 0; i < keys.length; i++) { - IArtifactDescriptor[] desc = repo.getArtifactDescriptors(keys[i]); - for (int j = 0; j < desc.length; j++) { - IStatus status = repo.getArtifact(desc[j], new ByteArrayOutputStream(500), new NullProgressMonitor()); - //All artifacts that are expected to fail MD5 check are those whose id starts with bogus - if (desc[j].getArtifactKey().getId().startsWith("bogus")) { - assertNotOK(status); - continue; - } - assertOK("2.1 " + desc[j], status); + IQueryResult descriptors = repo.descriptorQueryable().query(ArtifactDescriptorQuery.ALL_DESCRIPTORS, null); + for (Iterator iterator = descriptors.iterator(); iterator.hasNext();) { + IArtifactDescriptor desc = iterator.next(); + IStatus status = repo.getArtifact(desc, new ByteArrayOutputStream(500), new NullProgressMonitor()); + //All artifacts that are expected to fail MD5 check are those whose id starts with bogus + if (desc.getArtifactKey().getId().startsWith("bogus")) { + assertNotOK(status); + continue; } + assertOK("2.1 " + desc, status); } } public void testBug249035_ArtifactIdentity() { //MD5 sum should not affect the identity of the artifact - ArtifactDescriptor descriptor = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "aaPlugin", new Version("1.0.0"))); + ArtifactDescriptor descriptor = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "aaPlugin", Version.create("1.0.0"))); descriptor.setProperty(IArtifactDescriptor.DOWNLOAD_MD5, "42"); try { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/MirrorRequestTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/MirrorRequestTest.java index 6c6bef325..f7e7b8017 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/MirrorRequestTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/MirrorRequestTest.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.*; import java.lang.reflect.Field; @@ -24,12 +24,13 @@ import org.eclipse.equinox.internal.p2.artifact.repository.MirrorRequest; import org.eclipse.equinox.internal.p2.artifact.repository.MirrorSelector; import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.AbstractArtifactRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.repository.AbstractRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.AbstractArtifactRepository; +import org.eclipse.equinox.p2.repository.spi.AbstractRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.AbstractWrappedArtifactRepository; import org.w3c.dom.*; @@ -66,7 +67,7 @@ public class MirrorRequestTest extends AbstractProvisioningTest { public void testInvalidZipFileInTheSource() { IArtifactKey key = new ArtifactKey("org.eclipse.update.feature", "HelloWorldFeature", Version.createOSGi(1, 0, 0)); - Properties targetProperties = new Properties(); + Map targetProperties = new HashMap(); targetProperties.put("artifact.folder", "true"); MirrorRequest request = new MirrorRequest(key, targetRepository, null, targetProperties); request.setSourceRepository(sourceRepository); @@ -79,7 +80,7 @@ public class MirrorRequestTest extends AbstractProvisioningTest { public void testMissingArtifact() { IArtifactKey key = new ArtifactKey("org.eclipse.update.feature", "Missing", Version.createOSGi(1, 0, 0)); - Properties targetProperties = new Properties(); + Map targetProperties = new HashMap(); targetProperties.put("artifact.folder", "true"); MirrorRequest request = new MirrorRequest(key, targetRepository, null, targetProperties); request.setSourceRepository(sourceRepository); @@ -134,10 +135,11 @@ public class MirrorRequestTest extends AbstractProvisioningTest { // Set status sequence, actual Statuses added later source.setSequence(seq); // Grab an ArtifactKey to mirror, doesn't matter which - IArtifactKey[] keys = source.getArtifactKeys(); - assertTrue("Unable to obtain artifact keys", keys != null && keys.length > 0); + IQueryResult keys = source.query(ArtifactKeyQuery.ALL_KEYS, null); + assertTrue("Unable to obtain artifact keys", keys != null && !keys.isEmpty()); - MirrorRequest req = new MirrorRequest(keys[0], targetRepository, null, null); + IArtifactKey key = (IArtifactKey) keys.iterator().next(); + MirrorRequest req = new MirrorRequest(key, targetRepository, null, null); req.setSourceRepository(source); // Set Status sequence seq.add(new Status(IStatus.ERROR, "Activator", "Message")); @@ -147,9 +149,9 @@ public class MirrorRequestTest extends AbstractProvisioningTest { assertEquals("Expected WARNING status", IStatus.WARNING, req.getResult().getSeverity()); // Remove key from repo so the same one can be used - targetRepository.removeDescriptor(keys[0]); + targetRepository.removeDescriptor(key); // Set Status sequence - req = new MirrorRequest(keys[0], targetRepository, null, null); + req = new MirrorRequest(key, targetRepository, null, null); req.setSourceRepository(source); seq.add(new Status(IStatus.WARNING, "Activator", "Message")); seq.add(new Status(IStatus.INFO, "Activator", "Message")); @@ -158,9 +160,9 @@ public class MirrorRequestTest extends AbstractProvisioningTest { assertEquals("Expected INFO status", IStatus.INFO, req.getResult().getSeverity()); // Remove key from repo so the same one can be used - targetRepository.removeDescriptor(keys[0]); + targetRepository.removeDescriptor(key); // Set Status sequence - req = new MirrorRequest(keys[0], targetRepository, null, null); + req = new MirrorRequest(key, targetRepository, null, null); req.setSourceRepository(source); seq.add(new Status(IStatus.INFO, "Activator", "Message")); req.perform(new NullProgressMonitor()); @@ -289,10 +291,6 @@ public class MirrorRequestTest extends AbstractProvisioningTest { return delegate.getArtifactDescriptors(key); } - public IArtifactKey[] getArtifactKeys() { - return delegate.getArtifactKeys(); - } - public IStatus getArtifacts(IArtifactRequest[] requests, IProgressMonitor monitor) { return delegate.getArtifacts(requests, monitor); } @@ -304,6 +302,14 @@ public class MirrorRequestTest extends AbstractProvisioningTest { public IStatus getRawArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) { return delegate.getRawArtifact(descriptor, destination, monitor); } + + public IQueryable descriptorQueryable() { + return delegate.descriptorQueryable(); + } + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return delegate.query(query, monitor); + } } /* diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/SimpleArtifactRepositoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/SimpleArtifactRepositoryTest.java index c0173b5c9..ad1d357d1 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/SimpleArtifactRepositoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/SimpleArtifactRepositoryTest.java @@ -12,23 +12,28 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.artifact.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.io.*; import java.net.URI; import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map; +import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository; +import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepositoryFactory; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.SimpleArtifactRepositoryFactory; +import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; +import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepHandler; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; @@ -80,7 +85,7 @@ public class SimpleArtifactRepositoryTest extends AbstractProvisioningTest { assertEquals(base, SimpleArtifactRepository.getActualLocation(base, true)); } - public void testCompressedRepository() throws URISyntaxException, ProvisionException { + public void testCompressedRepository() throws ProvisionException { IArtifactRepositoryManager artifactRepositoryManager = getArtifactRepositoryManager(); String tempDir = System.getProperty("java.io.tmpdir"); repositoryFile = new File(tempDir, "SimpleArtifactRepositoryTest"); @@ -90,7 +95,7 @@ public class SimpleArtifactRepositoryTest extends AbstractProvisioningTest { properties.put(IRepository.PROP_COMPRESSED, "true"); IArtifactRepository repo = artifactRepositoryManager.createRepository(repositoryURI, "artifact name", IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); - IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); IArtifactDescriptor descriptor = PublisherHelper.createArtifactDescriptor(key, null); repo.addDescriptor(descriptor); @@ -113,7 +118,7 @@ public class SimpleArtifactRepositoryTest extends AbstractProvisioningTest { fail("Repository should not create artifact.xml"); } - public void testUncompressedRepository() throws URISyntaxException, ProvisionException { + public void testUncompressedRepository() throws ProvisionException { IArtifactRepositoryManager artifactRepositoryManager = getArtifactRepositoryManager(); String tempDir = System.getProperty("java.io.tmpdir"); repositoryFile = new File(tempDir, "SimpleArtifactRepositoryTest"); @@ -123,7 +128,7 @@ public class SimpleArtifactRepositoryTest extends AbstractProvisioningTest { properties.put(IRepository.PROP_COMPRESSED, "false"); IArtifactRepository repo = artifactRepositoryManager.createRepository(repositoryURI, "artifact name", IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); - IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey key = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); IArtifactDescriptor descriptor = PublisherHelper.createArtifactDescriptor(key, null); repo.addDescriptor(descriptor); @@ -158,6 +163,7 @@ public class SimpleArtifactRepositoryTest extends AbstractProvisioningTest { public void test_248772() { SimpleArtifactRepositoryFactory factory = new SimpleArtifactRepositoryFactory(); + factory.setAgent(getAgent()); URI location = null; location = new File(getTempFolder(), getUniqueString()).toURI(); factory.create(location, "test type", null, null); @@ -193,7 +199,7 @@ public class SimpleArtifactRepositoryTest extends AbstractProvisioningTest { } catch (ProvisionException e) { fail("Failed to create repository", e); } - IArtifactDescriptor descriptor = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "aaPlugin", new Version("1.0.0"))); + IArtifactDescriptor descriptor = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "aaPlugin", Version.create("1.0.0"))); OutputStream out = null; try { @@ -247,8 +253,8 @@ public class SimpleArtifactRepositoryTest extends AbstractProvisioningTest { // Create a descriptor for a packed repo ArtifactDescriptor descriptor = new ArtifactDescriptor(new ArtifactKey("org.eclipse.update.feature", "test", Version.parseVersion("1.0.0"))); - descriptor.setProperty(IArtifactDescriptor.FORMAT, "packed"); - descriptor.setProcessingSteps(new ProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}); + descriptor.setProperty(IArtifactDescriptor.FORMAT, IArtifactDescriptor.FORMAT_PACKED); + descriptor.setProcessingSteps(new IProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}); // Create repository Map properties = new HashMap(); @@ -262,4 +268,115 @@ public class SimpleArtifactRepositoryTest extends AbstractProvisioningTest { fail("Test failed", e); } } + + private static class TestDescriptor implements IArtifactDescriptor { + private static final IProcessingStepDescriptor[] steps = new IProcessingStepDescriptor[0]; + private IArtifactKey artifactKey; + private Properties properties = new Properties(); + + public TestDescriptor(IArtifactKey key) { + this.artifactKey = key; + } + + public IArtifactKey getArtifactKey() { + return artifactKey; + } + + public IProcessingStepDescriptor[] getProcessingSteps() { + return steps; + } + + public Map getProperties() { + return properties; + } + + public String getProperty(String key) { + return properties.getProperty(key); + } + + public IArtifactRepository getRepository() { + return null; + } + + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof IArtifactDescriptor)) + return false; + + IArtifactDescriptor other = (IArtifactDescriptor) obj; + if (!artifactKey.equals(other.getArtifactKey())) + return false; + + if (!Arrays.equals(steps, other.getProcessingSteps())) + return false; + + String format = getProperty(FORMAT); + String otherFormat = other.getProperty(FORMAT); + if (format != null ? !format.equals(otherFormat) : otherFormat != null) + return false; + + return true; + } + + public int hashCode() { + String format = getProperty(FORMAT); + + final int prime = 31; + int result = 1; + result = prime * result + ((artifactKey == null) ? 0 : artifactKey.hashCode()); + result = prime * result + Arrays.asList(steps).hashCode(); + result = prime * result + (format != null ? format.hashCode() : 0); + return result; + } + } + + public void testAddContains() throws Exception { + File folder = getTestFolder("simple_AddContains"); + repositoryURI = folder.toURI(); + + Map properties = new HashMap(); + SimpleArtifactRepository repo = (SimpleArtifactRepository) getArtifactRepositoryManager().createRepository(repositoryURI, "My Repo", IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); + + TestDescriptor descriptor = new TestDescriptor(new ArtifactKey("osgi.bundle", "aaPlugin", Version.create("1.0.0"))); + OutputStream stream = repo.getOutputStream(descriptor); + stream.write("I am an artifact\n".getBytes()); + stream.close(); + + assertTrue(repo.contains(descriptor)); + + assertTrue(repo.contains(new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "aaPlugin", Version.create("1.0.0"))))); + + } + + public void testQuery() throws Exception { + File folder = getTestFolder("ArtifactRepository_testQuery"); + repositoryURI = folder.toURI(); + + IArtifactRepository repo = getArtifactRepositoryManager().createRepository(repositoryURI, "test", IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, new HashMap()); + + ArtifactDescriptor d1 = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "a", Version.create("1.0.0"))); + ArtifactDescriptor d2 = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "a", Version.create("2.0.0"))); + ArtifactDescriptor d3 = new ArtifactDescriptor(new ArtifactKey("osgi.bundle", "a", Version.create("2.0.0"))); + d3.setProperty(IArtifactDescriptor.FORMAT, IArtifactDescriptor.FORMAT_PACKED); + + repo.addDescriptor(d1); + repo.addDescriptor(d2); + repo.addDescriptor(d3); + + IQueryable descQueryable = repo.descriptorQueryable(); + IQueryResult result = descQueryable.query(new ArtifactDescriptorQuery("a", null, null), null); + assertEquals(3, queryResultSize(result)); + + result = descQueryable.query(new ArtifactDescriptorQuery(null, new VersionRange("[2.0.0, 3.0.0)"), null), null); + assertEquals(2, queryResultSize(result)); + assertNotContains(result, d1); + + result = descQueryable.query(new ArtifactDescriptorQuery(null, null, IArtifactDescriptor.FORMAT_PACKED), null); + assertEquals(1, queryResultSize(result)); + IArtifactDescriptor resultDescriptor = result.iterator().next(); + assertEquals(d3.getArtifactKey(), resultDescriptor.getArtifactKey()); + } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/Adder.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/Adder.java index 845d33de0..c3394503b 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/Adder.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/Adder.java @@ -15,9 +15,9 @@ import java.io.IOException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.artifact.repository.Activator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; public class Adder extends ProcessingStep { @@ -32,7 +32,7 @@ public class Adder extends ProcessingStep { this.operand = operand; } - public void initialize(ProcessingStepDescriptor descriptor, IArtifactDescriptor context) { + public void initialize(IProcessingStepDescriptor descriptor, IArtifactDescriptor context) { super.initialize(descriptor, context); try { operand = Integer.valueOf(descriptor.getData()).intValue(); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/ByteShifter.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/ByteShifter.java index 38c6fbeb7..507d9283a 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/ByteShifter.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/ByteShifter.java @@ -15,9 +15,9 @@ import java.io.IOException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.artifact.repository.Activator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; public class ByteShifter extends ProcessingStep { @@ -33,7 +33,7 @@ public class ByteShifter extends ProcessingStep { basicInitialize(null); } - private void basicInitialize(ProcessingStepDescriptor descriptor) { + private void basicInitialize(IProcessingStepDescriptor descriptor) { // if the status is already set to something that not ok, we've already found a problem. if (!getStatus().isOK()) return; @@ -51,7 +51,7 @@ public class ByteShifter extends ProcessingStep { setStatus(new Status(code, Activator.ID, "ByteShifter operand invalid: " + operand)); } - public void initialize(ProcessingStepDescriptor descriptor, IArtifactDescriptor context) { + public void initialize(IProcessingStepDescriptor descriptor, IArtifactDescriptor context) { super.initialize(descriptor, context); try { operand = Integer.valueOf(descriptor.getData()).intValue(); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/Counter.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/Counter.java index 008b05370..0a033464e 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/Counter.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/Counter.java @@ -14,9 +14,9 @@ import java.io.IOException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.artifact.repository.Activator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; public class Counter extends ProcessingStep { @@ -33,7 +33,7 @@ public class Counter extends ProcessingStep { basicInitialize(null); } - private void basicInitialize(ProcessingStepDescriptor descriptor) { + private void basicInitialize(IProcessingStepDescriptor descriptor) { // if the status is already set to something that not ok, we've already found a problem. if (!getStatus().isOK()) return; @@ -51,7 +51,7 @@ public class Counter extends ProcessingStep { setStatus(new Status(code, Activator.ID, "Counter size not set")); } - public void initialize(ProcessingStepDescriptor descriptor, IArtifactDescriptor context) { + public void initialize(IProcessingStepDescriptor descriptor, IArtifactDescriptor context) { super.initialize(descriptor, context); String data = descriptor.getData(); if (data == null) diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/Multiplier.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/Multiplier.java index 4b090422a..feb98171c 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/Multiplier.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/Multiplier.java @@ -15,9 +15,9 @@ import java.io.IOException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.artifact.repository.Activator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; public class Multiplier extends ProcessingStep { @@ -32,7 +32,7 @@ public class Multiplier extends ProcessingStep { this.operand = operand; } - public void initialize(ProcessingStepDescriptor descriptor, IArtifactDescriptor context) { + public void initialize(IProcessingStepDescriptor descriptor, IArtifactDescriptor context) { super.initialize(descriptor, context); try { operand = Integer.valueOf(descriptor.getData()).intValue(); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/ProcessingStepHandlerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/ProcessingStepHandlerTest.java index c3862a5a0..d22e509fc 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/ProcessingStepHandlerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/artifact/repository/processing/ProcessingStepHandlerTest.java @@ -18,7 +18,10 @@ import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.artifact.processors.pack200.Pack200ProcessorStep; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; import org.eclipse.equinox.internal.p2.jarprocessor.PackStep; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.*; +import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep; +import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepHandler; +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; import org.eclipse.equinox.p2.tests.TestActivator; public class ProcessingStepHandlerTest extends TestCase { @@ -29,7 +32,7 @@ public class ProcessingStepHandlerTest extends TestCase { IProgressMonitor monitor = new NullProgressMonitor(); public void testExecuteNoPSs() throws IOException { - ProcessingStepDescriptor[] descriptors = new ProcessingStepDescriptor[0]; + IProcessingStepDescriptor[] descriptors = new IProcessingStepDescriptor[0]; OutputStream result = new ByteArrayOutputStream(10); OutputStream testStream = handler.createAndLink(descriptors, null, result, monitor); testStream.write("Test".getBytes()); @@ -125,7 +128,7 @@ public class ProcessingStepHandlerTest extends TestCase { //this test is only applicable if pack200 is available if (!PackStep.canPack()) return; - ProcessingStepDescriptor[] descriptors = new ProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; + IProcessingStepDescriptor[] descriptors = new IProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; ProcessingStep[] steps = handler.create(descriptors, null); ByteArrayOutputStream result = new ByteArrayOutputStream(100000); OutputStream testStream = handler.link(steps, result, monitor); @@ -137,7 +140,7 @@ public class ProcessingStepHandlerTest extends TestCase { } public void testCreateByteShifterPS() { - ProcessingStepDescriptor[] descriptors = new ProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.ByteShifter", "1", true)}; + IProcessingStepDescriptor[] descriptors = new IProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.ByteShifter", "1", true)}; ProcessingStep[] steps = handler.create(descriptors, null); assertNotNull(steps); assertEquals(1, steps.length); @@ -153,7 +156,7 @@ public class ProcessingStepHandlerTest extends TestCase { // } public void testCreateAdderPS() { - ProcessingStepDescriptor[] descriptors = new ProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Adder", "1", true)}; + IProcessingStepDescriptor[] descriptors = new IProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Adder", "1", true)}; ProcessingStep[] steps = handler.create(descriptors, null); assertNotNull(steps); assertEquals(1, steps.length); @@ -161,7 +164,7 @@ public class ProcessingStepHandlerTest extends TestCase { } public void testCreateMultiplierPS() { - ProcessingStepDescriptor[] descriptors = new ProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Multiplier", "2", true)}; + IProcessingStepDescriptor[] descriptors = new IProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Multiplier", "2", true)}; ProcessingStep[] steps = handler.create(descriptors, null); assertNotNull(steps); assertEquals(1, steps.length); @@ -169,7 +172,7 @@ public class ProcessingStepHandlerTest extends TestCase { } public void testCreatePack200UnpackerPS() { - ProcessingStepDescriptor[] descriptors = new ProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; + IProcessingStepDescriptor[] descriptors = new IProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; ProcessingStep[] steps = handler.create(descriptors, null); assertNotNull(steps); assertEquals(1, steps.length); @@ -177,9 +180,9 @@ public class ProcessingStepHandlerTest extends TestCase { } public void testCreatePSsAndAssureOrderingOfPSs1() throws IOException { - ProcessingStepDescriptor adder = new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Adder", "1", true); - ProcessingStepDescriptor multiplier = new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Multiplier", "2", true); - ProcessingStepDescriptor[] descriptors = new ProcessingStepDescriptor[] {adder, multiplier}; + IProcessingStepDescriptor adder = new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Adder", "1", true); + IProcessingStepDescriptor multiplier = new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Multiplier", "2", true); + IProcessingStepDescriptor[] descriptors = new IProcessingStepDescriptor[] {adder, multiplier}; ProcessingStep[] steps = handler.create(descriptors, null); ByteArrayOutputStream result = new ByteArrayOutputStream(10); OutputStream testStream = handler.link(steps, result, monitor); @@ -189,9 +192,9 @@ public class ProcessingStepHandlerTest extends TestCase { } public void testCreatePSsAndAssureOrderingOfPSs2() throws IOException { - ProcessingStepDescriptor adder = new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Adder", "1", true); - ProcessingStepDescriptor multiplier = new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Multiplier", "2", true); - ProcessingStepDescriptor[] descriptors = new ProcessingStepDescriptor[] {multiplier, adder}; + IProcessingStepDescriptor adder = new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Adder", "1", true); + IProcessingStepDescriptor multiplier = new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Multiplier", "2", true); + IProcessingStepDescriptor[] descriptors = new IProcessingStepDescriptor[] {multiplier, adder}; ProcessingStep[] steps = handler.create(descriptors, null); ByteArrayOutputStream result = new ByteArrayOutputStream(10); OutputStream testStream = handler.link(steps, result, monitor); @@ -201,9 +204,9 @@ public class ProcessingStepHandlerTest extends TestCase { } public void testLinkPSs() throws IOException { - ProcessingStepDescriptor adder = new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Adder", "1", true); - ProcessingStepDescriptor multiplier = new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Multiplier", "2", true); - ProcessingStepDescriptor[] descriptors = new ProcessingStepDescriptor[] {adder, multiplier}; + IProcessingStepDescriptor adder = new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Adder", "1", true); + IProcessingStepDescriptor multiplier = new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Multiplier", "2", true); + IProcessingStepDescriptor[] descriptors = new IProcessingStepDescriptor[] {adder, multiplier}; ByteArrayOutputStream result = new ByteArrayOutputStream(10); OutputStream testStream = handler.createAndLink(descriptors, null, result, monitor); testStream.write(new byte[] {1, 2, 3, 4, 5}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/AggregateQueryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/AggregateQueryTest.java index ddf8fca34..bea6a9cdc 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/AggregateQueryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/AggregateQueryTest.java @@ -11,7 +11,8 @@ package org.eclipse.equinox.p2.tests.core; import java.util.*; import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** * This tests both Compound and Composite queries @@ -28,16 +29,17 @@ public class AggregateQueryTest extends TestCase { } public void testEmptyCompositeQuery() { - CompositeQuery query = new CompositeQuery(new Query[0]); - query.perform(getABCDE().iterator(), new Collector()); + PipedQuery query = new PipedQuery(new IQuery[0]); + query.perform(getABCDE().iterator()); // We should not throw an exception. No guarantee on what perform // will return in this case } public void testSymmetry() { - Query getLatest = new ContextQuery() { + IQuery getLatest = new ContextQuery() { - public Collector perform(Iterator iterator, Collector result) { + public Collector perform(Iterator iterator) { + Collector result = new Collector(); List list = new ArrayList(); while (iterator.hasNext()) { list.add(iterator.next()); @@ -48,9 +50,10 @@ public class AggregateQueryTest extends TestCase { } }; - Query getAllBut3 = new ContextQuery() { + IQuery getAllBut3 = new ContextQuery() { - public Collector perform(Iterator iterator, Collector result) { + public Collector perform(Iterator iterator) { + Collector result = new Collector(); while (iterator.hasNext()) { Object o = iterator.next(); if (!o.equals("3")) @@ -60,21 +63,21 @@ public class AggregateQueryTest extends TestCase { } }; - CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new Query[] {getLatest, getAllBut3}, true); - Collector result = compoundQuery.perform(get123().iterator(), new Collector()); - assertEquals(0, result.size()); + CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new IQuery[] {getLatest, getAllBut3}, true); + IQueryResult result = compoundQuery.perform(get123().iterator()); + assertEquals(0, AbstractProvisioningTest.queryResultSize(result)); - compoundQuery = CompoundQuery.createCompoundQuery(new Query[] {getAllBut3, getLatest}, true); - result = compoundQuery.perform(get123().iterator(), new Collector()); - assertEquals(0, result.size()); + compoundQuery = CompoundQuery.createCompoundQuery(new IQuery[] {getAllBut3, getLatest}, true); + result = compoundQuery.perform(get123().iterator()); + assertEquals(0, AbstractProvisioningTest.queryResultSize(result)); - compoundQuery = CompoundQuery.createCompoundQuery(new Query[] {getLatest, getAllBut3}, false); - result = compoundQuery.perform(get123().iterator(), new Collector()); - assertEquals(3, result.size()); + compoundQuery = CompoundQuery.createCompoundQuery(new IQuery[] {getLatest, getAllBut3}, false); + result = compoundQuery.perform(get123().iterator()); + assertEquals(3, AbstractProvisioningTest.queryResultSize(result)); - compoundQuery = CompoundQuery.createCompoundQuery(new Query[] {getAllBut3, getLatest}, false); - result = compoundQuery.perform(get123().iterator(), new Collector()); - assertEquals(3, result.size()); + compoundQuery = CompoundQuery.createCompoundQuery(new IQuery[] {getAllBut3, getLatest}, false); + result = compoundQuery.perform(get123().iterator()); + assertEquals(3, AbstractProvisioningTest.queryResultSize(result)); } @@ -83,9 +86,10 @@ public class AggregateQueryTest extends TestCase { * This method tests that */ public void testNonSymmetry() { - Query getLatest = new ContextQuery() { + IQuery getLatest = new ContextQuery() { - public Collector perform(Iterator iterator, Collector result) { + public Collector perform(Iterator iterator) { + Collector result = new Collector(); List list = new ArrayList(); while (iterator.hasNext()) { list.add(iterator.next()); @@ -96,9 +100,11 @@ public class AggregateQueryTest extends TestCase { } }; - Query getAllBut3 = new ContextQuery() { + IQuery getAllBut3 = new ContextQuery() { + + public Collector perform(Iterator iterator) { + Collector result = new Collector(); - public Collector perform(Iterator iterator, Collector result) { while (iterator.hasNext()) { Object o = iterator.next(); if (!o.equals("3")) @@ -108,95 +114,95 @@ public class AggregateQueryTest extends TestCase { } }; - CompositeQuery compoundQuery = new CompositeQuery(new Query[] {getLatest, getAllBut3}); - Collector result = compoundQuery.perform(get123().iterator(), new Collector()); - assertEquals(0, result.size()); + PipedQuery compoundQuery = new PipedQuery(getLatest, getAllBut3); + IQueryResult result = compoundQuery.perform(get123().iterator()); + assertEquals(0, AbstractProvisioningTest.queryResultSize(result)); - compoundQuery = new CompositeQuery(new Query[] {getAllBut3, getLatest}); - result = compoundQuery.perform(get123().iterator(), new Collector()); - assertEquals(1, result.size()); - assertEquals("2", result.toCollection().iterator().next()); + compoundQuery = new PipedQuery(getAllBut3, getLatest); + result = compoundQuery.perform(get123().iterator()); + assertEquals(1, AbstractProvisioningTest.queryResultSize(result)); + assertEquals("2", result.iterator().next()); } public void testCompoundAllMatchQueries() { - Query A = new MatchQuery() { + IQuery A = new MatchQuery() { public boolean isMatch(Object candidate) { return false; } }; - Query B = new MatchQuery() { + IQuery B = new MatchQuery() { public boolean isMatch(Object candidate) { return false; } }; - Query C = new MatchQuery() { + IQuery C = new MatchQuery() { public boolean isMatch(Object candidate) { return false; } }; - CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new Query[] {A, B, C}, true); + CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new IQuery[] {A, B, C}, true); assertTrue("1.0", compoundQuery instanceof IMatchQuery); - assertEquals("1.1", 3, compoundQuery.getQueries().length); - assertEquals("1.2", A, compoundQuery.getQueries()[0]); - assertEquals("1.3", B, compoundQuery.getQueries()[1]); - assertEquals("1.4", C, compoundQuery.getQueries()[2]); + assertEquals("1.1", 3, compoundQuery.getQueries().size()); + assertEquals("1.2", A, compoundQuery.getQueries().get(0)); + assertEquals("1.3", B, compoundQuery.getQueries().get(1)); + assertEquals("1.4", C, compoundQuery.getQueries().get(2)); } public void testCompoundSomeMatchQueries() { - Query A = new MatchQuery() { + IQuery A = new MatchQuery() { public boolean isMatch(Object candidate) { return false; } }; - Query B = new ContextQuery() { - public Collector perform(Iterator iterator, Collector result) { + IQuery B = new ContextQuery() { + public Collector perform(Iterator iterator) { // TODO Auto-generated method stub return null; } }; - Query C = new MatchQuery() { + IQuery C = new MatchQuery() { public boolean isMatch(Object candidate) { return false; } }; - CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new Query[] {A, B, C}, true); + CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new IQuery[] {A, B, C}, true); assertTrue("1.0", !(compoundQuery instanceof IMatchQuery)); - assertEquals("1.1", 3, compoundQuery.getQueries().length); - assertEquals("1.2", A, compoundQuery.getQueries()[0]); - assertEquals("1.3", B, compoundQuery.getQueries()[1]); - assertEquals("1.4", C, compoundQuery.getQueries()[2]); + assertEquals("1.1", 3, compoundQuery.getQueries().size()); + assertEquals("1.2", A, compoundQuery.getQueries().get(0)); + assertEquals("1.3", B, compoundQuery.getQueries().get(1)); + assertEquals("1.4", C, compoundQuery.getQueries().get(2)); } public void testCompoundNoMatchQueries() { - Query A = new ContextQuery() { - public Collector perform(Iterator iterator, Collector result) { + IQuery A = new ContextQuery() { + public Collector perform(Iterator iterator) { // TODO Auto-generated method stub return null; } }; - Query B = new ContextQuery() { - public Collector perform(Iterator iterator, Collector result) { + IQuery B = new ContextQuery() { + public Collector perform(Iterator iterator) { // TODO Auto-generated method stub return null; } }; - Query C = new ContextQuery() { - public Collector perform(Iterator iterator, Collector result) { + IQuery C = new ContextQuery() { + public Collector perform(Iterator iterator) { // TODO Auto-generated method stub return null; } }; - CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new Query[] {A, B, C}, true); + CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new IQuery[] {A, B, C}, true); assertTrue("1.0", !(compoundQuery instanceof IMatchQuery)); - assertEquals("1.1", 3, compoundQuery.getQueries().length); - assertEquals("1.2", A, compoundQuery.getQueries()[0]); - assertEquals("1.3", B, compoundQuery.getQueries()[1]); - assertEquals("1.4", C, compoundQuery.getQueries()[2]); + assertEquals("1.1", 3, compoundQuery.getQueries().size()); + assertEquals("1.2", A, compoundQuery.getQueries().get(0)); + assertEquals("1.3", B, compoundQuery.getQueries().get(1)); + assertEquals("1.4", C, compoundQuery.getQueries().get(2)); } public void testIntersection() { - Query ABC = new MatchQuery() { + IQuery ABC = new MatchQuery() { public boolean isMatch(Object candidate) { if (candidate.equals("A") || candidate.equals("B") || candidate.equals("C")) return true; @@ -204,7 +210,7 @@ public class AggregateQueryTest extends TestCase { } }; - Query BCDE = new MatchQuery() { + IQuery BCDE = new MatchQuery() { public boolean isMatch(Object candidate) { if (candidate.equals("B") || candidate.equals("C") || candidate.equals("D") || candidate.equals("E")) return true; @@ -212,16 +218,17 @@ public class AggregateQueryTest extends TestCase { } }; - CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new Query[] {ABC, BCDE}, true); - Collector result = compoundQuery.perform(getABCDE().iterator(), new Collector()); - assertEquals("1.0", result.size(), 2); - assertTrue("1.1", result.toCollection().contains("B")); - assertTrue("1.2", result.toCollection().contains("C")); + CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new IQuery[] {ABC, BCDE}, true); + IQueryResult result = compoundQuery.perform(getABCDE().iterator()); + assertEquals("1.0", AbstractProvisioningTest.queryResultSize(result), 2); + AbstractProvisioningTest.assertContains("1.1", result, "B"); + AbstractProvisioningTest.assertContains("1.2", result, "C"); } public void testIntersection2() { - Query ABC = new ContextQuery() { - public Collector perform(Iterator iterator, Collector result) { + IQuery ABC = new ContextQuery() { + public Collector perform(Iterator iterator) { + Collector result = new Collector(); while (iterator.hasNext()) { Object o = iterator.next(); if (o.equals("A") || o.equals("B") || o.equals("C")) @@ -231,8 +238,9 @@ public class AggregateQueryTest extends TestCase { } }; - Query BCDE = new ContextQuery() { - public Collector perform(Iterator iterator, Collector result) { + IQuery BCDE = new ContextQuery() { + public Collector perform(Iterator iterator) { + Collector result = new Collector(); while (iterator.hasNext()) { Object o = iterator.next(); if (o.equals("B") || o.equals("C") || o.equals("D") || o.equals("E")) @@ -242,15 +250,15 @@ public class AggregateQueryTest extends TestCase { } }; - CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new Query[] {ABC, BCDE}, true); - Collector result = compoundQuery.perform(getABCDE().iterator(), new Collector()); - assertEquals("1.0", result.size(), 2); - assertTrue("1.1", result.toCollection().contains("B")); - assertTrue("1.2", result.toCollection().contains("C")); + CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new IQuery[] {ABC, BCDE}, true); + IQueryResult result = compoundQuery.perform(getABCDE().iterator()); + assertEquals("1.0", AbstractProvisioningTest.queryResultSize(result), 2); + AbstractProvisioningTest.assertContains("1.1", result, "B"); + AbstractProvisioningTest.assertContains("1.2", result, "C"); } public void testUnion() { - Query ABC = new MatchQuery() { + IQuery ABC = new MatchQuery() { public boolean isMatch(Object candidate) { if (candidate.equals("A") || candidate.equals("B") || candidate.equals("C")) return true; @@ -258,7 +266,7 @@ public class AggregateQueryTest extends TestCase { } }; - Query BCDE = new MatchQuery() { + IQuery BCDE = new MatchQuery() { public boolean isMatch(Object candidate) { if (candidate.equals("B") || candidate.equals("C") || candidate.equals("D") || candidate.equals("E")) return true; @@ -266,19 +274,20 @@ public class AggregateQueryTest extends TestCase { } }; - CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new Query[] {ABC, BCDE}, false); - Collector result = compoundQuery.perform(getABCDE().iterator(), new Collector()); - assertEquals("1.0", result.size(), 5); - assertTrue("1.1", result.toCollection().contains("A")); - assertTrue("1.2", result.toCollection().contains("B")); - assertTrue("1.3", result.toCollection().contains("C")); - assertTrue("1.4", result.toCollection().contains("D")); - assertTrue("1.5", result.toCollection().contains("E")); + CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new IQuery[] {ABC, BCDE}, false); + IQueryResult result = compoundQuery.perform(getABCDE().iterator()); + assertEquals("1.0", AbstractProvisioningTest.queryResultSize(result), 5); + AbstractProvisioningTest.assertContains("1.1", result, "A"); + AbstractProvisioningTest.assertContains("1.2", result, "B"); + AbstractProvisioningTest.assertContains("1.3", result, "C"); + AbstractProvisioningTest.assertContains("1.4", result, "D"); + AbstractProvisioningTest.assertContains("1.5", result, "E"); } public void testUnion2() { - Query ABC = new ContextQuery() { - public Collector perform(Iterator iterator, Collector result) { + IQuery ABC = new ContextQuery() { + public Collector perform(Iterator iterator) { + Collector result = new Collector(); while (iterator.hasNext()) { Object o = iterator.next(); if (o.equals("A") || o.equals("B") || o.equals("C")) @@ -288,8 +297,9 @@ public class AggregateQueryTest extends TestCase { } }; - Query BCDE = new ContextQuery() { - public Collector perform(Iterator iterator, Collector result) { + IQuery BCDE = new ContextQuery() { + public Collector perform(Iterator iterator) { + Collector result = new Collector(); while (iterator.hasNext()) { Object o = iterator.next(); if (o.equals("B") || o.equals("C") || o.equals("D") || o.equals("E")) @@ -299,13 +309,13 @@ public class AggregateQueryTest extends TestCase { } }; - CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new Query[] {ABC, BCDE}, false); - Collector result = compoundQuery.perform(getABCDE().iterator(), new Collector()); - assertEquals("1.0", result.size(), 5); - assertTrue("1.1", result.toCollection().contains("A")); - assertTrue("1.2", result.toCollection().contains("B")); - assertTrue("1.3", result.toCollection().contains("C")); - assertTrue("1.4", result.toCollection().contains("D")); - assertTrue("1.5", result.toCollection().contains("E")); + CompoundQuery compoundQuery = CompoundQuery.createCompoundQuery(new IQuery[] {ABC, BCDE}, false); + IQueryResult result = compoundQuery.perform(getABCDE().iterator()); + assertEquals("1.0", AbstractProvisioningTest.queryResultSize(result), 5); + AbstractProvisioningTest.assertContains("1.1", result, "A"); + AbstractProvisioningTest.assertContains("1.2", result, "B"); + AbstractProvisioningTest.assertContains("1.3", result, "C"); + AbstractProvisioningTest.assertContains("1.4", result, "D"); + AbstractProvisioningTest.assertContains("1.5", result, "E"); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/CollectorTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/CollectorTest.java index 7e12817bc..8b2760129 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/CollectorTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/CollectorTest.java @@ -12,7 +12,7 @@ package org.eclipse.equinox.p2.tests.core; import java.util.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.p2.query.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** @@ -47,7 +47,7 @@ public class CollectorTest extends AbstractProvisioningTest { public void testCompositeCollectors() { String[] s = new String[] {"A", "B", "C", "D", "E", "F", "G", "1", "2", "3", "4", "5", "6", "7"}; List list = Arrays.asList(s); - Query numeric = new MatchQuery() { + IQuery numeric = new MatchQuery() { public boolean isMatch(Object candidate) { if (((String) candidate).compareTo("0") > 0 && ((String) candidate).compareTo("8") < 0) { @@ -57,7 +57,7 @@ public class CollectorTest extends AbstractProvisioningTest { } }; - Query fourOrFiveOrABC = new MatchQuery() { + IQuery fourOrFiveOrABC = new MatchQuery() { public boolean isMatch(Object candidate) { if (((String) candidate).equals("4") || ((String) candidate).equals("5") || ((String) candidate).equals("A") || ((String) candidate).equals("B") || ((String) candidate).equals("C")) { return true; @@ -65,20 +65,19 @@ public class CollectorTest extends AbstractProvisioningTest { return false; } }; - Collector collector = numeric.perform(list.iterator(), new Collector()); - assertEquals("1.0", 7, collector.toCollection().size()); - - collector = collector.query(fourOrFiveOrABC, new Collector(), null); - Collection collection = collector.toCollection(); - assertEquals("2.0", 2, collection.size()); - assertTrue("2.1", collection.contains("4")); - assertTrue("2.2", collection.contains("5")); + IQueryResult queryResult = numeric.perform(list.iterator()); + assertEquals("1.0", 7, queryResultSize(queryResult)); + + queryResult = queryResult.query(fourOrFiveOrABC, null); + assertEquals("2.0", 2, queryResultSize(queryResult)); + assertContains("2.1", queryResult, "4"); + assertContains("2.2", queryResult, "5"); } public void testSameCollector() { String[] s = new String[] {"A", "B", "C", "D", "E", "F", "G", "1", "2", "3", "4", "5", "6", "7"}; List list = Arrays.asList(s); - Query numeric = new MatchQuery() { + IQuery numeric = new MatchQuery() { public boolean isMatch(Object candidate) { if (((String) candidate).compareTo("0") > 0 && ((String) candidate).compareTo("8") < 0) { @@ -88,7 +87,7 @@ public class CollectorTest extends AbstractProvisioningTest { } }; - Query fourOrFiveOrABC = new MatchQuery() { + IQuery fourOrFiveOrABC = new MatchQuery() { public boolean isMatch(Object candidate) { if (((String) candidate).equals("4") || ((String) candidate).equals("5") || ((String) candidate).equals("A") || ((String) candidate).equals("B") || ((String) candidate).equals("C")) { return true; @@ -96,11 +95,12 @@ public class CollectorTest extends AbstractProvisioningTest { return false; } }; - Collector collector = numeric.perform(list.iterator(), new Collector()); - assertEquals("1.0", 7, collector.toCollection().size()); + Collector collector = new Collector(); + collector.addAll(numeric.perform(list.iterator())); + assertEquals("1.0", 7, collector.unmodifiableSet().size()); - collector = collector.query(fourOrFiveOrABC, collector, null); - Collection collection = collector.toCollection(); + collector.addAll(collector.query(fourOrFiveOrABC, null)); + Collection collection = collector.unmodifiableSet(); assertEquals("2.0", 7, collection.size()); } @@ -110,7 +110,7 @@ public class CollectorTest extends AbstractProvisioningTest { public void testEmptyCompositeCollectors() { String[] s = new String[] {"A", "B", "C", "D", "E", "F", "G", "1", "2", "3", "4", "5", "6", "7"}; List list = Arrays.asList(s); - Query eightOrNine = new MatchQuery() { + IQuery eightOrNine = new MatchQuery() { public boolean isMatch(Object candidate) { if (((String) candidate).compareTo("8") > 0 && ((String) candidate).compareTo("9") < 0) { @@ -120,7 +120,7 @@ public class CollectorTest extends AbstractProvisioningTest { } }; - Query fourOrFiveOrABC = new MatchQuery() { + IQuery fourOrFiveOrABC = new MatchQuery() { public boolean isMatch(Object candidate) { if (((String) candidate).equals("4") || ((String) candidate).equals("5") || ((String) candidate).equals("A") || ((String) candidate).equals("B") || ((String) candidate).equals("C")) { return true; @@ -128,17 +128,16 @@ public class CollectorTest extends AbstractProvisioningTest { return false; } }; - Collector collector = eightOrNine.perform(list.iterator(), new Collector()); - assertEquals("1.0", 0, collector.toCollection().size()); + IQueryResult queryResult = eightOrNine.perform(list.iterator()); + assertTrue("1.0", queryResult.isEmpty()); - collector = collector.query(fourOrFiveOrABC, new Collector(), null); - Collection collection = collector.toCollection(); - assertEquals("2.0", 0, collection.size()); + queryResult = queryResult.query(fourOrFiveOrABC, null); + assertTrue("2.0", queryResult.isEmpty()); } public void testToCollection() { Collector collector = new Collector(); - Collection result = collector.toCollection(); + Collection result = collector.unmodifiableSet(); assertEquals("1.0", 0, result.size()); //collection should be immutable try { @@ -150,7 +149,7 @@ public class CollectorTest extends AbstractProvisioningTest { String value = "value"; collector.accept(value); - result = collector.toCollection(); + result = collector.unmodifiableSet(); assertEquals("2.0", 1, result.size()); assertEquals("2.1", value, result.iterator().next()); //collection should be immutable diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/CompoundQueryableTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/CompoundQueryableTest.java index 16783c3f7..c05dd804a 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/CompoundQueryableTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/CompoundQueryableTest.java @@ -9,11 +9,13 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.core; -import java.util.*; +import java.util.Arrays; +import java.util.Iterator; import junit.framework.TestCase; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.tests.harness.TestProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** * Tests the compound queryable @@ -56,10 +58,11 @@ public class CompoundQueryableTest extends TestCase { IQueryable queryable1 = new IQueryable() { Integer[] elements = new Integer[] {1, 2, 3, 4, 5}; - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + IQueryResult collector; try { monitor.beginTask("", 10); - collector = query.perform(createIterator(elements), collector); + collector = query.perform(createIterator(elements)); monitor.worked(10); } finally { monitor.done(); @@ -71,10 +74,11 @@ public class CompoundQueryableTest extends TestCase { IQueryable queryable2 = new IQueryable() { Integer[] elements = new Integer[] {4, 6, 8, 10, 12}; - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + IQueryResult collector; try { monitor.beginTask("", 10); - collector = query.perform(createIterator(elements), collector); + collector = query.perform(createIterator(elements)); monitor.worked(10); } finally { monitor.done(); @@ -86,10 +90,11 @@ public class CompoundQueryableTest extends TestCase { IQueryable queryable3 = new IQueryable() { Integer[] elements = new Integer[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + IQueryResult collector; try { monitor.beginTask("", 10); - collector = query.perform(createIterator(elements), collector); + collector = query.perform(createIterator(elements)); monitor.worked(10); } finally { monitor.done(); @@ -98,7 +103,7 @@ public class CompoundQueryableTest extends TestCase { } }; - Query matchQuery = new MatchQuery() { + IQuery matchQuery = new MatchQuery() { public boolean isMatch(Object candidate) { if (candidate instanceof Integer) { @@ -110,7 +115,7 @@ public class CompoundQueryableTest extends TestCase { } }; - Query matchMod4query = new MatchQuery() { + IQuery matchMod4query = new MatchQuery() { public boolean isMatch(Object candidate) { if (candidate instanceof Integer) { int x = ((Integer) candidate).intValue(); @@ -121,9 +126,10 @@ public class CompoundQueryableTest extends TestCase { } }; - Query contextQuery = new ContextQuery() { + IQuery contextQuery = new ContextQuery() { - public Collector perform(Iterator iterator, Collector result) { + public Collector perform(Iterator iterator) { + Collector result = new Collector(); while (iterator.hasNext()) { Object o = iterator.next(); if (o instanceof Integer && ((Integer) o).intValue() % 2 == 0) { @@ -135,8 +141,9 @@ public class CompoundQueryableTest extends TestCase { }; - Query greatestNumberQuery = new ContextQuery() { - public Collector perform(Iterator iterator, Collector result) { + IQuery greatestNumberQuery = new ContextQuery() { + public Collector perform(Iterator iterator) { + Collector result = new Collector(); int greatest = Integer.MIN_VALUE; while (iterator.hasNext()) { int item = ((Integer) iterator.next()).intValue(); @@ -151,208 +158,129 @@ public class CompoundQueryableTest extends TestCase { }; public void testMatchQuery() { - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1, queryable2}); + CompoundQueryable cQueryable = new CompoundQueryable(queryable1, queryable2); CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - Collector collector = cQueryable.query(matchQuery, new Collector(), monitor); - assertEquals("1.0", 6, collector.size()); - Collection collection = collector.toCollection(); - assertTrue("1.1", collection.contains(2)); - assertTrue("1.2", collection.contains(4)); - assertTrue("1.3", collection.contains(6)); - assertTrue("1.4", collection.contains(8)); - assertTrue("1.5", collection.contains(10)); - assertTrue("1.6", collection.contains(12)); + IQueryResult queryResult = cQueryable.query(matchQuery, monitor); + assertEquals("1.0", 6, AbstractProvisioningTest.queryResultSize(queryResult)); + AbstractProvisioningTest.assertContains("1.1", queryResult, 2); + AbstractProvisioningTest.assertContains("1.2", queryResult, 4); + AbstractProvisioningTest.assertContains("1.3", queryResult, 6); + AbstractProvisioningTest.assertContains("1.4", queryResult, 8); + AbstractProvisioningTest.assertContains("1.5", queryResult, 10); + AbstractProvisioningTest.assertContains("1.6", queryResult, 12); } public void testSingleQueryable() { - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1}); + CompoundQueryable cQueryable = new CompoundQueryable(queryable1); CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - Collector collector = cQueryable.query(matchQuery, new Collector(), monitor); - assertEquals("1.0", 2, collector.size()); - Collection collection = collector.toCollection(); - assertTrue("1.1", collection.contains(2)); - assertTrue("1.2", collection.contains(4)); + IQueryResult queryResult = cQueryable.query(matchQuery, monitor); + assertEquals("1.0", 2, AbstractProvisioningTest.queryResultSize(queryResult)); + AbstractProvisioningTest.assertContains("1.1", queryResult, 2); + AbstractProvisioningTest.assertContains("1.2", queryResult, 4); } public void testSingleContextQuery() { - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1}); + CompoundQueryable cQueryable = new CompoundQueryable(queryable1); CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - Collector collector = cQueryable.query(greatestNumberQuery, new Collector(), monitor); - assertEquals("1.0", 1, collector.size()); - Collection collection = collector.toCollection(); - assertTrue("1.1", collection.contains(5)); + IQueryResult queryResult = cQueryable.query(greatestNumberQuery, monitor); + assertEquals("1.0", 1, AbstractProvisioningTest.queryResultSize(queryResult)); + AbstractProvisioningTest.assertContains("1.1", queryResult, 5); } public void testMultipleContextQueries() { - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1, queryable2}); + CompoundQueryable cQueryable = new CompoundQueryable(queryable1, queryable2); CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - Collector collector = cQueryable.query(greatestNumberQuery, new Collector(), monitor); - assertEquals("1.0", 1, collector.size()); - Collection collection = collector.toCollection(); - assertTrue("1.1", collection.contains(12)); - } - - public void testListCollector1() { - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1, queryable2}); - CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - Collector collector = cQueryable.query(contextQuery, cQueryable.new ListCollector(), monitor); - - // We use a list so there should be 7 elements (4 is there twice) - assertEquals("1.0", 7, collector.size()); - Collection collection = collector.toCollection(); - assertTrue("1.1", collection.contains(2)); - assertTrue("1.2", collection.contains(4)); - assertTrue("1.3", collection.contains(6)); - assertTrue("1.4", collection.contains(8)); - assertTrue("1.5", collection.contains(10)); - assertTrue("1.6", collection.contains(12)); - } - - public void testListCollector_isEmpty() { - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1, queryable2}); - CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - Collector collector = cQueryable.new ListCollector(); - assertTrue("1.0", collector.isEmpty()); - collector = cQueryable.query(contextQuery, cQueryable.new ListCollector(), monitor); - assertFalse("1.0", collector.isEmpty()); - } - - public void testListCollector_getCollection() { - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1, queryable2}); - CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - - Collector collector = cQueryable.query(contextQuery, cQueryable.new ListCollector(), monitor); - - // We use a list so there should be 7 elements (4 is there twice) - assertEquals("1.0", 7, collector.size()); - Integer[] array = (Integer[]) collector.toArray(Integer.class); - Collection collection = Arrays.asList(array); - assertTrue("1.1", collection.contains(2)); - assertTrue("1.2", collection.contains(4)); - assertTrue("1.3", collection.contains(6)); - assertTrue("1.4", collection.contains(8)); - assertTrue("1.5", collection.contains(10)); - assertTrue("1.6", collection.contains(12)); - } - - public void testListCollector_toArray() { - final CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1, queryable2}); - CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - - class CustomListCollector extends CompoundQueryable.ListCollector { - - public CustomListCollector() { - cQueryable.super(); - } - - public Collection getCollection() { - return super.getCollection(); - } - } - - CustomListCollector collector = (CustomListCollector) cQueryable.query(contextQuery, new CustomListCollector(), monitor); - - // We use a list so there should be 7 elements (4 is there twice) - assertEquals("1.0", 7, collector.size()); - Collection collection = collector.getCollection(); - assertTrue("1.1", collection.contains(2)); - assertTrue("1.2", collection.contains(4)); - assertTrue("1.3", collection.contains(6)); - assertTrue("1.4", collection.contains(8)); - assertTrue("1.5", collection.contains(10)); - assertTrue("1.6", collection.contains(12)); + IQueryResult queryResult = cQueryable.query(greatestNumberQuery, monitor); + assertEquals("1.0", 1, AbstractProvisioningTest.queryResultSize(queryResult)); + AbstractProvisioningTest.assertContains("1.1", queryResult, 12); } public void testCompoundMatchAndQuery() { - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1, queryable2}); + CompoundQueryable cQueryable = new CompoundQueryable(queryable1, queryable2); CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - Collector collector = cQueryable.query(CompoundQuery.createCompoundQuery(new Query[] {matchQuery, matchMod4query}, true), new Collector(), monitor); - assertEquals("1.0", 3, collector.size()); - Collection collection = collector.toCollection(); - assertTrue("1.2", collection.contains(4)); - assertTrue("1.4", collection.contains(8)); - assertTrue("1.6", collection.contains(12)); + IQueryResult queryResult = cQueryable.query(CompoundQuery.createCompoundQuery(new IQuery[] {matchQuery, matchMod4query}, true), monitor); + assertEquals("1.0", 3, AbstractProvisioningTest.queryResultSize(queryResult)); + AbstractProvisioningTest.assertContains("1.2", queryResult, 4); + AbstractProvisioningTest.assertContains("1.4", queryResult, 8); + AbstractProvisioningTest.assertContains("1.6", queryResult, 12); } public void testCompoundMatchOrQuery() { - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1, queryable2}); + CompoundQueryable cQueryable = new CompoundQueryable(queryable1, queryable2); CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - Collector collector = cQueryable.query(CompoundQuery.createCompoundQuery(new Query[] {matchQuery, matchMod4query}, false), new Collector(), monitor); - assertEquals("1.0", 6, collector.size()); - Collection collection = collector.toCollection(); - assertTrue("1.2", collection.contains(2)); - assertTrue("1.2", collection.contains(4)); - assertTrue("1.2", collection.contains(6)); - assertTrue("1.4", collection.contains(8)); - assertTrue("1.2", collection.contains(10)); - assertTrue("1.6", collection.contains(12)); + IQueryResult queryResult = cQueryable.query(CompoundQuery.createCompoundQuery(new IQuery[] {matchQuery, matchMod4query}, false), monitor); + assertEquals("1.0", 6, AbstractProvisioningTest.queryResultSize(queryResult)); + AbstractProvisioningTest.assertContains("1.2", queryResult, 2); + AbstractProvisioningTest.assertContains("1.2", queryResult, 4); + AbstractProvisioningTest.assertContains("1.2", queryResult, 6); + AbstractProvisioningTest.assertContains("1.4", queryResult, 8); + AbstractProvisioningTest.assertContains("1.2", queryResult, 10); + AbstractProvisioningTest.assertContains("1.6", queryResult, 12); } public void testMatchQueryProgressMonitor() { - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1, queryable2}); + CompoundQueryable cQueryable = new CompoundQueryable(queryable1, queryable2); CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - cQueryable.query(matchQuery, new Collector(), monitor); + cQueryable.query(matchQuery, monitor); assertTrue("1.0", monitor.isDone()); assertTrue("1.1", monitor.isWorkDone()); } public void testSingleQueryableProgressMonitor() { - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1}); + CompoundQueryable cQueryable = new CompoundQueryable(queryable1); CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - cQueryable.query(matchQuery, new Collector(), monitor); + cQueryable.query(matchQuery, monitor); assertTrue("1.0", monitor.isDone()); assertTrue("1.1", monitor.isWorkDone()); } public void testSingleContextQueryProgressMonitor() { - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1}); + CompoundQueryable cQueryable = new CompoundQueryable(queryable1); CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - cQueryable.query(greatestNumberQuery, new Collector(), monitor); + cQueryable.query(greatestNumberQuery, monitor); assertTrue("1.0", monitor.isDone()); assertTrue("1.1", monitor.isWorkDone()); } public void testMultipleContextQueriesProgressMonitor() { - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1, queryable2}); + CompoundQueryable cQueryable = new CompoundQueryable(queryable1, queryable2); CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - cQueryable.query(greatestNumberQuery, new Collector(), monitor); + cQueryable.query(greatestNumberQuery, monitor); assertTrue("1.0", monitor.isDone()); assertTrue("1.1", monitor.isWorkDone()); } public void testNullProgressMonitor() { - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {queryable1, queryable2}); - cQueryable.query(greatestNumberQuery, new Collector(), null); + CompoundQueryable cQueryable = new CompoundQueryable(queryable1, queryable2); + cQueryable.query(greatestNumberQuery, null); // this is the same as above will null passed in, this should not throw any exceptions } public void testDoubleCompoundContextOrQuery() { - CompoundQueryable cQueryable1 = new CompoundQueryable(new IQueryable[] {queryable3, queryable2}); - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {cQueryable1, queryable1}); + CompoundQueryable cQueryable1 = new CompoundQueryable(queryable3, queryable2); + CompoundQueryable cQueryable = new CompoundQueryable(cQueryable1, queryable1); CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - Collector collector = cQueryable.query(CompoundQuery.createCompoundQuery(new Query[] {contextQuery, greatestNumberQuery}, false), new Collector(), monitor); - assertEquals("1.0", 7, collector.size()); - Collection collection = collector.toCollection(); - assertTrue("1.2", collection.contains(2)); - assertTrue("1.2", collection.contains(4)); - assertTrue("1.2", collection.contains(6)); - assertTrue("1.4", collection.contains(8)); - assertTrue("1.2", collection.contains(10)); - assertTrue("1.6", collection.contains(12)); - assertTrue("1.6", collection.contains(13)); + IQueryResult queryResult = cQueryable.query(CompoundQuery.createCompoundQuery(new IQuery[] {contextQuery, greatestNumberQuery}, false), monitor); + assertEquals("1.0", 7, AbstractProvisioningTest.queryResultSize(queryResult)); + AbstractProvisioningTest.assertContains("1.2", queryResult, 2); + AbstractProvisioningTest.assertContains("1.2", queryResult, 4); + AbstractProvisioningTest.assertContains("1.2", queryResult, 6); + AbstractProvisioningTest.assertContains("1.4", queryResult, 8); + AbstractProvisioningTest.assertContains("1.2", queryResult, 10); + AbstractProvisioningTest.assertContains("1.6", queryResult, 12); + AbstractProvisioningTest.assertContains("1.6", queryResult, 13); assertTrue("1.0", monitor.isDone()); assertTrue("1.1", monitor.isWorkDone()); } public void testDoubleCompositeQuery() { - CompoundQueryable cQueryable1 = new CompoundQueryable(new IQueryable[] {queryable3, queryable2}); - CompoundQueryable cQueryable = new CompoundQueryable(new IQueryable[] {cQueryable1, queryable1}); + CompoundQueryable cQueryable1 = new CompoundQueryable(queryable3, queryable2); + CompoundQueryable cQueryable = new CompoundQueryable(cQueryable1, queryable1); CompoundQueryTestProgressMonitor monitor = new CompoundQueryTestProgressMonitor(); - Collector collector = cQueryable.query(new CompositeQuery(new Query[] {contextQuery, greatestNumberQuery}), new Collector(), monitor); - assertEquals("1.0", 1, collector.size()); - Collection collection = collector.toCollection(); - assertTrue("1.2", collection.contains(12)); + IQueryResult queryResult = cQueryable.query(new PipedQuery(contextQuery, greatestNumberQuery), monitor); + assertEquals("1.0", 1, AbstractProvisioningTest.queryResultSize(queryResult)); + AbstractProvisioningTest.assertContains("1.2", queryResult, 12); assertTrue("1.0", monitor.isDone()); assertTrue("1.1", monitor.isWorkDone()); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/PropertyLookupQuery1.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/PropertyLookupQuery1.java index 22d98ddbc..b212c8c28 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/PropertyLookupQuery1.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/PropertyLookupQuery1.java @@ -9,7 +9,7 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.core; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.MatchQuery; +import org.eclipse.equinox.p2.query.MatchQuery; public class PropertyLookupQuery1 extends MatchQuery { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/PropertyLookupQuery2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/PropertyLookupQuery2.java index 7564cc633..e7e45457a 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/PropertyLookupQuery2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/PropertyLookupQuery2.java @@ -10,8 +10,8 @@ package org.eclipse.equinox.p2.tests.core; import java.util.Iterator; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.ContextQuery; +import org.eclipse.equinox.p2.query.Collector; +import org.eclipse.equinox.p2.query.ContextQuery; public class PropertyLookupQuery2 extends ContextQuery { @@ -19,7 +19,7 @@ public class PropertyLookupQuery2 extends ContextQuery { return "bar"; } - public Collector perform(Iterator iterator, Collector result) { + public Collector perform(Iterator iterator) { return null; } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/QueryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/QueryTest.java index 81c2d9ca6..e05b16f25 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/QueryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/core/QueryTest.java @@ -10,9 +10,11 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.core; -import java.util.*; +import java.util.Arrays; +import java.util.List; import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** * Tests for the {@link org.eclipse.equinox.internal.provisional.p2.query.Query} class. @@ -63,29 +65,16 @@ public class QueryTest extends TestCase { } /** - * A collector that only accepts the first element and then short-circuits. - */ - static class ShortCircuitCollector extends Collector { - @Override - public boolean accept(Object object) { - super.accept(object); - return false; - } - } - - /** - * Tests a simple perform where all items match. - */ + * Tests a simple perform where all items match. + */ public void testPerformSimple() { List items = Arrays.asList("red", "green", "blue"); - Query query = new AnyStringQuery(); - Collector collector = new Collector(); - query.perform(items.iterator(), collector); - Collection result = collector.toCollection(); - assertEquals("1.0", 3, result.size()); - assertTrue("1.1", result.contains("red")); - assertTrue("1.2", result.contains("green")); - assertTrue("1.3", result.contains("blue")); + IQuery query = new AnyStringQuery(); + IQueryResult collector = query.perform(items.iterator()); + assertEquals("1.0", 3, AbstractProvisioningTest.queryResultSize(collector)); + AbstractProvisioningTest.assertContains("1.1", collector, "red"); + AbstractProvisioningTest.assertContains("1.2", collector, "green"); + AbstractProvisioningTest.assertContains("1.3", collector, "blue"); } /** @@ -93,53 +82,50 @@ public class QueryTest extends TestCase { */ public void testPerformSomeMatches() { List items = Arrays.asList(new Object(), "green", new Object()); - Query query = new AnyStringQuery(); - Collector collector = new Collector(); - query.perform(items.iterator(), collector); - Collection result = collector.toCollection(); - assertEquals("1.0", 1, result.size()); - assertTrue("1.1", result.contains("green")); + IQuery query = new AnyStringQuery(); + IQueryResult collector = query.perform(items.iterator()); + assertEquals("1.0", 1, AbstractProvisioningTest.queryResultSize(collector)); + AbstractProvisioningTest.assertContains("1.1", collector, "green"); } public void testPerformHooks() { List items = Arrays.asList("red", "green", "blue"); PerformHookQuery query = new PerformHookQuery(); - Collector collector = new Collector(); assertFalse("1.0", query.isComplete()); assertFalse("1.1", query.isPrepared()); - query.perform(items.iterator(), collector); + query.perform(items.iterator()); assertTrue("1.2", query.isComplete()); assertTrue("1.3", query.isPrepared()); assertTrue("1.4", query.areHooksExecutedProperly()); } public void testPropertyLookupMatchQuery() { - Query query1 = new PropertyLookupQuery1(); + IQuery query1 = new PropertyLookupQuery1(); Object property = query1.getProperty("SomeProperty"); assertEquals("1.0", "foo", property); } public void testPropertyLookupContextQuery() { - Query query1 = new PropertyLookupQuery2(); + IQuery query1 = new PropertyLookupQuery2(); Object property = query1.getProperty("SomeOtherProperty"); assertEquals("1.0", "bar", property); } public void testPropertyLookupInvalidProperty1() { - Query query1 = new PropertyLookupQuery1(); + IQuery query1 = new PropertyLookupQuery1(); Object property = query1.getProperty("ThisProperty"); assertEquals("1.0", null, property); } public void testPropertyLookupInvalidProperty2() { - Query query1 = new PropertyLookupQuery1(); + IQuery query1 = new PropertyLookupQuery1(); Object property = query1.getProperty("SomeOtherProperty"); assertEquals("1.0", null, property); } public void testIDLookup() { - Query query1 = new PropertyLookupQuery1(); - Query query2 = new PropertyLookupQuery2(); + IQuery query1 = new PropertyLookupQuery1(); + IQuery query2 = new PropertyLookupQuery2(); assertEquals("1.0", "org.eclipse.equinox.p2.tests.core.PropertyLookupQuery1", query1.getId()); assertEquals("1.0", "org.eclipse.equinox.p2.tests.core.PropertyLookupQuery2", query2.getId()); } @@ -147,11 +133,10 @@ public class QueryTest extends TestCase { public void testPerformHooksOnQueryFail() { List items = Arrays.asList("red", new Object()); PerformHookQuery query = new PerformHookQuery(); - Collector collector = new Collector(); assertFalse("1.0", query.isComplete()); assertFalse("1.1", query.isPrepared()); try { - query.perform(items.iterator(), collector); + query.perform(items.iterator()); } catch (RuntimeException e) { // expected } @@ -162,15 +147,14 @@ public class QueryTest extends TestCase { public void testPreAndPostCompoundANDQuery() { List items = Arrays.asList("red", "green", "blue"); - Collector collector = new Collector(); PerformHookQuery query1 = new PerformHookQuery(); PerformHookQuery query2 = new PerformHookQuery(); - CompoundQuery cQuery = CompoundQuery.createCompoundQuery(new Query[] {query1, query2}, true); + CompoundQuery cQuery = CompoundQuery.createCompoundQuery(new IQuery[] {query1, query2}, true); assertFalse("1.0", query1.isComplete()); assertFalse("1.1", query1.isPrepared()); assertFalse("1.2", query2.isComplete()); assertFalse("1.3", query2.isPrepared()); - cQuery.perform(items.iterator(), collector); + cQuery.perform(items.iterator()); assertTrue("1.4", query1.isComplete()); assertTrue("1.5", query1.isPrepared()); assertTrue("1.6", query2.isComplete()); @@ -181,15 +165,14 @@ public class QueryTest extends TestCase { public void testPreAndPostCompoundOrQuery() { List items = Arrays.asList("red", "green", "blue"); - Collector collector = new Collector(); PerformHookQuery query1 = new PerformHookQuery(); PerformHookQuery query2 = new PerformHookQuery(); - CompoundQuery cQuery = CompoundQuery.createCompoundQuery(new Query[] {query1, query2}, false); + CompoundQuery cQuery = CompoundQuery.createCompoundQuery(new IQuery[] {query1, query2}, false); assertFalse("1.0", query1.isComplete()); assertFalse("1.1", query1.isPrepared()); assertFalse("1.2", query2.isComplete()); assertFalse("1.3", query2.isPrepared()); - cQuery.perform(items.iterator(), collector); + cQuery.perform(items.iterator()); assertTrue("1.4", query1.isComplete()); assertTrue("1.5", query1.isPrepared()); assertTrue("1.6", query2.isComplete()); @@ -200,15 +183,14 @@ public class QueryTest extends TestCase { public void testPreAndPostCompositeQuery() { List items = Arrays.asList("red", "green", "blue"); - Collector collector = new Collector(); PerformHookQuery query1 = new PerformHookQuery(); PerformHookQuery query2 = new PerformHookQuery(); - CompositeQuery cQuery = new CompositeQuery(new Query[] {query1, query2}); + PipedQuery cQuery = new PipedQuery(query1, query2); assertFalse("1.0", query1.isComplete()); assertFalse("1.1", query1.isPrepared()); assertFalse("1.2", query2.isComplete()); assertFalse("1.3", query2.isPrepared()); - cQuery.perform(items.iterator(), collector); + cQuery.perform(items.iterator()); assertTrue("1.4", query1.isComplete()); assertTrue("1.5", query1.isPrepared()); assertTrue("1.6", query2.isComplete()); @@ -219,16 +201,15 @@ public class QueryTest extends TestCase { public void testPreAndPostCompoundQueryFail() { List items = Arrays.asList("red", new Object()); - Collector collector = new Collector(); PerformHookQuery query1 = new PerformHookQuery(); PerformHookQuery query2 = new PerformHookQuery(); - CompoundQuery cQuery = CompoundQuery.createCompoundQuery(new Query[] {query1, query2}, true); + CompoundQuery cQuery = CompoundQuery.createCompoundQuery(new IQuery[] {query1, query2}, true); assertFalse("1.0", query1.isComplete()); assertFalse("1.1", query1.isPrepared()); assertFalse("1.2", query2.isComplete()); assertFalse("1.3", query2.isPrepared()); try { - cQuery.perform(items.iterator(), collector); + cQuery.perform(items.iterator()); fail("This query is expected to fail"); } catch (RuntimeException e) { // expected @@ -243,16 +224,15 @@ public class QueryTest extends TestCase { public void testPreAndPostCompositeQueryFail() { List items = Arrays.asList("red", new Object()); - Collector collector = new Collector(); PerformHookQuery query1 = new PerformHookQuery(); PerformHookQuery query2 = new PerformHookQuery(); - CompositeQuery cQuery = new CompositeQuery(new Query[] {query1, query2}); + PipedQuery cQuery = new PipedQuery(query1, query2); assertFalse("1.0", query1.isComplete()); assertFalse("1.1", query1.isPrepared()); assertFalse("1.2", query2.isComplete()); assertFalse("1.3", query2.isPrepared()); try { - cQuery.perform(items.iterator(), collector); + cQuery.perform(items.iterator()); fail("This query is expected to fail"); } catch (RuntimeException e) { // expected @@ -265,17 +245,59 @@ public class QueryTest extends TestCase { assertTrue("1.9", query2.areHooksExecutedProperly()); } - /** - * Tests a perform where the collector decides to short-circuit the query. - */ - public void testShortCircuit() { + public void testLimitQuery() { List items = Arrays.asList("red", "green", "blue"); - Query query = new AnyStringQuery(); - Collector collector = new ShortCircuitCollector(); - query.perform(items.iterator(), collector); - Collection result = collector.toCollection(); - assertEquals("1.0", 1, result.size()); - assertTrue("1.1", result.contains("red")); + IQuery query = new AnyStringQuery(); + IQuery limitQuery = new LimitQuery(query, 1); + IQueryResult collector = limitQuery.perform(items.iterator()); + assertEquals("1.0", 1, AbstractProvisioningTest.queryResultSize(collector)); + AbstractProvisioningTest.assertContains("1.1", collector, "red"); } + public void testLimitQuery2() { + List items = Arrays.asList("red", "green", "blue"); + IQuery query = new AnyStringQuery(); + IQuery limitQuery = new LimitQuery(query, 2); + IQueryResult collector = limitQuery.perform(items.iterator()); + assertEquals("1.0", 2, AbstractProvisioningTest.queryResultSize(collector)); + AbstractProvisioningTest.assertContains("1.1", collector, "red"); + AbstractProvisioningTest.assertContains("1.2", collector, "green"); + } + + public void testLimitQuery3() { + List items = Arrays.asList("red", "green", "blue"); + IQuery query = new AnyStringQuery(); + IQuery limitQuery = new LimitQuery(query, 3); + IQueryResult collector = limitQuery.perform(items.iterator()); + assertEquals("1.0", 3, AbstractProvisioningTest.queryResultSize(collector)); + AbstractProvisioningTest.assertContains("1.1", collector, "red"); + AbstractProvisioningTest.assertContains("1.2", collector, "green"); + AbstractProvisioningTest.assertContains("1.3", collector, "blue"); + } + + public void testLimitQuery0() { + List items = Arrays.asList("red", "green", "blue"); + IQuery query = new AnyStringQuery(); + IQuery limitQuery = new LimitQuery(query, 0); + IQueryResult collector = limitQuery.perform(items.iterator()); + assertEquals("1.0", 0, AbstractProvisioningTest.queryResultSize(collector)); + } + + // public void testPipedLimitQuery() { + // List items = Arrays.asList("pink", "red", "green", "pink"); + // IQuery anyString = new AnyStringQuery(); + // IQuery containsI = new MatchQuery() { + // + // public boolean isMatch(Object candidate) { + // return ((String) candidate).contains("e"); + // } + // }; + // IQuery pipedQuery = new PipedQuery(new IQuery[] {anyString, containsI}); + // IQuery limitQuery = new LimitQuery(pipedQuery, 1); + // Collector collector = limitQuery.perform(items.iterator(), new Collector()); + // Collection result = collector.toCollection(); + // assertEquals("1.0", 1, result.size()); + // assertTrue("1.1", result.contains("red")); + // } + } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/AutomatedDirectorTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/AutomatedDirectorTest.java index a18084e7f..cabde3bcb 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/AutomatedDirectorTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/AutomatedDirectorTest.java @@ -14,17 +14,21 @@ import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IDirector; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IProvidedCapability; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; +import org.osgi.framework.Filter; /** * Various automated tests of the {@link IDirector} API. */ public class AutomatedDirectorTest extends AbstractProvisioningTest { - //private static Version version = new Version(1, 0, 0); + //private static Version version = Version.createOSGi(1, 0, 0); public static Test suite() { return new TestSuite(AutomatedDirectorTest.class); @@ -49,8 +53,8 @@ public class AutomatedDirectorTest extends AbstractProvisioningTest { IInstallableUnit requiredIU = createIU("required." + getName()); // The IU to be installed - String filter = createFilter("FilterKey", "true"); - IRequiredCapability capability = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, requiredIU.getId(), ANY_VERSION, filter, false, false); + Filter filter = createFilter("FilterKey", "true"); + IRequiredCapability capability = (IRequiredCapability) MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, requiredIU.getId(), ANY_VERSION, filter, false, false); IInstallableUnit toInstallIU = createIU("toInstall." + getName(), new IRequiredCapability[] {capability}); IInstallableUnit[] allUnits = new IInstallableUnit[] {requiredIU, toInstallIU}; @@ -61,7 +65,7 @@ public class AutomatedDirectorTest extends AbstractProvisioningTest { //Install into a profile in which the filter is satisfied Map properties = new HashMap(); properties.put(IProfile.PROP_ENVIRONMENTS, "FilterKey=true"); - IProfile satisfied = createProfile("Satisfied." + getName(), null, properties); + IProfile satisfied = createProfile("Satisfied." + getName(), properties); ProfileChangeRequest request = new ProfileChangeRequest(satisfied); request.addInstallableUnits(toInstallArray); IStatus result = director.provision(request, null, null); @@ -78,7 +82,7 @@ public class AutomatedDirectorTest extends AbstractProvisioningTest { IInstallableUnit requiredIU = createIU("required." + getName(), new IProvidedCapability[] {MetadataFactory.createProvidedCapability("test.capability", capabilityId, DEFAULT_VERSION)}); //The IU that optionally requires the capability - IRequiredCapability required = MetadataFactory.createRequiredCapability("test.capability", capabilityId, ANY_VERSION, null, /* optional=> */true, /* multiple=> */false, /* greedy=>*/false); + IRequiredCapability required = (IRequiredCapability) MetadataFactory.createRequiredCapability("test.capability", capabilityId, ANY_VERSION, null, /* optional=> */true, /* multiple=> */false, /* greedy=>*/false); IInstallableUnit toInstallIU = createIU("toInstall." + getName(), new IRequiredCapability[] {required}); IInstallableUnit[] allUnits = new IInstallableUnit[] {toInstallIU, requiredIU}; @@ -102,7 +106,7 @@ public class AutomatedDirectorTest extends AbstractProvisioningTest { public void testInstallOptionalUnavailable() { String capabilityId = "test." + getName(); //no IU will be available that exports this capability - IRequiredCapability required = MetadataFactory.createRequiredCapability("test.capability", capabilityId, ANY_VERSION, null, true, false); + IRequiredCapability required = (IRequiredCapability) MetadataFactory.createRequiredCapability("test.capability", capabilityId, ANY_VERSION, null, true, false); IInstallableUnit toInstallIU = createIU("toInstall." + getName(), new IRequiredCapability[] {required}); IInstallableUnit[] allUnits = new IInstallableUnit[] {toInstallIU}; @@ -129,7 +133,7 @@ public class AutomatedDirectorTest extends AbstractProvisioningTest { IProvidedCapability[] provides = new IProvidedCapability[] {MetadataFactory.createProvidedCapability("test.capability", capabilityId, DEFAULT_VERSION)}; IInstallableUnit requiredIU = createIU("required." + getName(), createFilter("osgi.os", "blort"), provides); - IInstallableUnit toInstallIU = createIU("toInstall." + getName(), createRequiredCapabilities("test.capability", capabilityId, ANY_VERSION, null)); + IInstallableUnit toInstallIU = createIU("toInstall." + getName(), createRequiredCapabilities("test.capability", capabilityId, ANY_VERSION, (Filter) null)); IInstallableUnit[] allUnits = new IInstallableUnit[] {requiredIU, toInstallIU}; IInstallableUnit[] toInstallArray = new IInstallableUnit[] {toInstallIU}; @@ -145,7 +149,7 @@ public class AutomatedDirectorTest extends AbstractProvisioningTest { //try again with the filter satisfied Map properties = new HashMap(); properties.put(IProfile.PROP_ENVIRONMENTS, "osgi.os=blort"); - IProfile profile2 = createProfile("TestProfile2." + getName(), null, properties); + IProfile profile2 = createProfile("TestProfile2." + getName(), properties); request = new ProfileChangeRequest(profile2); request.addInstallableUnits(toInstallArray); result = director.provision(request, null, null); @@ -172,7 +176,7 @@ public class AutomatedDirectorTest extends AbstractProvisioningTest { //try again with the filter satisfied Map properties = new HashMap(); properties.put(IProfile.PROP_ENVIRONMENTS, "osgi.os=blort"); - IProfile profile2 = createProfile("TestProfile2." + getName(), null, properties); + IProfile profile2 = createProfile("TestProfile2." + getName(), properties); request = new ProfileChangeRequest(profile2); request.addInstallableUnits(toInstallArray); result = director.provision(request, null, null); @@ -188,7 +192,7 @@ public class AutomatedDirectorTest extends AbstractProvisioningTest { //The IU that exports the capability IInstallableUnit requiredIU = createIU("required." + getName(), new IProvidedCapability[] {MetadataFactory.createProvidedCapability("test.capability", capabilityId, DEFAULT_VERSION)}); - IInstallableUnit toInstallIU = createIU("toInstall." + getName(), createRequiredCapabilities("test.capability", capabilityId, ANY_VERSION, null)); + IInstallableUnit toInstallIU = createIU("toInstall." + getName(), createRequiredCapabilities("test.capability", capabilityId, ANY_VERSION, (Filter) null)); IInstallableUnit[] allUnits = new IInstallableUnit[] {requiredIU, toInstallIU}; IInstallableUnit[] toInstallArray = new IInstallableUnit[] {toInstallIU}; @@ -214,7 +218,7 @@ public class AutomatedDirectorTest extends AbstractProvisioningTest { //The IU that is needed IInstallableUnit requiredIU = createIU("required." + getName()); - IRequiredCapability capability = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, requiredIU.getId(), null, null, false, false); + IRequiredCapability capability = (IRequiredCapability) MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, requiredIU.getId(), null, null, false, false); IInstallableUnit toInstallIU = createIU("toInstall." + getName(), new IRequiredCapability[] {capability}); IInstallableUnit[] allUnits = new IInstallableUnit[] {requiredIU, toInstallIU}; @@ -242,7 +246,7 @@ public class AutomatedDirectorTest extends AbstractProvisioningTest { //The IU that exports the capability IInstallableUnit requiredIU = createIU("required." + getName()); - IRequiredCapability capability = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, requiredIU.getId(), ANY_VERSION, null, false, false); + IRequiredCapability capability = (IRequiredCapability) MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, requiredIU.getId(), ANY_VERSION, null, false, false); IInstallableUnit toInstallIU = createIU("toInstall." + getName(), new IRequiredCapability[] {capability}); IInstallableUnit[] allUnits = new IInstallableUnit[] {requiredIU, toInstallIU}; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/Bug203637.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/Bug203637.java index c087e00b9..08e3f6fdd 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/Bug203637.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/Bug203637.java @@ -10,19 +10,19 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.director; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import org.eclipse.equinox.internal.provisional.p2.director.IDirector; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class Bug203637 extends AbstractProvisioningTest { public void test() { IDirector d = createDirector(); IProfile profile = createProfile("TestProfile." + getName()); - IInstallableUnit a1 = createIU("A", new Version(1, 0, 0), true); + IInstallableUnit a1 = createIU("A", Version.createOSGi(1, 0, 0), true); ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {a1}); request.removeInstallableUnits(new IInstallableUnit[0]); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/DirectorAppTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/DirectorAppTest.java index 2cf543da7..d39a38c6c 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/DirectorAppTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/DirectorAppTest.java @@ -22,12 +22,12 @@ import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.director.app.Activator; import org.eclipse.equinox.internal.p2.director.app.Application; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.osgi.framework.Bundle; @@ -473,10 +473,10 @@ public class DirectorAppTest extends AbstractProvisioningTest { URI metadataRepo1 = getTestData("10.1", "/testData/metadataRepo/good").toURI(); URI metadataRepo2 = getTestData("10.1", "/testData/metadataRepo/multipleversions1").toURI(); Application application = new Application(); - Method method = application.getClass().getDeclaredMethod("collectRootIUs", URI[].class, Query.class, Collector.class); + Method method = application.getClass().getDeclaredMethod("collectRootIUs", URI[].class, IQuery.class); method.setAccessible(true); URI[] uris = new URI[] {metadataRepo1, metadataRepo2}; - Query query = new MatchQuery() { + IQuery query = new MatchQuery() { public boolean isMatch(Object candidate) { if (candidate instanceof IInstallableUnit) { IInstallableUnit iu = (IInstallableUnit) candidate; @@ -486,8 +486,7 @@ public class DirectorAppTest extends AbstractProvisioningTest { return false; } }; - Collector collector = new Collector(); - Collector result = (Collector) method.invoke(application, uris, query, collector); + Collector result = (Collector) method.invoke(application, uris, query); assertEquals("1.0", 1, result.size()); } @@ -572,8 +571,8 @@ public class DirectorAppTest extends AbstractProvisioningTest { File artifactRepo1 = getTestData("12.0", "/testData/mirror/mirrorSourceRepo3"); File metadataRepo1 = getTestData("12.1", "/testData/mirror/mirrorSourceRepo3"); - IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); - IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); + IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); assertNotNull(artifactManager); assertNotNull(metadataManager); @@ -619,8 +618,8 @@ public class DirectorAppTest extends AbstractProvisioningTest { File artifactRepo1 = getTestData("13.0", "/testData/mirror/mirrorSourceRepo4"); File metadataRepo1 = getTestData("13.1", "/testData/mirror/mirrorSourceRepo4"); - IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); - IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); + IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); assertNotNull(artifactManager); assertNotNull(metadataManager); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/DirectorApplicationTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/DirectorApplicationTest.java index a88c991f6..336011ab3 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/DirectorApplicationTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/DirectorApplicationTest.java @@ -22,12 +22,12 @@ import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.director.app.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.osgi.framework.Bundle; @@ -526,10 +526,10 @@ public class DirectorApplicationTest extends AbstractProvisioningTest { URI metadataRepo1 = getTestData("10.1", "/testData/metadataRepo/good").toURI(); URI metadataRepo2 = getTestData("10.1", "/testData/metadataRepo/multipleversions1").toURI(); Application application = new Application(); - Method method = application.getClass().getDeclaredMethod("collectRootIUs", URI[].class, Query.class, Collector.class); + Method method = application.getClass().getDeclaredMethod("collectRootIUs", URI[].class, IQuery.class); method.setAccessible(true); URI[] uris = new URI[] {metadataRepo1, metadataRepo2}; - Query query = new MatchQuery() { + IQuery query = new MatchQuery() { public boolean isMatch(Object candidate) { if (candidate instanceof IInstallableUnit) { IInstallableUnit iu = (IInstallableUnit) candidate; @@ -539,8 +539,7 @@ public class DirectorApplicationTest extends AbstractProvisioningTest { return false; } }; - Collector collector = new Collector(); - Collector result = (Collector) method.invoke(application, uris, query, collector); + Collector result = (Collector) method.invoke(application, uris, query); assertEquals("1.0", 1, result.size()); } @@ -633,8 +632,8 @@ public class DirectorApplicationTest extends AbstractProvisioningTest { File artifactRepo1 = getTestData("12.0", "/testData/mirror/mirrorSourceRepo3"); File metadataRepo1 = getTestData("12.1", "/testData/mirror/mirrorSourceRepo3"); - IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); - IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); + IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); assertNotNull(artifactManager); assertNotNull(metadataManager); @@ -683,8 +682,8 @@ public class DirectorApplicationTest extends AbstractProvisioningTest { File artifactRepo1 = getTestData("13.0", "/testData/mirror/mirrorSourceRepo4"); File metadataRepo1 = getTestData("13.1", "/testData/mirror/mirrorSourceRepo4"); - IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); - IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); + IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); assertNotNull(artifactManager); assertNotNull(metadataManager); @@ -724,8 +723,8 @@ public class DirectorApplicationTest extends AbstractProvisioningTest { public void testUninstallIgnoresPassedInRepos() throws Exception { File srcRepo = getTestData("14.0", "/testData/mirror/mirrorSourceRepo4"); - IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); - IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); + IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); assertNotNull(artifactManager); assertNotNull(metadataManager); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/OperationGenerationTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/OperationGenerationTest.java index 416a37a18..a1c451d32 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/OperationGenerationTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/OperationGenerationTest.java @@ -10,23 +10,23 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.director; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; -import java.util.ArrayList; -import java.util.Collection; +import java.util.*; import org.eclipse.equinox.internal.p2.director.OperationGenerator; import org.eclipse.equinox.internal.p2.metadata.ResolvedInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; import org.eclipse.equinox.internal.provisional.p2.metadata.*; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class OperationGenerationTest extends AbstractProvisioningTest { public void testInstallUninstall() { - IInstallableUnit a1 = createIU("a", new Version(1, 0, 0), false); - IInstallableUnit a2 = createIU("a", new Version(2, 0, 0), false); - IInstallableUnit a3 = createIU("a", new Version(3, 0, 0), false); + IInstallableUnit a1 = createIU("a", Version.createOSGi(1, 0, 0), false); + IInstallableUnit a2 = createIU("a", Version.createOSGi(2, 0, 0), false); + IInstallableUnit a3 = createIU("a", Version.createOSGi(3, 0, 0), false); Collection from; from = new ArrayList(); @@ -38,16 +38,16 @@ public class OperationGenerationTest extends AbstractProvisioningTest { to.add(a1); to.add(a3); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); // 1 x install // 1 x uninstall - assertEquals(2, operands.length); + assertEquals(2, operands.size()); } public void test1() { - IInstallableUnit a1 = createIU("a", new Version(1, 0, 0), false); - IInstallableUnit a2 = createIU("a", new Version(2, 0, 0), false); - IInstallableUnit a3 = createIU("a", new Version(3, 0, 0), false); + IInstallableUnit a1 = createIU("a", Version.createOSGi(1, 0, 0), false); + IInstallableUnit a2 = createIU("a", Version.createOSGi(2, 0, 0), false); + IInstallableUnit a3 = createIU("a", Version.createOSGi(3, 0, 0), false); Collection from; from = new ArrayList(); @@ -60,15 +60,15 @@ public class OperationGenerationTest extends AbstractProvisioningTest { to.add(a3); to.add(a2); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); // 1 x install - assertEquals(1, operands.length); + assertEquals(1, operands.size()); } public void test2() { - IInstallableUnit a1 = createIU("a", new Version(1, 0, 0), false); - IInstallableUnit a2 = createIU("a", new Version(2, 0, 0), false); - IInstallableUnit a3 = createIU("a", new Version(3, 0, 0), false); + IInstallableUnit a1 = createIU("a", Version.createOSGi(1, 0, 0), false); + IInstallableUnit a2 = createIU("a", Version.createOSGi(2, 0, 0), false); + IInstallableUnit a3 = createIU("a", Version.createOSGi(3, 0, 0), false); Collection from; from = new ArrayList(); @@ -81,17 +81,17 @@ public class OperationGenerationTest extends AbstractProvisioningTest { to.add(a1); to.add(a3); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); // 1 x uninstall - assertEquals(1, operands.length); + assertEquals(1, operands.size()); } public void testUpdate1() { - IInstallableUnit a = createIU("a", new Version(1, 0, 0), false); + IInstallableUnit a = createIU("a", Version.createOSGi(1, 0, 0), false); InstallableUnitDescription b = new MetadataFactory.InstallableUnitDescription(); b.setId("b"); - b.setVersion(new Version(1, 0, 0)); + b.setVersion(Version.createOSGi(1, 0, 0)); b.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor("a", new VersionRange("[1.0.0, 2.0.0)"), IUpdateDescriptor.NORMAL, null)); Collection from; @@ -102,18 +102,18 @@ public class OperationGenerationTest extends AbstractProvisioningTest { to = new ArrayList(); to.add(MetadataFactory.createInstallableUnit(b)); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); // 1 x upgrade - assertEquals(1, operands.length); + assertEquals(1, operands.size()); } public void testUpdate2() { - IInstallableUnit a1 = createIU("a", new Version(1, 0, 0), false); - IInstallableUnit a2 = createIU("a", new Version(2, 0, 0), false); + IInstallableUnit a1 = createIU("a", Version.createOSGi(1, 0, 0), false); + IInstallableUnit a2 = createIU("a", Version.createOSGi(2, 0, 0), false); InstallableUnitDescription b = new MetadataFactory.InstallableUnitDescription(); b.setId("b"); - b.setVersion(new Version(1, 0, 0)); + b.setVersion(Version.createOSGi(1, 0, 0)); b.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor("a", new VersionRange("[1.0.0, 3.0.0)"), IUpdateDescriptor.NORMAL, null)); Collection from; @@ -125,24 +125,24 @@ public class OperationGenerationTest extends AbstractProvisioningTest { to = new ArrayList(); to.add(MetadataFactory.createInstallableUnit(b)); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); // 1 x install // 2 x uninstall - assertEquals(3, operands.length); + assertEquals(3, operands.size()); } public void testUpdate3() { - IInstallableUnit a1 = createIU("a", new Version(1, 0, 0), false); - IInstallableUnit a2 = createIU("a", new Version(2, 0, 0), false); + IInstallableUnit a1 = createIU("a", Version.createOSGi(1, 0, 0), false); + IInstallableUnit a2 = createIU("a", Version.createOSGi(2, 0, 0), false); InstallableUnitDescription b = new MetadataFactory.InstallableUnitDescription(); b.setId("b"); - b.setVersion(new Version(1, 0, 0)); + b.setVersion(Version.createOSGi(1, 0, 0)); b.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor("a", new VersionRange("[1.0.0, 2.0.0)"), IUpdateDescriptor.NORMAL, null)); InstallableUnitDescription c = new MetadataFactory.InstallableUnitDescription(); c.setId("c"); - c.setVersion(new Version(1, 0, 0)); + c.setVersion(Version.createOSGi(1, 0, 0)); c.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor("a", new VersionRange("[2.0.0, 2.3.0)"), IUpdateDescriptor.NORMAL, null)); Collection from; @@ -155,19 +155,19 @@ public class OperationGenerationTest extends AbstractProvisioningTest { to.add(MetadataFactory.createInstallableUnit(b)); to.add(MetadataFactory.createInstallableUnit(c)); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); // 2 x update - assertEquals(2, operands.length); + assertEquals(2, operands.size()); } public void testUpdate4() { - IInstallableUnit a1 = createIU("a", new Version(1, 0, 0), false); - IInstallableUnit a2 = createIU("a", new Version(2, 0, 0), false); - IInstallableUnit b1 = createIU("b", new Version(1, 0, 0), false); + IInstallableUnit a1 = createIU("a", Version.createOSGi(1, 0, 0), false); + IInstallableUnit a2 = createIU("a", Version.createOSGi(2, 0, 0), false); + IInstallableUnit b1 = createIU("b", Version.createOSGi(1, 0, 0), false); InstallableUnitDescription b2 = new MetadataFactory.InstallableUnitDescription(); b2.setId("b"); - b2.setVersion(new Version(2, 0, 0)); + b2.setVersion(Version.createOSGi(2, 0, 0)); b2.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor("b", new VersionRange("[1.0.0, 2.0.0)"), IUpdateDescriptor.NORMAL, null)); Collection from; @@ -182,19 +182,19 @@ public class OperationGenerationTest extends AbstractProvisioningTest { to.add(a2); to.add(MetadataFactory.createInstallableUnit(b2)); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); // 1 x update - assertEquals(1, operands.length); + assertEquals(1, operands.size()); } public void testUpdate5() { - IInstallableUnit a1 = createIU("a", new Version(1, 0, 0), false); - IInstallableUnit a2 = createIU("a", new Version(2, 0, 0), false); - IInstallableUnit b1 = createIU("b", new Version(1, 0, 0), false); + IInstallableUnit a1 = createIU("a", Version.createOSGi(1, 0, 0), false); + IInstallableUnit a2 = createIU("a", Version.createOSGi(2, 0, 0), false); + IInstallableUnit b1 = createIU("b", Version.createOSGi(1, 0, 0), false); InstallableUnitDescription b2 = new MetadataFactory.InstallableUnitDescription(); b2.setId("b"); - b2.setVersion(new Version(2, 0, 0)); + b2.setVersion(Version.createOSGi(2, 0, 0)); b2.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor("b", new VersionRange("[1.0.0, 2.0.0)"), IUpdateDescriptor.NORMAL, null)); Collection from; @@ -208,21 +208,21 @@ public class OperationGenerationTest extends AbstractProvisioningTest { to.add(a1); to.add(MetadataFactory.createInstallableUnit(b2)); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); // 1 x update // 1 x uninstall - assertEquals(2, operands.length); + assertEquals(2, operands.size()); } public void test248468b() { String id = "myBundle"; - IUpdateDescriptor update = createUpdateDescriptor(id, new Version("1.0.0")); - IInstallableUnit one = createIU(id, new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update, null); - IUpdateDescriptor update2 = createUpdateDescriptor(id, new Version("2.0.0")); - IInstallableUnit two = createIU(id, new Version("2.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update2, null); + IUpdateDescriptor update = createUpdateDescriptor(id, Version.create("1.0.0")); + IInstallableUnit one = createIU(id, Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update, null); + IUpdateDescriptor update2 = createUpdateDescriptor(id, Version.create("2.0.0")); + IInstallableUnit two = createIU(id, Version.create("2.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update2, null); - IUpdateDescriptor update3 = createUpdateDescriptor(id, new Version("3.0.0")); - IInstallableUnit three = createIU(id, new Version("3.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update3, null); + IUpdateDescriptor update3 = createUpdateDescriptor(id, Version.create("3.0.0")); + IInstallableUnit three = createIU(id, Version.create("3.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update3, null); Collection from = new ArrayList(); from.add(MetadataFactory.createResolvedInstallableUnit(one, new IInstallableUnitFragment[0])); @@ -232,27 +232,27 @@ public class OperationGenerationTest extends AbstractProvisioningTest { Collection to = new ArrayList(); to.add(MetadataFactory.createResolvedInstallableUnit(three, new IInstallableUnitFragment[0])); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); //We are uninstalling myBundle 1.0 and 2.0. 3.0 stays unchanged. - for (int i = 0; i < operands.length; i++) { - assertNotSame("3.0", three, operands[i].first()); - assertNotSame("3.0.1", three, operands[i].second()); + for (int i = 0; i < operands.size(); i++) { + assertNotSame("3.0", three, operands.get(i).first()); + assertNotSame("3.0.1", three, operands.get(i).second()); } - assertEquals("3.1", one, operands[0].first()); - assertNull("3.2", operands[0].second()); - assertEquals("3.3", two, operands[1].first()); - assertNull("3.4", operands[1].second()); + assertEquals("3.1", one, operands.get(0).first()); + assertNull("3.2", operands.get(0).second()); + assertEquals("3.3", two, operands.get(1).first()); + assertNull("3.4", operands.get(1).second()); } public void test248468d() { String id = "myBundle"; - IUpdateDescriptor update = createUpdateDescriptor(id, new Version("1.0.0")); - IInstallableUnit one = createIU(id, new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update, null); - update = createUpdateDescriptor(id, new Version("2.0.0")); - IInstallableUnit two = createIU(id, new Version("2.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update, null); + IUpdateDescriptor update = createUpdateDescriptor(id, Version.create("1.0.0")); + IInstallableUnit one = createIU(id, Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update, null); + update = createUpdateDescriptor(id, Version.create("2.0.0")); + IInstallableUnit two = createIU(id, Version.create("2.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update, null); - IUpdateDescriptor update3 = createUpdateDescriptor(id, new Version("3.0.0")); - IInstallableUnit three = createIU("anotherBundle", new Version("3.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update3, null); + IUpdateDescriptor update3 = createUpdateDescriptor(id, Version.create("3.0.0")); + IInstallableUnit three = createIU("anotherBundle", Version.create("3.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update3, null); Collection from = new ArrayList(); from.add(MetadataFactory.createResolvedInstallableUnit(one, new IInstallableUnitFragment[0])); @@ -262,28 +262,28 @@ public class OperationGenerationTest extends AbstractProvisioningTest { to.add(MetadataFactory.createResolvedInstallableUnit(two, new IInstallableUnitFragment[0])); to.add(MetadataFactory.createResolvedInstallableUnit(three, new IInstallableUnitFragment[0])); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); //Two is already in the system therefore it will not be in the operands - for (int i = 0; i < operands.length; i++) { - assertNotSame("2.0", two, operands[i].first()); - assertNotSame("2.1", two, operands[i].second()); + for (int i = 0; i < operands.size(); i++) { + assertNotSame("2.0", two, operands.get(i).first()); + assertNotSame("2.1", two, operands.get(i).second()); } //three is an update of one - assertEquals("2.2", 1, operands.length); - assertEquals("2.4", one, operands[0].first()); - assertEquals("2.5", three, operands[0].second()); + assertEquals("2.2", 1, operands.size()); + assertEquals("2.4", one, operands.get(0).first()); + assertEquals("2.5", three, operands.get(0).second()); } public void test248468c() { String id = "myBundle"; - IUpdateDescriptor update = createUpdateDescriptor(id, new Version("1.0.0")); - IInstallableUnit one = createIU(id, new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update, null); - update = createUpdateDescriptor(id, new Version("2.0.0")); - IInstallableUnit two = createIU(id, new Version("2.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update, null); + IUpdateDescriptor update = createUpdateDescriptor(id, Version.create("1.0.0")); + IInstallableUnit one = createIU(id, Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update, null); + update = createUpdateDescriptor(id, Version.create("2.0.0")); + IInstallableUnit two = createIU(id, Version.create("2.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update, null); - IUpdateDescriptor update3 = MetadataFactory.createUpdateDescriptor(id, new VersionRange(new Version(2, 0, 0), true, new Version(3, 0, 0), false), IUpdateDescriptor.HIGH, "desc"); - // IUpdateDescriptor update3 = createUpdateDescriptor(id, new Version("3.0.0")); - IInstallableUnit three = createIU("anotherBundle", new Version("3.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update3, null); + IUpdateDescriptor update3 = MetadataFactory.createUpdateDescriptor(id, new VersionRange(Version.createOSGi(2, 0, 0), true, Version.createOSGi(3, 0, 0), false), IUpdateDescriptor.HIGH, "desc"); + // IUpdateDescriptor update3 = createUpdateDescriptor(id, Version.create("3.0.0")); + IInstallableUnit three = createIU("anotherBundle", Version.create("3.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update3, null); Collection from = new ArrayList(); from.add(MetadataFactory.createResolvedInstallableUnit(one, new IInstallableUnitFragment[0])); @@ -293,26 +293,26 @@ public class OperationGenerationTest extends AbstractProvisioningTest { to.add(MetadataFactory.createResolvedInstallableUnit(two, new IInstallableUnitFragment[0])); to.add(MetadataFactory.createResolvedInstallableUnit(three, new IInstallableUnitFragment[0])); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); //Two is already in the system therefore it will not be in the operands - for (int i = 0; i < operands.length; i++) { - assertNotSame("2.0", two, operands[i].first()); - assertNotSame("2.1", two, operands[i].second()); + for (int i = 0; i < operands.size(); i++) { + assertNotSame("2.0", two, operands.get(i).first()); + assertNotSame("2.1", two, operands.get(i).second()); } //We install three and uninstall one - assertEquals("2.2", 2, operands.length); - assertNull("2.3", operands[0].first()); - assertEquals("2.4", three, operands[0].second()); - assertEquals("2.5", one, operands[1].first()); - assertNull("2.6", operands[1].second()); + assertEquals("2.2", 2, operands.size()); + assertNull("2.3", operands.get(0).first()); + assertEquals("2.4", three, operands.get(0).second()); + assertEquals("2.5", one, operands.get(1).first()); + assertNull("2.6", operands.get(1).second()); } public void test248468() { String id = "myBundle"; - IUpdateDescriptor update = createUpdateDescriptor(id, new Version("1.0.0")); - IInstallableUnit one = createIU(id, new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update, null); - update = createUpdateDescriptor(id, new Version("2.0.0")); - IInstallableUnit two = createIU(id, new Version("2.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update, null); + IUpdateDescriptor update = createUpdateDescriptor(id, Version.create("1.0.0")); + IInstallableUnit one = createIU(id, Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update, null); + update = createUpdateDescriptor(id, Version.create("2.0.0")); + IInstallableUnit two = createIU(id, Version.create("2.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, update, null); Collection from = new ArrayList(); from.add(MetadataFactory.createResolvedInstallableUnit(one, new IInstallableUnitFragment[0])); @@ -321,20 +321,20 @@ public class OperationGenerationTest extends AbstractProvisioningTest { Collection to = new ArrayList(); to.add(MetadataFactory.createResolvedInstallableUnit(two, new IInstallableUnitFragment[0])); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); - assertEquals("1.0", 1, operands.length); - assertEquals("1.1", one, operands[0].first()); - assertNull("1.2", operands[0].second()); + List operands = new OperationGenerator().generateOperation(from, to); + assertEquals("1.0", 1, operands.size()); + assertEquals("1.1", one, operands.get(0).first()); + assertNull("1.2", operands.get(0).second()); } public void testConfigurationChange1() { String id = "myBundle"; String cuId = "cu"; - IInstallableUnit anIU = createIU(id, new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); - IInstallableUnit anotherIU = createIU("misc", new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); - IInstallableUnit anotherIU2 = createIU("misc2", new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); - IInstallableUnitFragment cu1 = createIUFragment(anIU, cuId, new Version("1.0.0")); - IInstallableUnitFragment cu2 = createIUFragment(anIU, cuId, new Version("2.0.0")); + IInstallableUnit anIU = createIU(id, Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); + IInstallableUnit anotherIU = createIU("misc", Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); + IInstallableUnit anotherIU2 = createIU("misc2", Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); + IInstallableUnitFragment cu1 = createIUFragment(anIU, cuId, Version.create("1.0.0")); + IInstallableUnitFragment cu2 = createIUFragment(anIU, cuId, Version.create("2.0.0")); Collection from = new ArrayList(); ResolvedInstallableUnit fromResolved = (ResolvedInstallableUnit) MetadataFactory.createResolvedInstallableUnit(anIU, new IInstallableUnitFragment[] {cu1}); @@ -346,16 +346,17 @@ public class OperationGenerationTest extends AbstractProvisioningTest { to.add(toResolved); to.add(MetadataFactory.createResolvedInstallableUnit(anotherIU2, new IInstallableUnitFragment[0])); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); - assertEquals("1.0", 3, operands.length); + assertEquals("1.0", 3, operands.size()); assertContainsConfigurationChange("2.0", operands); assertContainsInstallableUnitOperand("3.0", operands, new InstallableUnitOperand(fromResolved, toResolved)); } - private void assertContainsInstallableUnitOperand(String message, InstallableUnitOperand[] operands, InstallableUnitOperand operand) { - for (int i = 0; i < operands.length; i++) { - if (operands[i].first() != null && operands[i].first().equals(operand.first()) && operands[i].second() != null && operands[i].second().equals(operand.second())) + private void assertContainsInstallableUnitOperand(String message, List operands, InstallableUnitOperand operand) { + for (int i = 0; i < operands.size(); i++) { + InstallableUnitOperand cmp = operands.get(i); + if (cmp.first() != null && cmp.first().equals(operand.first()) && cmp.second() != null && cmp.second().equals(operand.second())) return; } fail(message); @@ -364,8 +365,8 @@ public class OperationGenerationTest extends AbstractProvisioningTest { public void testConfigurationChange2() { String id = "myBundle"; String cuId = "cu"; - IInstallableUnit anIU = createIU(id, new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); - IInstallableUnitFragment cu2 = createIUFragment(anIU, cuId, new Version("2.0.0")); + IInstallableUnit anIU = createIU(id, Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); + IInstallableUnitFragment cu2 = createIUFragment(anIU, cuId, Version.create("2.0.0")); Collection from = new ArrayList(); ResolvedInstallableUnit fromResolved = (ResolvedInstallableUnit) MetadataFactory.createResolvedInstallableUnit(anIU, new IInstallableUnitFragment[0]); @@ -375,17 +376,17 @@ public class OperationGenerationTest extends AbstractProvisioningTest { IInstallableUnit toResolved = MetadataFactory.createResolvedInstallableUnit(anIU, new IInstallableUnitFragment[] {cu2}); to.add(toResolved); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); - assertEquals("1.0", 1, operands.length); + assertEquals("1.0", 1, operands.size()); assertContainsInstallableUnitOperand("3.0", operands, new InstallableUnitOperand(fromResolved, toResolved)); } public void testConfigurationChange3() { String id = "myBundle"; String cuId = "cu"; - IInstallableUnit anIU = createIU(id, new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); - IInstallableUnitFragment cu2 = createIUFragment(anIU, cuId, new Version("2.0.0")); + IInstallableUnit anIU = createIU(id, Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); + IInstallableUnitFragment cu2 = createIUFragment(anIU, cuId, Version.create("2.0.0")); Collection from = new ArrayList(); ResolvedInstallableUnit fromResolved = (ResolvedInstallableUnit) MetadataFactory.createResolvedInstallableUnit(anIU, new IInstallableUnitFragment[] {cu2}); @@ -395,17 +396,17 @@ public class OperationGenerationTest extends AbstractProvisioningTest { IInstallableUnit toResolved = MetadataFactory.createResolvedInstallableUnit(anIU, new IInstallableUnitFragment[0]); to.add(toResolved); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); - assertEquals("1.0", 1, operands.length); + assertEquals("1.0", 1, operands.size()); assertContainsInstallableUnitOperand("3.0", operands, new InstallableUnitOperand(fromResolved, toResolved)); } public void testConfigurationChange4() { String id = "myBundle"; String cuId = "cu"; - IInstallableUnit anIU = createIU(id, new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); - IInstallableUnitFragment cu2 = createIUFragment(anIU, cuId, new Version("2.0.0")); + IInstallableUnit anIU = createIU(id, Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); + IInstallableUnitFragment cu2 = createIUFragment(anIU, cuId, Version.create("2.0.0")); Collection from = new ArrayList(); ResolvedInstallableUnit fromResolved = (ResolvedInstallableUnit) MetadataFactory.createResolvedInstallableUnit(anIU, new IInstallableUnitFragment[] {cu2}); @@ -415,17 +416,17 @@ public class OperationGenerationTest extends AbstractProvisioningTest { IInstallableUnit toResolved = MetadataFactory.createResolvedInstallableUnit(anIU, new IInstallableUnitFragment[] {cu2}); to.add(toResolved); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); - assertEquals("1.0", 0, operands.length); + assertEquals("1.0", 0, operands.size()); } public void testConfigurationChange5() { String id = "myBundle"; String cuId = "cu"; - IInstallableUnit anIU = createIU(id, new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); - IInstallableUnitFragment cu2 = createIUFragment(anIU, cuId, new Version("2.0.0")); - IInstallableUnitFragment cu1 = createIUFragment(anIU, cuId, new Version("1.0.0")); + IInstallableUnit anIU = createIU(id, Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); + IInstallableUnitFragment cu2 = createIUFragment(anIU, cuId, Version.create("2.0.0")); + IInstallableUnitFragment cu1 = createIUFragment(anIU, cuId, Version.create("1.0.0")); Collection from = new ArrayList(); ResolvedInstallableUnit fromResolved = (ResolvedInstallableUnit) MetadataFactory.createResolvedInstallableUnit(anIU, new IInstallableUnitFragment[] {cu1, cu2}); @@ -435,18 +436,18 @@ public class OperationGenerationTest extends AbstractProvisioningTest { IInstallableUnit toResolved = MetadataFactory.createResolvedInstallableUnit(anIU, new IInstallableUnitFragment[] {cu2, cu1}); to.add(toResolved); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); - assertEquals("1.0", 0, operands.length); + assertEquals("1.0", 0, operands.size()); } public void testConfigurationChange6() { String id = "myBundle"; String cuId = "cu"; - IInstallableUnit anIU = createIU(id, new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); - IInstallableUnitFragment cu2 = createIUFragment(anIU, cuId, new Version("2.0.0")); - IInstallableUnitFragment cu1 = createIUFragment(anIU, cuId, new Version("1.0.0")); - IInstallableUnitFragment cu3 = createIUFragment(anIU, cuId, new Version("3.0.0")); + IInstallableUnit anIU = createIU(id, Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); + IInstallableUnitFragment cu2 = createIUFragment(anIU, cuId, Version.create("2.0.0")); + IInstallableUnitFragment cu1 = createIUFragment(anIU, cuId, Version.create("1.0.0")); + IInstallableUnitFragment cu3 = createIUFragment(anIU, cuId, Version.create("3.0.0")); Collection from = new ArrayList(); ResolvedInstallableUnit fromResolved = (ResolvedInstallableUnit) MetadataFactory.createResolvedInstallableUnit(anIU, new IInstallableUnitFragment[] {cu1, cu2}); @@ -456,9 +457,9 @@ public class OperationGenerationTest extends AbstractProvisioningTest { IInstallableUnit toResolved = MetadataFactory.createResolvedInstallableUnit(anIU, new IInstallableUnitFragment[] {cu1, cu3}); to.add(toResolved); - InstallableUnitOperand[] operands = new OperationGenerator().generateOperation(from, to); + List operands = new OperationGenerator().generateOperation(from, to); - assertEquals("1.0", 1, operands.length); + assertEquals("1.0", 1, operands.size()); assertContainsInstallableUnitOperand("3.0", operands, new InstallableUnitOperand(fromResolved, toResolved)); } @@ -470,9 +471,10 @@ public class OperationGenerationTest extends AbstractProvisioningTest { fail(message + "Can't find " + expected); } - public void assertContainsConfigurationChange(String message, InstallableUnitOperand[] ops) { - for (int i = 0; i < ops.length; i++) { - if (ops[i].first() != null && ops[i].first().equals(ops[i].second())) { + public void assertContainsConfigurationChange(String message, List ops) { + for (int i = 0; i < ops.size(); i++) { + InstallableUnitOperand op = ops.get(i); + if (op.first() != null && op.first().equals(op.second())) { return; } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/OracleTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/OracleTest.java index a947717e6..40088c1a0 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/OracleTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/OracleTest.java @@ -8,15 +8,15 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.director; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IDirector; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class OracleTest extends AbstractProvisioningTest { @@ -31,18 +31,18 @@ public class OracleTest extends AbstractProvisioningTest { IProfile profile; protected void setUp() throws Exception { - IRequiredCapability[] requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 2.0.0)"), null); + IRequiredCapability[] requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 2.0.0)")); a1 = createIU("A", requires, true); - requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "D", new VersionRange("[1.0.0, 3.0.0)"), null); + requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "D", new VersionRange("[1.0.0, 3.0.0)")); c1 = createIU("C", requires, true); d1 = createIU("D", DEFAULT_VERSION, true); - requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "D", new VersionRange("[2.0.0, 3.0.0)"), null); + requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "D", new VersionRange("[2.0.0, 3.0.0)")); b1 = createIU("B", requires, true); - d2 = createIU("D", new Version(2, 0, 0), true); + d2 = createIU("D", Version.createOSGi(2, 0, 0), true); createTestMetdataRepository(new IInstallableUnit[] {a1, c1, d1, b1}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/OracleTest2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/OracleTest2.java index 430fadc9b..11aeff973 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/OracleTest2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/OracleTest2.java @@ -8,15 +8,18 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.director; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IDirector; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IUpdateDescriptor; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class OracleTest2 extends AbstractProvisioningTest { @@ -30,16 +33,16 @@ public class OracleTest2 extends AbstractProvisioningTest { IProfile profile; protected void setUp() throws Exception { - IRequiredCapability[] requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 2.0.0)"), null); + IRequiredCapability[] requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 2.0.0)")); a1 = createIU("A", requires, true); c1 = createIU("C", DEFAULT_VERSION, true); - requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[2.0.0, 3.0.0)"), null); + requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[2.0.0, 3.0.0)")); InstallableUnitDescription desc = new MetadataFactory.InstallableUnitDescription(); desc.setRequiredCapabilities(requires); desc.setId("A"); - desc.setVersion(new Version(2, 0, 0)); + desc.setVersion(Version.createOSGi(2, 0, 0)); desc.setSingleton(true); desc.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor("A", new VersionRange("[1.0.0, 2.3.0)"), IUpdateDescriptor.NORMAL, null)); @@ -49,7 +52,7 @@ public class OracleTest2 extends AbstractProvisioningTest { InstallableUnitDescription desc2 = new MetadataFactory.InstallableUnitDescription(); desc2.setId("C"); - desc2.setVersion(new Version(2, 0, 0)); + desc2.setVersion(Version.createOSGi(2, 0, 0)); desc2.setSingleton(true); desc2.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor("C", new VersionRange("[1.0.0, 2.3.0)"), IUpdateDescriptor.NORMAL, null)); c2 = MetadataFactory.createInstallableUnit(desc2); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/ReplacePlanTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/ReplacePlanTest.java index ed6f1d617..9efa4f8e3 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/ReplacePlanTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/ReplacePlanTest.java @@ -10,14 +10,14 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.director; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** @@ -40,8 +40,8 @@ public class ReplacePlanTest extends AbstractProvisioningTest { protected void setUp() throws Exception { //base IU that others require f1 = createIU("f1", DEFAULT_VERSION, true); - f1_1 = createIU("f1", new Version(1, 1, 0), true); - f1_4 = createIU("f1", new Version(1, 4, 0), true); + f1_1 = createIU("f1", Version.createOSGi(1, 1, 0), true); + f1_4 = createIU("f1", Version.createOSGi(1, 4, 0), true); //fragments of base IU frag1 = createIUFragment(f1, "frag1", f1.getVersion()); @@ -49,10 +49,10 @@ public class ReplacePlanTest extends AbstractProvisioningTest { frag1_4 = createIUFragment(f1, "frag1", f1_4.getVersion()); //IUs that require base IU - IRequiredCapability[] requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "f1", new VersionRange("[1.0.0, 1.3.0)"), null); + IRequiredCapability[] requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "f1", new VersionRange("[1.0.0, 1.3.0)")); fa = createIU("fa", requires, false); - requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "f1", new VersionRange("[1.0.0, 1.4.0)"), null); - fap = createIU("fa", new Version(1, 1, 0), requires, NO_PROPERTIES, false); + requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "f1", new VersionRange("[1.0.0, 1.4.0)")); + fap = createIU("fa", Version.createOSGi(1, 1, 0), requires, NO_PROPERTIES, false); createTestMetdataRepository(new IInstallableUnit[] {f1, fa, frag1}); @@ -73,10 +73,10 @@ public class ReplacePlanTest extends AbstractProvisioningTest { ProfileChangeRequest request = new ProfileChangeRequest(profile); request.removeInstallableUnits(oldUnits); request.addInstallableUnits(newUnits); - ProvisioningPlan plan = planner.getProvisioningPlan(request, new ProvisioningContext(), null); + IProvisioningPlan plan = planner.getProvisioningPlan(request, new ProvisioningContext(), null); assertTrue("1.0", plan.getStatus().isOK()); assertProfileContainsAll("1.1", profile, oldUnits); - IStatus result = createEngine().perform(profile, new DefaultPhaseSet(), plan.getOperands(), null, null); + IStatus result = createEngine().perform(plan, null); assertTrue("1.2", result.isOK()); assertProfileContainsAll("1.3", profile, newUnits); } @@ -86,7 +86,7 @@ public class ReplacePlanTest extends AbstractProvisioningTest { ProfileChangeRequest request = new ProfileChangeRequest(profile); request.removeInstallableUnits(new IInstallableUnit[] {frag1}); request.addInstallableUnits(new IInstallableUnit[] {frag1_4}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, new ProvisioningContext(), null); + IProvisioningPlan plan = planner.getProvisioningPlan(request, new ProvisioningContext(), null); assertTrue("1.0", plan.getStatus().isOK()); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/RollbackTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/RollbackTest.java index 98cd52f53..5fdd4e937 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/RollbackTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/RollbackTest.java @@ -10,25 +10,25 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.director; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; -import java.net.*; -import java.util.ArrayList; -import java.util.List; +import java.net.URI; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.director.DirectorActivator; -import org.eclipse.equinox.internal.provisional.p2.core.*; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IDirector; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; @@ -49,8 +49,8 @@ public class RollbackTest extends AbstractProvisioningTest { c1 = createIU("C", DEFAULT_VERSION, true); IRequiredCapability[] req = new IRequiredCapability[1]; - req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, true); - d1 = createIU("D", new Version("1.0.0"), req); + req[0] = (IRequiredCapability) MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, true); + d1 = createIU("D", Version.create("1.0.0"), req); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, c1, d1}); @@ -67,21 +67,13 @@ public class RollbackTest extends AbstractProvisioningTest { } private IMetadataRepository getRollbackRepository() throws ProvisionException { - try { - IMetadataRepositoryManager repoMan = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.class.getName()); - URL location = ((AgentLocation) ServiceHelper.getService(DirectorActivator.context, AgentLocation.class.getName())).getDataArea(DirectorActivator.PI_DIRECTOR); - return repoMan.loadRepository(URIUtil.toURI(new URL(location, "rollback")), null); - } catch (MalformedURLException e) { - fail("0.02", e); - return null; - } catch (URISyntaxException e) { - fail("0.03", e); - return null; - } + IMetadataRepositoryManager repoMan = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); + URI location = ((IAgentLocation) ServiceHelper.getService(DirectorActivator.context, IAgentLocation.class.getName())).getDataArea(DirectorActivator.PI_DIRECTOR); + return repoMan.loadRepository(URIUtil.append(location, "rollback"), null); } public void testRollbackProfileProperties() { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = getProfileRegistry(); assertEquals(1, profileRegistry.listProfileTimestamps(profile.getProfileId()).length); ProfileChangeRequest request1 = new ProfileChangeRequest(profile); @@ -115,7 +107,7 @@ public class RollbackTest extends AbstractProvisioningTest { } public void testRollbackIUs() { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = getProfileRegistry(); assertEquals(1, profileRegistry.listProfileTimestamps(profile.getProfileId()).length); ProfileChangeRequest request1 = new ProfileChangeRequest(profile); @@ -124,9 +116,9 @@ public class RollbackTest extends AbstractProvisioningTest { IStatus status = director.provision(request1, null, new NullProgressMonitor()); assertEquals("1.0", IStatus.OK, status.getCode()); - List profileIUs = new ArrayList(profile.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection()); - assertTrue("2.0", profileIUs.contains(a1)); - assertTrue("3.0", profileIUs.contains(b1)); + IQueryResult profileIUs = profile.query(InstallableUnitQuery.ANY, null); + assertContains("2.0", profileIUs, a1); + assertContains("3.0", profileIUs, b1); assertEquals(2, profileRegistry.listProfileTimestamps(profile.getProfileId()).length); @@ -136,10 +128,10 @@ public class RollbackTest extends AbstractProvisioningTest { status = director.provision(request2, null, new NullProgressMonitor()); assertEquals("5.0", IStatus.OK, status.getCode()); - profileIUs = new ArrayList(profile.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection()); - assertFalse("6.0", profileIUs.contains(a1)); - assertTrue("7.0", profileIUs.contains(b1)); - assertTrue("8.0", profileIUs.contains(c1)); + profileIUs = profile.query(InstallableUnitQuery.ANY, null); + assertNotContains("6.0", profileIUs, a1); + assertContains("7.0", profileIUs, b1); + assertContains("8.0", profileIUs, c1); assertEquals(3, profileRegistry.listProfileTimestamps(profile.getProfileId()).length); IProfile revertProfile = profileRegistry.getProfile(profile.getProfileId(), profileRegistry.listProfileTimestamps(profile.getProfileId())[1]); @@ -147,14 +139,14 @@ public class RollbackTest extends AbstractProvisioningTest { status = director.revert(profile, revertProfile, new ProvisioningContext(), new NullProgressMonitor()); assertEquals("10.0", IStatus.OK, status.getCode()); - profileIUs = new ArrayList(profile.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection()); - assertTrue("11.0", profileIUs.contains(a1)); - assertTrue("12.0", profileIUs.contains(b1)); - assertFalse("13.0", profileIUs.contains(c1)); + profileIUs = profile.query(InstallableUnitQuery.ANY, null); + assertContains("11.0", profileIUs, a1); + assertContains("12.0", profileIUs, b1); + assertNotContains("13.0", profileIUs, c1); } public void testRollbackIUProfileProperties() { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = getProfileRegistry(); assertEquals(1, profileRegistry.listProfileTimestamps(profile.getProfileId()).length); ProfileChangeRequest request1 = new ProfileChangeRequest(profile); @@ -189,7 +181,7 @@ public class RollbackTest extends AbstractProvisioningTest { } public void testRollbackDependentIUProfileProperties() { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = getProfileRegistry(); assertEquals(1, profileRegistry.listProfileTimestamps(profile.getProfileId()).length); ProfileChangeRequest request1 = new ProfileChangeRequest(profile); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/SingletonTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/SingletonTest.java index a21e834de..d066a3d16 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/SingletonTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/SingletonTest.java @@ -10,14 +10,14 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.director; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.provisional.p2.director.IDirector; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SingletonTest extends AbstractProvisioningTest { @@ -34,17 +34,17 @@ public class SingletonTest extends AbstractProvisioningTest { IProfile profile; protected void setUp() throws Exception { - f1 = createIU("f1", new Version(1, 0, 0), true); + f1 = createIU("f1", Version.createOSGi(1, 0, 0), true); - f1_1 = createIU("f1", new Version(1, 1, 0), true); + f1_1 = createIU("f1", Version.createOSGi(1, 1, 0), true); - f2 = createIU("f2", new Version(1, 0, 0), true); + f2 = createIU("f2", Version.createOSGi(1, 0, 0), true); - f2_1 = createIU("f2", new Version(1, 0, 1)); + f2_1 = createIU("f2", Version.createOSGi(1, 0, 1)); - junit38 = createIU("junit", new Version(3, 8, 1)); + junit38 = createIU("junit", Version.createOSGi(3, 8, 1)); - junit40 = createIU("junit", new Version(4, 0, 1)); + junit40 = createIU("junit", Version.createOSGi(4, 0, 1)); createTestMetdataRepository(new IInstallableUnit[] {f1, f1_1, junit38, junit40, f2, f2_1}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/UninstallTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/UninstallTest.java index 8360cd9ae..4758f3614 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/UninstallTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/UninstallTest.java @@ -12,8 +12,8 @@ package org.eclipse.equinox.p2.tests.director; import org.eclipse.equinox.internal.provisional.p2.director.IDirector; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class UninstallTest extends AbstractProvisioningTest { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/UpdateTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/UpdateTest.java index f2d224097..cb08ac8f5 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/UpdateTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/UpdateTest.java @@ -8,16 +8,15 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.director; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class UpdateTest extends AbstractProvisioningTest { @@ -34,15 +33,15 @@ public class UpdateTest extends AbstractProvisioningTest { protected void setUp() throws Exception { String f1Id = getName() + "f1"; f1 = createIU(f1Id, DEFAULT_VERSION, true); - f1_1 = createIU(f1Id, new Version(1, 1, 0), true); - f1_4 = createIU(f1Id, new Version(1, 4, 0), true); + f1_1 = createIU(f1Id, Version.createOSGi(1, 1, 0), true); + f1_4 = createIU(f1Id, Version.createOSGi(1, 4, 0), true); - IRequiredCapability[] requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, f1Id, new VersionRange("[1.0.0, 1.3.0)"), null); + IRequiredCapability[] requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, f1Id, new VersionRange("[1.0.0, 1.3.0)")); String faId = getName() + ".fa"; fa = createIU(faId, requires, false); - requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, f1Id, new VersionRange("[1.0.0, 1.4.0)"), null); - fap = createIU(faId, new Version(1, 1, 0), requires, NO_PROPERTIES, false); + requires = createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, f1Id, new VersionRange("[1.0.0, 1.4.0)")); + fap = createIU(faId, Version.createOSGi(1, 1, 0), requires, NO_PROPERTIES, false); createTestMetdataRepository(new IInstallableUnit[] {f1, fa}); @@ -59,7 +58,7 @@ public class UpdateTest extends AbstractProvisioningTest { public void testInstall() { ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {f1_1}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, new ProvisioningContext(), new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, new ProvisioningContext(), new NullProgressMonitor()); assertOK("1.0", plan.getStatus()); assertOK("1.1", director.provision(request, null, null)); request = new ProfileChangeRequest(profile); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/directorywatcher/ProfileSynchronizerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/directorywatcher/ProfileSynchronizerTest.java index 7df459def..a77f39e67 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/directorywatcher/ProfileSynchronizerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/directorywatcher/ProfileSynchronizerTest.java @@ -10,14 +10,14 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.directorywatcher; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import java.util.*; import junit.framework.Test; import junit.framework.TestSuite; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; /** * @since 1.0 @@ -113,7 +113,7 @@ public class ProfileSynchronizerTest extends AbstractDirectoryWatcherTest { IArtifactKey[] artifacts = watcher.getArtifactKeys(); assertEquals("3.0", 1, ius.length); assertEquals("3.1", "ccc", ius[0].getId()); - assertEquals("3.2", new Version("2.0.0"), ius[0].getVersion()); + assertEquals("3.2", Version.create("2.0.0"), ius[0].getVersion()); assertEquals("4.0", 1, artifacts.length); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/directorywatcher/RepositoryListenerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/directorywatcher/RepositoryListenerTest.java index 1f8dd7d7b..bf2e0a86b 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/directorywatcher/RepositoryListenerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/directorywatcher/RepositoryListenerTest.java @@ -11,11 +11,12 @@ package org.eclipse.equinox.p2.tests.directorywatcher; import java.io.File; +import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactDescriptor; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; public class RepositoryListenerTest extends AbstractDirectoryWatcherTest { @@ -33,11 +34,11 @@ public class RepositoryListenerTest extends AbstractDirectoryWatcherTest { return new TestSuite(RepositoryListenerTest.class); } - public static boolean isZipped(ITouchpointData[] data) { - if (data == null || data.length == 0) + public static boolean isZipped(List data) { + if (data == null || data.size() == 0) return false; - for (int i = 0; i < data.length; i++) { - if (data[i].getInstruction("zipped") != null) //$NON-NLS-1$ + for (int i = 0; i < data.size(); i++) { + if (data.get(i).getInstruction("zipped") != null) //$NON-NLS-1$ return true; } return false; @@ -135,7 +136,7 @@ public class RepositoryListenerTest extends AbstractDirectoryWatcherTest { IArtifactKey key = keys[i]; IArtifactDescriptor[] descriptors = watcher.getArtifactDescriptors(key); assertEquals("8.0", 1, descriptors.length); - ArtifactDescriptor descriptor = (ArtifactDescriptor) descriptors[0]; + SimpleArtifactDescriptor descriptor = (SimpleArtifactDescriptor) descriptors[0]; String isFolder = descriptor.getRepositoryProperty("artifact.folder"); if (Boolean.valueOf(isFolder).booleanValue()) { assertNull("9.0", directoryDescriptor); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/directorywatcher/TestRepositoryWatcher.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/directorywatcher/TestRepositoryWatcher.java index d9cfbb081..19f92dfbd 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/directorywatcher/TestRepositoryWatcher.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/directorywatcher/TestRepositoryWatcher.java @@ -11,16 +11,15 @@ package org.eclipse.equinox.p2.tests.directorywatcher; import java.io.File; -import java.util.Dictionary; import java.util.Hashtable; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; +import java.util.Map; import org.eclipse.equinox.internal.provisional.p2.directorywatcher.DirectoryWatcher; import org.eclipse.equinox.internal.provisional.p2.directorywatcher.RepositoryListener; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.BundleContext; @@ -37,7 +36,7 @@ class TestRepositoryWatcher extends DirectoryWatcher { */ public static TestRepositoryWatcher createWatcher(File folder) { RepositoryListener listener = new RepositoryListener(AbstractProvisioningTest.getUniqueString(), false); - Dictionary props = new Hashtable(); + Map props = new Hashtable(); props.put(DirectoryWatcher.DIR, folder.getAbsolutePath()); props.put(DirectoryWatcher.POLL, "500"); TestRepositoryWatcher result = new TestRepositoryWatcher(props, TestActivator.getContext()); @@ -48,7 +47,7 @@ class TestRepositoryWatcher extends DirectoryWatcher { /* * Constructor for the class. */ - private TestRepositoryWatcher(Dictionary props, BundleContext context) { + private TestRepositoryWatcher(Map props, BundleContext context) { super(props, context); } @@ -64,14 +63,15 @@ class TestRepositoryWatcher extends DirectoryWatcher { * Return the list of all the IUs known to the metadata repository this watcher's listener. */ public IInstallableUnit[] getInstallableUnits() { - return (IInstallableUnit[]) listener.getMetadataRepository().query(InstallableUnitQuery.ANY, new Collector(), null).toArray(IInstallableUnit.class); + return listener.getMetadataRepository().query(InstallableUnitQuery.ANY, null).toArray(IInstallableUnit.class); } /* * Return the list of artifact keys known to this listener's repository. */ public IArtifactKey[] getArtifactKeys() { - return listener.getArtifactRepository().getArtifactKeys(); + IQueryResult keys = listener.getArtifactRepository().query(ArtifactKeyQuery.ALL_KEYS, null); + return (IArtifactKey[]) keys.toArray(IArtifactKey.class); } /* diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ActionManagerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ActionManagerTest.java index 09a62ed29..2bdf4694d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ActionManagerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ActionManagerTest.java @@ -10,13 +10,13 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.engine; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.io.File; import java.net.MalformedURLException; import org.eclipse.equinox.internal.p2.engine.ActionManager; -import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.internal.provisional.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.Bundle; @@ -37,7 +37,7 @@ public class ActionManagerTest extends AbstractProvisioningTest { public void testGetTouchpointQualifiedActionId() { ActionManager manager = new ActionManager(); - assertNotNull(manager.getTouchpointQualifiedActionId("test", MetadataFactory.createTouchpointType("phaseTest", new Version("1")))); + assertNotNull(manager.getTouchpointQualifiedActionId("test", MetadataFactory.createTouchpointType("phaseTest", Version.create("1")))); } public void testGetActionWithVersion() { @@ -50,7 +50,8 @@ public class ActionManagerTest extends AbstractProvisioningTest { assertNotNull(manager.getAction("test1.test", null)); } - public void testDynamicAction() throws MalformedURLException, BundleException, InterruptedException { + // temporarily disabling this test until API is done + public void DISABLED_testDynamicAction() throws MalformedURLException, BundleException, InterruptedException { ActionManager manager = new ActionManager(); assertNull(manager.getAction("dummy.touchpointAndAction.dummy", new VersionRange("1.0.0"))); File dummy = getTestData("0.1", "/testData/engineTest/dummy.touchpointAndAction_1.0.0.jar"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/CertificateCheckerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/CertificateCheckerTest.java index 5e3d14e6f..466da3497 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/CertificateCheckerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/CertificateCheckerTest.java @@ -13,14 +13,12 @@ package org.eclipse.equinox.p2.tests.engine; import java.io.File; import java.io.IOException; import java.security.cert.Certificate; -import java.util.Hashtable; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.core.ProvisioningAgent; import org.eclipse.equinox.internal.p2.engine.EngineActivator; +import org.eclipse.equinox.internal.p2.engine.phases.CertificateChecker; import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI; -import org.eclipse.equinox.internal.provisional.p2.engine.CertificateChecker; -import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; -import org.eclipse.equinox.p2.tests.TestData; -import org.osgi.framework.ServiceRegistration; +import org.eclipse.equinox.p2.tests.*; /** * Tests for {@link CertificateChecker}. @@ -46,12 +44,16 @@ public class CertificateCheckerTest extends AbstractProvisioningTest { } CertificateChecker checker; - ServiceRegistration serviceReg; CertificateTestService serviceUI; File unsigned; + private ProvisioningAgent testAgent; protected void setUp() throws Exception { - checker = new CertificateChecker(); + serviceUI = new CertificateTestService(); + testAgent = new ProvisioningAgent(); + testAgent.registerService(IServiceUI.SERVICE_NAME, serviceUI); + testAgent.setBundleContext(TestActivator.getContext()); + checker = new CertificateChecker(testAgent); try { unsigned = TestData.getFile("CertificateChecker", "unsigned.jar"); } catch (IOException e) { @@ -59,17 +61,6 @@ public class CertificateCheckerTest extends AbstractProvisioningTest { } assertTrue("1.0", unsigned != null); assertTrue("1.0", unsigned.exists()); - // We need to ensure the test service has a higher ranking than - // anything registered by the SDK via DS. - serviceUI = new CertificateTestService(); - Hashtable properties = new Hashtable(1); - properties.put(org.osgi.framework.Constants.SERVICE_RANKING, new Integer(Integer.MAX_VALUE)); - serviceReg = EngineActivator.getContext().registerService(IServiceUI.class.getName(), serviceUI, properties); - } - - protected void tearDown() throws Exception { - if (serviceReg != null) - serviceReg.unregister(); } /** @@ -154,16 +145,10 @@ public class CertificateCheckerTest extends AbstractProvisioningTest { */ public void testBug291049() { try { - - // Intentionally unregister our service so that we get whatever the default (or null) service is - // in an SDK configuration. - if (serviceReg != null) { - serviceReg.unregister(); - serviceReg = null; - } + // Intentionally replace our service with a null service + testAgent.registerService(IServiceUI.SERVICE_NAME, null); checker.add(unsigned); // TODO need to add some untrusted files here, too. To prove that we treated them as trusted temporarily - System.getProperties().setProperty(EngineActivator.PROP_UNSIGNED_POLICY, EngineActivator.UNSIGNED_PROMPT); IStatus result = checker.start(); assertTrue("1.0", result.isOK()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/DownloadManagerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/DownloadManagerTest.java index 37fde9fd3..cc89dbf17 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/DownloadManagerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/DownloadManagerTest.java @@ -17,9 +17,9 @@ import junit.framework.TestSuite; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.engine.DownloadManager; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRequest; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** @@ -34,7 +34,7 @@ public class DownloadManagerTest extends AbstractProvisioningTest { * Tests invocation of DownloadManager when there is nothing to download. */ public void testEmpty() { - DownloadManager manager = new DownloadManager(null); + DownloadManager manager = createDownloadManager(null); IStatus result = manager.start(null); assertTrue("1.0", result.isOK()); } @@ -44,7 +44,7 @@ public class DownloadManagerTest extends AbstractProvisioningTest { */ public void testEmptyWithContext() { ProvisioningContext context = new ProvisioningContext(); - DownloadManager manager = new DownloadManager(context); + DownloadManager manager = createDownloadManager(context); IStatus result = manager.start(null); assertTrue("1.0", result.isOK()); } @@ -54,7 +54,7 @@ public class DownloadManagerTest extends AbstractProvisioningTest { */ public void testAddNullArtifactRequest() { ProvisioningContext context = new ProvisioningContext(); - DownloadManager manager = new DownloadManager(context); + DownloadManager manager = createDownloadManager(context); try { manager.add((IArtifactRequest) null); } catch (RuntimeException e) { @@ -65,7 +65,7 @@ public class DownloadManagerTest extends AbstractProvisioningTest { public void testAddNullArtifactRequestArray() { ProvisioningContext context = new ProvisioningContext(); - DownloadManager manager = new DownloadManager(context); + DownloadManager manager = createDownloadManager(context); try { manager.add((IArtifactRequest[]) null); } catch (RuntimeException e) { @@ -76,7 +76,7 @@ public class DownloadManagerTest extends AbstractProvisioningTest { public void testAddEmptyArtifactRequestArray() { ProvisioningContext context = new ProvisioningContext(); - DownloadManager manager = new DownloadManager(context); + DownloadManager manager = createDownloadManager(context); manager.add(new IArtifactRequest[0]); IStatus result = manager.start(null); assertTrue("1.0", result.isOK()); @@ -84,7 +84,7 @@ public class DownloadManagerTest extends AbstractProvisioningTest { public void testAddArtifactRequestArrayContainingNull() { ProvisioningContext context = new ProvisioningContext(); - DownloadManager manager = new DownloadManager(context); + DownloadManager manager = createDownloadManager(context); try { IArtifactRequest[] requests = new IArtifactRequest[] {null}; manager.add(requests); @@ -96,7 +96,7 @@ public class DownloadManagerTest extends AbstractProvisioningTest { public void testAddArtifactRequest() { ProvisioningContext context = new ProvisioningContext(); - DownloadManager manager = new DownloadManager(context); + DownloadManager manager = createDownloadManager(context); IArtifactRequest request = createArtifactRequest(); manager.add(request); @@ -108,7 +108,7 @@ public class DownloadManagerTest extends AbstractProvisioningTest { public void testContext() { ProvisioningContext context = new ProvisioningContext(); context.setArtifactRepositories(new URI[0]); - DownloadManager manager = new DownloadManager(context); + DownloadManager manager = createDownloadManager(context); IArtifactRequest request = createArtifactRequest(); manager.add(request); @@ -119,7 +119,7 @@ public class DownloadManagerTest extends AbstractProvisioningTest { public void testAddArtifactRequestArray() { ProvisioningContext context = new ProvisioningContext(); - DownloadManager manager = new DownloadManager(context); + DownloadManager manager = createDownloadManager(context); IArtifactRequest[] requests = new IArtifactRequest[] {createArtifactRequest()}; manager.add(requests); @@ -144,7 +144,7 @@ public class DownloadManagerTest extends AbstractProvisioningTest { public void testEmptyArtifactRepositoryListContext() { ProvisioningContext context = new ProvisioningContext(); context.setArtifactRepositories(new URI[0]); - DownloadManager manager = new DownloadManager(context); + DownloadManager manager = createDownloadManager(context); IArtifactRequest[] requests = new IArtifactRequest[] {createArtifactRequest()}; manager.add(requests); @@ -163,7 +163,7 @@ public class DownloadManagerTest extends AbstractProvisioningTest { } context.setArtifactRepositories(artifactRepos); - DownloadManager manager = new DownloadManager(context); + DownloadManager manager = createDownloadManager(context); IArtifactRequest[] requests = new IArtifactRequest[] {createArtifactRequest()}; manager.add(requests); @@ -182,7 +182,7 @@ public class DownloadManagerTest extends AbstractProvisioningTest { } context.setArtifactRepositories(artifactRepos); - DownloadManager manager = new DownloadManager(context); + DownloadManager manager = createDownloadManager(context); IArtifactRequest[] requests = new IArtifactRequest[] {createArtifactRequest()}; manager.add(requests); @@ -201,11 +201,15 @@ public class DownloadManagerTest extends AbstractProvisioningTest { } context.setArtifactRepositories(artifactRepos); - DownloadManager manager = new DownloadManager(context); + DownloadManager manager = createDownloadManager(context); IArtifactRequest[] requests = new IArtifactRequest[] {createArtifactRequest()}; manager.add(requests); IStatus result = manager.start(null); assertTrue("1.0", result.isOK()); } + + private DownloadManager createDownloadManager(ProvisioningContext context) { + return new DownloadManager(context, getArtifactRepositoryManager()); + } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/EngineTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/EngineTest.java index b82177bb7..96349ca5e 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/EngineTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/EngineTest.java @@ -10,15 +10,23 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.engine; +import org.eclipse.equinox.p2.metadata.Version; + import java.io.File; import java.util.*; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.engine.phases.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.p2.engine.*; +import org.eclipse.equinox.internal.p2.engine.phases.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitFragmentDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IInstallableUnitFragment; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.Collector; +import org.eclipse.equinox.p2.query.IQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.ServiceReference; @@ -64,7 +72,7 @@ public class EngineTest extends AbstractProvisioningTest { return super.initializePhase(monitor, profile, parameters); } - protected ProvisioningAction[] getActions(Operand operand) { + protected List getActions(Operand operand) { return null; } @@ -83,7 +91,7 @@ public class EngineTest extends AbstractProvisioningTest { throw new NullPointerException(); } - protected ProvisioningAction[] getActions(Operand operand) { + protected List getActions(Operand operand) { return null; } } @@ -97,7 +105,7 @@ public class EngineTest extends AbstractProvisioningTest { this(false); } - protected ProvisioningAction[] getActions(Operand operand) { + protected List getActions(Operand operand) { ProvisioningAction action = new ProvisioningAction() { public IStatus undo(Map parameters) { @@ -108,7 +116,7 @@ public class EngineTest extends AbstractProvisioningTest { throw new NullPointerException(); } }; - return new ProvisioningAction[] {action}; + return Collections.singletonList(action); } } @@ -165,10 +173,9 @@ public class EngineTest extends AbstractProvisioningTest { public void testNullProfile() { IProfile profile = null; - PhaseSet phaseSet = new DefaultPhaseSet(); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {}; try { - engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); } catch (IllegalArgumentException expected) { return; } @@ -181,32 +188,89 @@ public class EngineTest extends AbstractProvisioningTest { PhaseSet phaseSet = null; InstallableUnitOperand[] operands = new InstallableUnitOperand[] {}; try { - engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); } catch (IllegalArgumentException expected) { return; } fail(); } - public void testNullOperands() { + public void testNullPlan() { - IProfile profile = createProfile("test"); - PhaseSet phaseSet = new DefaultPhaseSet(); - InstallableUnitOperand[] operands = null; try { - engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + engine.perform(null, new NullProgressMonitor()); fail(); - } catch (IllegalArgumentException expected) { + } catch (RuntimeException expected) { + //expected + } + } + + /* + * Tests for {@link IEngine#createPhaseSetExcluding}. + */ + public void testCreatePhaseSetExcluding() { + //null argument + IPhaseSet set = engine.createPhaseSetExcluding(null); + assertEquals("1.0", 7, set.getPhaseIds().length); + + //empty argument + set = engine.createPhaseSetExcluding(new String[0]); + assertEquals("2.0", 7, set.getPhaseIds().length); + + //bogus argument + set = engine.createPhaseSetExcluding(new String[] {"blort"}); + assertEquals("3.0", 7, set.getPhaseIds().length); + + //valid argument + set = engine.createPhaseSetExcluding(new String[] {IPhaseSet.PHASE_CHECK_TRUST}); + final String[] phases = set.getPhaseIds(); + assertEquals("4.0", 6, phases.length); + for (int i = 0; i < phases.length; i++) + if (phases[i].equals(IPhaseSet.PHASE_CHECK_TRUST)) + fail("4.1." + i); + + } + + /* + * Tests for {@link IEngine#createPhaseSetIncluding}. + */ + public void testCreatePhaseSetIncluding() { + //null argument + try { + engine.createPhaseSetIncluding(null); + fail("1.0"); + } catch (RuntimeException e) { //expected } + //empty argument + IPhaseSet set = engine.createPhaseSetIncluding(new String[0]); + assertNotNull("2.0", set); + assertEquals("2.1", 0, set.getPhaseIds().length); + + //unknown argument + set = engine.createPhaseSetIncluding(new String[] {"blort", "not a phase", "bad input"}); + assertNotNull("3.0", set); + assertEquals("3.1", 0, set.getPhaseIds().length); + + //one valid phase + set = engine.createPhaseSetIncluding(new String[] {IPhaseSet.PHASE_COLLECT}); + assertNotNull("4.0", set); + assertEquals("4.1", 1, set.getPhaseIds().length); + assertEquals("4.2", IPhaseSet.PHASE_COLLECT, set.getPhaseIds()[0]); + + //one valid phase and one bogus + set = engine.createPhaseSetIncluding(new String[] {IPhaseSet.PHASE_COLLECT, "bogus"}); + assertNotNull("4.0", set); + assertEquals("4.1", 1, set.getPhaseIds().length); + assertEquals("4.2", IPhaseSet.PHASE_COLLECT, set.getPhaseIds()[0]); + } public void testEmptyOperands() { IProfile profile = createProfile("test"); - PhaseSet phaseSet = new DefaultPhaseSet(); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {}; - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); assertTrue(result.isOK()); } @@ -219,7 +283,7 @@ public class EngineTest extends AbstractProvisioningTest { InstallableUnitOperand op = new InstallableUnitOperand(createResolvedIU(createIU("name")), null); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {op}; - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); assertTrue(result.isOK()); } @@ -235,7 +299,6 @@ public class EngineTest extends AbstractProvisioningTest { public void testPerformPropertyInstallUninstall() { IProfile profile = createProfile("testPerformPropertyInstallUninstall"); - PhaseSet phaseSet = new DefaultPhaseSet(); PropertyOperand propOp = new PropertyOperand("test", null, "test"); IInstallableUnit testIU = createResolvedIU(createIU("test")); @@ -243,7 +306,7 @@ public class EngineTest extends AbstractProvisioningTest { InstallableUnitPropertyOperand iuPropOp = new InstallableUnitPropertyOperand(testIU, "test", null, "test"); Operand[] operands = new Operand[] {propOp, iuOp, iuPropOp}; - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); assertTrue(result.isOK()); assertEquals("test", profile.getProperty("test")); assertEquals("test", profile.getInstallableUnitProperty(testIU, "test")); @@ -251,7 +314,7 @@ public class EngineTest extends AbstractProvisioningTest { PropertyOperand uninstallPropOp = new PropertyOperand("test", "test", null); InstallableUnitPropertyOperand uninstallIuPropOp = new InstallableUnitPropertyOperand(testIU, "test", "test", null); operands = new Operand[] {uninstallPropOp, uninstallIuPropOp}; - result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + result = engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); assertTrue(result.isOK()); assertNull("test", profile.getProperty("test")); assertNull("test", profile.getInstallableUnitProperty(testIU, "test")); @@ -262,18 +325,17 @@ public class EngineTest extends AbstractProvisioningTest { Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath()); - IProfile profile = createProfile("testPerformSizing", null, properties); + IProfile profile = createProfile("testPerformSizing", properties); for (Iterator it = getInstallableUnits(profile); it.hasNext();) { - PhaseSet phaseSet = new DefaultPhaseSet(); IInstallableUnit doomed = (IInstallableUnit) it.next(); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(createResolvedIU(doomed), null)}; - engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); } final Sizing sizingPhase = new Sizing(100, "sizing"); PhaseSet phaseSet = new PhaseSet(new Phase[] {sizingPhase}) {}; InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, createOSGiIU())}; - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); assertTrue(result.isOK()); assertTrue(sizingPhase.getDiskSize() == 0); assertTrue(sizingPhase.getDlSize() == 0); @@ -283,17 +345,15 @@ public class EngineTest extends AbstractProvisioningTest { Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath()); - IProfile profile = createProfile("testPerformInstallOSGiFramework", null, properties); + IProfile profile = createProfile("testPerformInstallOSGiFramework", properties); for (Iterator it = getInstallableUnits(profile); it.hasNext();) { - PhaseSet phaseSet = new DefaultPhaseSet(); IInstallableUnit doomed = (IInstallableUnit) it.next(); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(createResolvedIU(doomed), null)}; - engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); } PhaseSet phaseSet = new DefaultPhaseSet(); - InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, createOSGiIU())}; - IStatus result = engine.validate(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = ((Engine) engine).validate(profile, phaseSet, operands, null, new NullProgressMonitor()); assertTrue(result.isOK()); } @@ -301,17 +361,14 @@ public class EngineTest extends AbstractProvisioningTest { Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath()); - IProfile profile = createProfile("testPerformInstallOSGiFramework", null, properties); + IProfile profile = createProfile("testPerformInstallOSGiFramework", properties); for (Iterator it = getInstallableUnits(profile); it.hasNext();) { - PhaseSet phaseSet = new DefaultPhaseSet(); IInstallableUnit doomed = (IInstallableUnit) it.next(); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(createResolvedIU(doomed), null)}; - engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); } - PhaseSet phaseSet = new DefaultPhaseSet(); - InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, createOSGiIU())}; - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); assertTrue(result.isOK()); Iterator ius = getInstallableUnits(profile); assertTrue(ius.hasNext()); @@ -320,22 +377,21 @@ public class EngineTest extends AbstractProvisioningTest { public void testPerformUpdateOSGiFramework() { Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath()); - IProfile profile = createProfile("testPerformUpdateOSGiFramework", null, properties); - PhaseSet phaseSet = new DefaultPhaseSet(); + IProfile profile = createProfile("testPerformUpdateOSGiFramework", properties); IInstallableUnit iu33 = createOSGiIU("3.3"); IInstallableUnit iu34 = createOSGiIU("3.4"); InstallableUnitOperand[] installOperands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, iu33)}; - IStatus result = engine.perform(profile, phaseSet, installOperands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, installOperands, null), new NullProgressMonitor()); assertTrue(result.isOK()); - Iterator ius = profile.query(new InstallableUnitQuery(iu33), new Collector(), null).iterator(); + Iterator ius = profile.query(new InstallableUnitQuery(iu33), null).iterator(); assertTrue(ius.hasNext()); InstallableUnitOperand[] updateOperands = new InstallableUnitOperand[] {new InstallableUnitOperand(iu33, iu34)}; - result = engine.perform(profile, phaseSet, updateOperands, null, new NullProgressMonitor()); + result = engine.perform(engine.createCustomPlan(profile, updateOperands, null), new NullProgressMonitor()); assertTrue(result.isOK()); - ius = profile.query(new InstallableUnitQuery(iu34), new Collector(), null).iterator(); + ius = profile.query(new InstallableUnitQuery(iu34), null).iterator(); assertTrue(ius.hasNext()); } @@ -344,10 +400,9 @@ public class EngineTest extends AbstractProvisioningTest { Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath()); - IProfile profile = createProfile("testPerformUninstallOSGiFramework", null, properties); - PhaseSet phaseSet = new DefaultPhaseSet(); + IProfile profile = createProfile("testPerformUninstallOSGiFramework", properties); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(createOSGiIU(), null)}; - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); assertTrue(result.isOK()); assertEmptyProfile(profile); } @@ -356,14 +411,13 @@ public class EngineTest extends AbstractProvisioningTest { Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath()); - IProfile profile = createProfile("testPerformRollback", null, properties); - PhaseSet phaseSet = new DefaultPhaseSet(); + IProfile profile = createProfile("testPerformRollback", properties); Iterator ius = getInstallableUnits(profile); assertFalse(ius.hasNext()); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, createOSGiIU()), new InstallableUnitOperand(null, createBadIU())}; - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); assertFalse(result.isOK()); ius = getInstallableUnits(profile); @@ -374,14 +428,14 @@ public class EngineTest extends AbstractProvisioningTest { Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath()); - IProfile profile = createProfile("testPerformRollback", null, properties); + IProfile profile = createProfile("testPerformRollback", properties); PhaseSet phaseSet = new DefaultPhaseSet(); Iterator ius = getInstallableUnits(profile); assertFalse(ius.hasNext()); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, createOSGiIU()), new InstallableUnitOperand(null, createMissingActionIU())}; - IStatus result = engine.validate(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = ((Engine) engine).validate(profile, phaseSet, operands, null, new NullProgressMonitor()); assertFalse(result.isOK()); Throwable t = result.getException(); @@ -394,14 +448,13 @@ public class EngineTest extends AbstractProvisioningTest { Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath()); - IProfile profile = createProfile("testPerformMissingAction", null, properties); - PhaseSet phaseSet = new DefaultPhaseSet(); + IProfile profile = createProfile("testPerformMissingAction", properties); Iterator ius = getInstallableUnits(profile); assertFalse(ius.hasNext()); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, createOSGiIU()), new InstallableUnitOperand(null, createMissingActionIU())}; - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); assertFalse(result.isOK()); ius = getInstallableUnits(profile); assertFalse(ius.hasNext()); @@ -411,7 +464,7 @@ public class EngineTest extends AbstractProvisioningTest { Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath()); - IProfile profile = createProfile("testPerformRollbackOnError", null, properties); + IProfile profile = createProfile("testPerformRollbackOnError", properties); NPEPhase phase = new NPEPhase(); PhaseSet phaseSet = new TestPhaseSet(phase); @@ -419,7 +472,7 @@ public class EngineTest extends AbstractProvisioningTest { assertFalse(ius.hasNext()); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, createOSGiIU())}; - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); assertFalse(result.isOK()); ius = getInstallableUnits(profile); assertFalse(ius.hasNext()); @@ -430,7 +483,7 @@ public class EngineTest extends AbstractProvisioningTest { Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath()); - IProfile profile = createProfile("testPerformRollbackOnError", null, properties); + IProfile profile = createProfile("testPerformRollbackOnError", properties); ActionNPEPhase phase = new ActionNPEPhase(); PhaseSet phaseSet = new TestPhaseSet(phase); @@ -438,7 +491,7 @@ public class EngineTest extends AbstractProvisioningTest { assertFalse(ius.hasNext()); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, createOSGiIU())}; - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); assertFalse(result.isOK()); ius = getInstallableUnits(profile); assertFalse(ius.hasNext()); @@ -448,7 +501,7 @@ public class EngineTest extends AbstractProvisioningTest { public void testPerformForcedPhaseWithActionError() { Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath()); - IProfile profile = createProfile("testPerformForceWithActionError", null, properties); + IProfile profile = createProfile("testPerformForceWithActionError", properties); ActionNPEPhase phase = new ActionNPEPhase(true); PhaseSet phaseSet = new TestPhaseSet(phase); @@ -456,7 +509,7 @@ public class EngineTest extends AbstractProvisioningTest { assertFalse(ius.hasNext()); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, createOSGiIU())}; - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); assertTrue(result.isOK()); ius = getInstallableUnits(profile); assertTrue(ius.hasNext()); @@ -466,7 +519,7 @@ public class EngineTest extends AbstractProvisioningTest { public void testPerformForcedUninstallWithBadUninstallIUActionThrowsException() { Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath()); - IProfile profile = createProfile("testPerformForcedUninstallWithBadUninstallIUActionThrowsException", null, properties); + IProfile profile = createProfile("testPerformForcedUninstallWithBadUninstallIUActionThrowsException", properties); // forcedUninstall is false by default PhaseSet phaseSet = new DefaultPhaseSet(); @@ -476,20 +529,20 @@ public class EngineTest extends AbstractProvisioningTest { IInstallableUnit badUninstallIU = createBadUninstallIUThrowsException(); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, badUninstallIU)}; - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); assertTrue(result.isOK()); ius = getInstallableUnits(profile); assertTrue(ius.hasNext()); operands = new InstallableUnitOperand[] {new InstallableUnitOperand(badUninstallIU, null)}; - result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + result = engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); assertFalse(result.isOK()); ius = getInstallableUnits(profile); assertTrue(ius.hasNext()); // this simulates a DefaultPhaseSet with forcedUninstall set phaseSet = new TestPhaseSet(true); - result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + result = engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); assertTrue(result.isOK()); ius = getInstallableUnits(profile); assertFalse(ius.hasNext()); @@ -498,30 +551,29 @@ public class EngineTest extends AbstractProvisioningTest { public void testPerformForcedUninstallWithBadUninstallIUActionReturnsError() { Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, testProvisioning.getAbsolutePath()); - IProfile profile = createProfile("testPerformForcedUninstallWithBadUninstallIUActionReturnsError", null, properties); + IProfile profile = createProfile("testPerformForcedUninstallWithBadUninstallIUActionReturnsError", properties); // forcedUninstall is false by default - PhaseSet phaseSet = new DefaultPhaseSet(); Iterator ius = getInstallableUnits(profile); assertFalse(ius.hasNext()); IInstallableUnit badUninstallIU = createBadUninstallIUReturnsError(); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, badUninstallIU)}; - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); assertTrue(result.isOK()); ius = getInstallableUnits(profile); assertTrue(ius.hasNext()); operands = new InstallableUnitOperand[] {new InstallableUnitOperand(badUninstallIU, null)}; - result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + result = engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); assertFalse(result.isOK()); ius = getInstallableUnits(profile); assertTrue(ius.hasNext()); // this simulates a DefaultPhaseSet with forcedUninstall set - phaseSet = new TestPhaseSet(true); - result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IPhaseSet phaseSet = new TestPhaseSet(true); + result = engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); assertTrue(result.isOK()); ius = getInstallableUnits(profile); assertFalse(ius.hasNext()); @@ -529,15 +581,14 @@ public class EngineTest extends AbstractProvisioningTest { public void testOrphanedIUProperty() { IProfile profile = createProfile("testOrphanedIUProperty"); - PhaseSet phaseSet = new DefaultPhaseSet(); IInstallableUnit iu = createIU("someIU"); Operand[] operands = new InstallableUnitPropertyOperand[] {new InstallableUnitPropertyOperand(iu, "key", null, "value")}; - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); assertTrue(result.isOK()); assertFalse(profile.getInstallableUnitProperties(iu).containsKey("key")); operands = new Operand[] {new InstallableUnitOperand(null, iu), new InstallableUnitPropertyOperand(iu, "adifferentkey", null, "value")}; - result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + result = engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); assertTrue(result.isOK()); assertTrue(profile.getInstallableUnitProperties(iu).containsKey("adifferentkey")); assertFalse(profile.getInstallableUnitProperties(iu).containsKey("key")); @@ -550,7 +601,7 @@ public class EngineTest extends AbstractProvisioningTest { private IInstallableUnit createOSGiIU(String version) { InstallableUnitDescription description = new MetadataFactory.InstallableUnitDescription(); description.setId("org.eclipse.osgi"); - description.setVersion(new Version(version)); + description.setVersion(Version.create(version)); description.setTouchpointType(AbstractProvisioningTest.TOUCHPOINT_OSGI); Map touchpointData = new HashMap(); String manifest = "Manifest-Version: 1.0\r\n" + "Bundle-Activator: org.eclipse.osgi.framework.internal.core.SystemBundl\r\n" + " eActivator\r\n" + "Bundle-RequiredExecutionEnvironment: J2SE-1.4,OSGi/Minimum-1.0\r\n" + "Export-Package: org.eclipse.osgi.event;version=\"1.0\",org.eclipse.osgi.\r\n" + " framework.console;version=\"1.0\",org.eclipse.osgi.framework.eventmgr;v\r\n" + " ersion=\"1.0\",org.eclipse.osgi.framework.log;version=\"1.0\",org.eclipse\r\n" + " .osgi.service.datalocation;version=\"1.0\",org.eclipse.osgi.service.deb\r\n" + " ug;version=\"1.0\",org.eclipse.osgi.service.environment;version=\"1.0\",o\r\n" + " rg.eclipse.osgi.service.localization;version=\"1.0\",org.eclipse.osgi.s\r\n" + " ervice.pluginconversion;version=\"1.0\",org.eclipse.osgi.service.resolv\r\n" @@ -568,7 +619,7 @@ public class EngineTest extends AbstractProvisioningTest { IInstallableUnitFragment fragment = MetadataFactory.createInstallableUnitFragment(desc); cus[0] = fragment; - //IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", new Version("3.3.1.R33x_v20070828")); + //IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", Version.create("3.3.1.R33x_v20070828")); //iu.setArtifacts(new IArtifactKey[] {key}); IInstallableUnit iu = MetadataFactory.createInstallableUnit(description); @@ -578,7 +629,7 @@ public class EngineTest extends AbstractProvisioningTest { private IInstallableUnit createBadIU() { InstallableUnitDescription description = new MetadataFactory.InstallableUnitDescription(); description.setId("org.eclipse.osgi.bad"); - description.setVersion(new Version("3.3.1.R33x_v20070828")); + description.setVersion(Version.create("3.3.1.R33x_v20070828")); description.setTouchpointType(AbstractProvisioningTest.TOUCHPOINT_OSGI); Map touchpointData = new HashMap(); String manifest = "Manifest-Version: 1.0\r\n" + "Bundle-Activator: org.eclipse.osgi.framework.internal.core.SystemBundl\r\n" + " eActivator\r\n" + "Bundle-RequiredExecutionEnvironment: J2SE-1.4,OSGi/Minimum-1.0\r\n" + "Export-Package: org.eclipse.osgi.event;version=\"1.0\",org.eclipse.osgi.\r\n" + " framework.console;version=\"1.0\",org.eclipse.osgi.framework.eventmgr;v\r\n" + " ersion=\"1.0\",org.eclipse.osgi.framework.log;version=\"1.0\",org.eclipse\r\n" + " .osgi.service.datalocation;version=\"1.0\",org.eclipse.osgi.service.deb\r\n" + " ug;version=\"1.0\",org.eclipse.osgi.service.environment;version=\"1.0\",o\r\n" + " rg.eclipse.osgi.service.localization;version=\"1.0\",org.eclipse.osgi.s\r\n" + " ervice.pluginconversion;version=\"1.0\",org.eclipse.osgi.service.resolv\r\n" @@ -594,7 +645,7 @@ public class EngineTest extends AbstractProvisioningTest { desc.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); cus[0] = MetadataFactory.createInstallableUnitFragment(desc); - //IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", new Version("3.3.1.R33x_v20070828")); + //IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", Version.create("3.3.1.R33x_v20070828")); //iu.setArtifacts(new IArtifactKey[] {key}); IInstallableUnit iu = MetadataFactory.createInstallableUnit(description); @@ -604,7 +655,7 @@ public class EngineTest extends AbstractProvisioningTest { private IInstallableUnit createBadUninstallIUReturnsError() { InstallableUnitDescription description = new MetadataFactory.InstallableUnitDescription(); description.setId("org.eclipse.osgi.bad"); - description.setVersion(new Version("3.3.1.R33x_v20070828")); + description.setVersion(Version.create("3.3.1.R33x_v20070828")); description.setTouchpointType(AbstractProvisioningTest.TOUCHPOINT_OSGI); Map touchpointData = new HashMap(); String manifest = "Manifest-Version: 1.0\r\n" + "Bundle-Activator: org.eclipse.osgi.framework.internal.core.SystemBundl\r\n" + " eActivator\r\n" + "Bundle-RequiredExecutionEnvironment: J2SE-1.4,OSGi/Minimum-1.0\r\n" + "Export-Package: org.eclipse.osgi.event;version=\"1.0\",org.eclipse.osgi.\r\n" + " framework.console;version=\"1.0\",org.eclipse.osgi.framework.eventmgr;v\r\n" + " ersion=\"1.0\",org.eclipse.osgi.framework.log;version=\"1.0\",org.eclipse\r\n" + " .osgi.service.datalocation;version=\"1.0\",org.eclipse.osgi.service.deb\r\n" + " ug;version=\"1.0\",org.eclipse.osgi.service.environment;version=\"1.0\",o\r\n" + " rg.eclipse.osgi.service.localization;version=\"1.0\",org.eclipse.osgi.s\r\n" + " ervice.pluginconversion;version=\"1.0\",org.eclipse.osgi.service.resolv\r\n" @@ -620,7 +671,7 @@ public class EngineTest extends AbstractProvisioningTest { desc.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); cus[0] = MetadataFactory.createInstallableUnitFragment(desc); - //IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", new Version("3.3.1.R33x_v20070828")); + //IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", Version.create("3.3.1.R33x_v20070828")); //iu.setArtifacts(new IArtifactKey[] {key}); IInstallableUnit iu = MetadataFactory.createInstallableUnit(description); @@ -630,7 +681,7 @@ public class EngineTest extends AbstractProvisioningTest { private IInstallableUnit createBadUninstallIUThrowsException() { InstallableUnitDescription description = new MetadataFactory.InstallableUnitDescription(); description.setId("org.eclipse.osgi.bad"); - description.setVersion(new Version("3.3.1.R33x_v20070828")); + description.setVersion(Version.create("3.3.1.R33x_v20070828")); description.setTouchpointType(AbstractProvisioningTest.TOUCHPOINT_OSGI); Map touchpointData = new HashMap(); String manifest = "Manifest-Version: 1.0\r\n" + "Bundle-Activator: org.eclipse.osgi.framework.internal.core.SystemBundl\r\n" + " eActivator\r\n" + "Bundle-RequiredExecutionEnvironment: J2SE-1.4,OSGi/Minimum-1.0\r\n" + "Export-Package: org.eclipse.osgi.event;version=\"1.0\",org.eclipse.osgi.\r\n" + " framework.console;version=\"1.0\",org.eclipse.osgi.framework.eventmgr;v\r\n" + " ersion=\"1.0\",org.eclipse.osgi.framework.log;version=\"1.0\",org.eclipse\r\n" + " .osgi.service.datalocation;version=\"1.0\",org.eclipse.osgi.service.deb\r\n" + " ug;version=\"1.0\",org.eclipse.osgi.service.environment;version=\"1.0\",o\r\n" + " rg.eclipse.osgi.service.localization;version=\"1.0\",org.eclipse.osgi.s\r\n" + " ervice.pluginconversion;version=\"1.0\",org.eclipse.osgi.service.resolv\r\n" @@ -646,7 +697,7 @@ public class EngineTest extends AbstractProvisioningTest { desc.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); cus[0] = MetadataFactory.createInstallableUnitFragment(desc); - //IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", new Version("3.3.1.R33x_v20070828")); + //IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", Version.create("3.3.1.R33x_v20070828")); //iu.setArtifacts(new IArtifactKey[] {key}); IInstallableUnit iu = MetadataFactory.createInstallableUnit(description); @@ -656,7 +707,7 @@ public class EngineTest extends AbstractProvisioningTest { private IInstallableUnit createMissingActionIU() { InstallableUnitDescription description = new MetadataFactory.InstallableUnitDescription(); description.setId("org.eclipse.osgi.bad"); - description.setVersion(new Version("3.3.1.R33x_v20070828")); + description.setVersion(Version.create("3.3.1.R33x_v20070828")); description.setTouchpointType(AbstractProvisioningTest.TOUCHPOINT_OSGI); Map touchpointData = new HashMap(); String manifest = "Manifest-Version: 1.0\r\n" + "Bundle-Activator: org.eclipse.osgi.framework.internal.core.SystemBundl\r\n" + " eActivator\r\n" + "Bundle-RequiredExecutionEnvironment: J2SE-1.4,OSGi/Minimum-1.0\r\n" + "Export-Package: org.eclipse.osgi.event;version=\"1.0\",org.eclipse.osgi.\r\n" + " framework.console;version=\"1.0\",org.eclipse.osgi.framework.eventmgr;v\r\n" + " ersion=\"1.0\",org.eclipse.osgi.framework.log;version=\"1.0\",org.eclipse\r\n" + " .osgi.service.datalocation;version=\"1.0\",org.eclipse.osgi.service.deb\r\n" + " ug;version=\"1.0\",org.eclipse.osgi.service.environment;version=\"1.0\",o\r\n" + " rg.eclipse.osgi.service.localization;version=\"1.0\",org.eclipse.osgi.s\r\n" + " ervice.pluginconversion;version=\"1.0\",org.eclipse.osgi.service.resolv\r\n" @@ -672,7 +723,7 @@ public class EngineTest extends AbstractProvisioningTest { desc.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); cus[0] = MetadataFactory.createInstallableUnitFragment(desc); - //IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", new Version("3.3.1.R33x_v20070828")); + //IArtifactKey key = new ArtifactKey("eclipse", "plugin", "org.eclipse.osgi", Version.create("3.3.1.R33x_v20070828")); //iu.setArtifacts(new IArtifactKey[] {key}); IInstallableUnit iu = MetadataFactory.createInstallableUnit(description); @@ -682,8 +733,8 @@ public class EngineTest extends AbstractProvisioningTest { public void testIncompatibleProfile() { IProfile profile = new IProfile() { - public Collector available(Query query, Collector collector, IProgressMonitor monitor) { - return null; + public Collector available(IQuery query, IProgressMonitor monitor) { + return new Collector(); } public Map getInstallableUnitProperties(IInstallableUnit iu) { @@ -694,18 +745,6 @@ public class EngineTest extends AbstractProvisioningTest { return null; } - public Map getLocalProperties() { - return null; - } - - public String getLocalProperty(String key) { - return null; - } - - public IProfile getParentProfile() { - return null; - } - public String getProfileId() { return null; } @@ -718,30 +757,17 @@ public class EngineTest extends AbstractProvisioningTest { return null; } - public String[] getSubProfileIds() { - return null; - } - public long getTimestamp() { return 0; } - public boolean hasSubProfiles() { - return false; - } - - public boolean isRootProfile() { - return false; - } - - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - return null; + public Collector query(IQuery query, IProgressMonitor monitor) { + return new Collector(); } }; - PhaseSet phaseSet = new DefaultPhaseSet(); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {}; try { - engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); } catch (IllegalArgumentException expected) { return; } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/InstructionParserTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/InstructionParserTest.java index ec2f10ea2..c37eabce8 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/InstructionParserTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/InstructionParserTest.java @@ -10,23 +10,24 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.engine; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; +import java.util.List; import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.engine.ActionManager; import org.eclipse.equinox.internal.p2.engine.InstructionParser; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.engine.Touchpoint; -import org.eclipse.equinox.internal.provisional.p2.metadata.ITouchpointType; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.Touchpoint; +import org.eclipse.equinox.p2.metadata.ITouchpointType; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class InstructionParserTest extends AbstractProvisioningTest { - public static final ITouchpointType TOUCHPOINT_TYPE = MetadataFactory.createTouchpointType("InstructionParserTestTouchpoint", new Version("1.0")); //$NON-NLS-1$ //$NON-NLS-2$ + public static final ITouchpointType TOUCHPOINT_TYPE = MetadataFactory.createTouchpointType("InstructionParserTestTouchpoint", Version.create("1.0")); //$NON-NLS-1$ //$NON-NLS-2$ public static class InstructionParserTestTouchpoint extends Touchpoint { @@ -65,21 +66,21 @@ public class InstructionParserTest extends AbstractProvisioningTest { public void testGoodAction() { InstructionParser parser = new InstructionParser(new ActionManager()); - ProvisioningAction[] actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("goodAction()", null), TOUCHPOINT_TYPE); - assertEquals(1, actions.length); + List actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("goodAction()", null), TOUCHPOINT_TYPE); + assertEquals(1, actions.size()); } public void testGoodActionFullyQualified() { InstructionParser parser = new InstructionParser(new ActionManager()); - ProvisioningAction[] actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("instructionparsertest.goodAction()", null), null); - assertEquals(1, actions.length); + List actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("instructionparsertest.goodAction()", null), null); + assertEquals(1, actions.size()); } public void testBadActionFullyQualified() { InstructionParser parser = new InstructionParser(new ActionManager()); try { - ProvisioningAction[] actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("instructionparsertest.badAction()", null), null); - actions[0].execute(null); + List actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("instructionparsertest.badAction()", null), null); + actions.get(0).execute(null); } catch (IllegalArgumentException e) { return; } @@ -88,21 +89,21 @@ public class InstructionParserTest extends AbstractProvisioningTest { public void testGoodActionFromImport() { InstructionParser parser = new InstructionParser(new ActionManager()); - ProvisioningAction[] actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("goodAction()", "instructionparsertest.goodAction"), null); - assertEquals(1, actions.length); + List actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("goodAction()", "instructionparsertest.goodAction"), null); + assertEquals(1, actions.size()); } public void testGoodActionFromImportWithVersionRange() { InstructionParser parser = new InstructionParser(new ActionManager()); - ProvisioningAction[] actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("goodAction()", "instructionparsertest.goodAction;version=[1.0,2.0)"), null); - assertEquals(1, actions.length); + List actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("goodAction()", "instructionparsertest.goodAction;version=[1.0,2.0)"), null); + assertEquals(1, actions.size()); } public void testBadActionFromImport() { InstructionParser parser = new InstructionParser(new ActionManager()); try { - ProvisioningAction[] actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("badAction()", "instructionparsertest.badAction"), null); - actions[0].execute(null); + List actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("badAction()", "instructionparsertest.badAction"), null); + actions.get(0).execute(null); } catch (IllegalArgumentException e) { return; } @@ -111,20 +112,20 @@ public class InstructionParserTest extends AbstractProvisioningTest { public void testGoodActions() { InstructionParser parser = new InstructionParser(new ActionManager()); - ProvisioningAction[] actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("goodAction(); goodAction()", null), TOUCHPOINT_TYPE); - assertEquals(2, actions.length); + List actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("goodAction(); goodAction()", null), TOUCHPOINT_TYPE); + assertEquals(2, actions.size()); } public void testGoodParameter() { InstructionParser parser = new InstructionParser(new ActionManager()); - ProvisioningAction[] actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("goodAction(a:1)", null), TOUCHPOINT_TYPE); - assertEquals(1, actions.length); + List actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("goodAction(a:1)", null), TOUCHPOINT_TYPE); + assertEquals(1, actions.size()); } public void testGoodParameters() { InstructionParser parser = new InstructionParser(new ActionManager()); - ProvisioningAction[] actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("goodAction(a:1, b:2)", null), TOUCHPOINT_TYPE); - assertEquals(1, actions.length); + List actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("goodAction(a:1, b:2)", null), TOUCHPOINT_TYPE); + assertEquals(1, actions.size()); } public void testBadParameter() { @@ -160,8 +161,8 @@ public class InstructionParserTest extends AbstractProvisioningTest { public void testGoodActionBadAction() { InstructionParser parser = new InstructionParser(new ActionManager()); try { - ProvisioningAction[] actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("goodAction(); badAction()", null), TOUCHPOINT_TYPE); - actions[1].execute(null); + List actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("goodAction(); badAction()", null), TOUCHPOINT_TYPE); + actions.get(1).execute(null); } catch (IllegalArgumentException e) { return; } @@ -171,8 +172,8 @@ public class InstructionParserTest extends AbstractProvisioningTest { public void testNoActionFound() { InstructionParser parser = new InstructionParser(new ActionManager()); try { - ProvisioningAction[] actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("notfoundaction()", null), TOUCHPOINT_TYPE); - actions[0].execute(null); + List actions = parser.parseActions(MetadataFactory.createTouchpointInstruction("notfoundaction()", null), TOUCHPOINT_TYPE); + actions.get(0).execute(null); } catch (IllegalArgumentException e) { return; } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ParameterizedProvisioningActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ParameterizedProvisioningActionTest.java index 10ad1b8a7..e0069225f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ParameterizedProvisioningActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ParameterizedProvisioningActionTest.java @@ -14,7 +14,7 @@ import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.engine.ParameterizedProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class ParameterizedProvisioningActionTest extends AbstractProvisioningTest { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/PhaseApplicabilityTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/PhaseApplicabilityTest.java index c8da12b6e..a717ac609 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/PhaseApplicabilityTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/PhaseApplicabilityTest.java @@ -10,11 +10,11 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.engine; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.engine.phases.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.internal.p2.engine.phases.*; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** @@ -32,8 +32,8 @@ public class PhaseApplicabilityTest extends AbstractProvisioningTest { public void testCollectPhase() { - IInstallableUnit iuXv1 = createIU("iuX", new Version("1.0.0")); - IInstallableUnit iuXv2 = createIU("iuX", new Version("2.0.0")); + IInstallableUnit iuXv1 = createIU("iuX", Version.create("1.0.0")); + IInstallableUnit iuXv2 = createIU("iuX", Version.create("2.0.0")); Collect collectPhase = new Collect(1) { protected boolean isApplicable(InstallableUnitOperand op) { @@ -48,8 +48,8 @@ public class PhaseApplicabilityTest extends AbstractProvisioningTest { public void testSizingPhase() { - IInstallableUnit iuXv1 = createIU("iuX", new Version("1.0.0")); - IInstallableUnit iuXv2 = createIU("iuX", new Version("2.0.0")); + IInstallableUnit iuXv1 = createIU("iuX", Version.create("1.0.0")); + IInstallableUnit iuXv2 = createIU("iuX", Version.create("2.0.0")); Sizing sizingPhase = new Sizing(1, "collect") { protected boolean isApplicable(InstallableUnitOperand op) { @@ -64,8 +64,8 @@ public class PhaseApplicabilityTest extends AbstractProvisioningTest { public void testUnconfigurePhase() { - IInstallableUnit iuXv1 = createIU("iuX", new Version("1.0.0")); - IInstallableUnit iuXv2 = createIU("iuX", new Version("2.0.0")); + IInstallableUnit iuXv1 = createIU("iuX", Version.create("1.0.0")); + IInstallableUnit iuXv2 = createIU("iuX", Version.create("2.0.0")); Unconfigure unconfigurePhase = new Unconfigure(1) { protected boolean isApplicable(InstallableUnitOperand op) { @@ -80,8 +80,8 @@ public class PhaseApplicabilityTest extends AbstractProvisioningTest { public void testUninstallPhase() { - IInstallableUnit iuXv1 = createIU("iuX", new Version("1.0.0")); - IInstallableUnit iuXv2 = createIU("iuX", new Version("2.0.0")); + IInstallableUnit iuXv1 = createIU("iuX", Version.create("1.0.0")); + IInstallableUnit iuXv2 = createIU("iuX", Version.create("2.0.0")); Uninstall uninstallPhase = new Uninstall(1) { protected boolean isApplicable(InstallableUnitOperand op) { @@ -96,8 +96,8 @@ public class PhaseApplicabilityTest extends AbstractProvisioningTest { public void testInstallPhase() { - IInstallableUnit iuXv1 = createIU("iuX", new Version("1.0.0")); - IInstallableUnit iuXv2 = createIU("iuX", new Version("2.0.0")); + IInstallableUnit iuXv1 = createIU("iuX", Version.create("1.0.0")); + IInstallableUnit iuXv2 = createIU("iuX", Version.create("2.0.0")); Install installPhase = new Install(1) { protected boolean isApplicable(InstallableUnitOperand op) { @@ -112,8 +112,8 @@ public class PhaseApplicabilityTest extends AbstractProvisioningTest { public void testConfigurePhase() { - IInstallableUnit iuXv1 = createIU("iuX", new Version("1.0.0")); - IInstallableUnit iuXv2 = createIU("iuX", new Version("2.0.0")); + IInstallableUnit iuXv1 = createIU("iuX", Version.create("1.0.0")); + IInstallableUnit iuXv2 = createIU("iuX", Version.create("2.0.0")); Configure configurePhase = new Configure(1) { protected boolean isApplicable(InstallableUnitOperand op) { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/PhaseSetTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/PhaseSetTest.java index 7f714321b..2faad7acf 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/PhaseSetTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/PhaseSetTest.java @@ -12,7 +12,8 @@ package org.eclipse.equinox.p2.tests.engine; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.engine.*; +import org.eclipse.equinox.internal.p2.engine.*; +import org.eclipse.equinox.p2.engine.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** @@ -53,7 +54,7 @@ public class PhaseSetTest extends AbstractProvisioningTest { InstallableUnitOperand[] operands = new InstallableUnitOperand[] {op}; ProvisioningContext context = new ProvisioningContext(); - IStatus result = phaseSet.perform(null, new EngineSession(profile, null, context), profile, operands, context, new NullProgressMonitor()); + IStatus result = phaseSet.perform(new EngineSession(null, profile, context), operands, new NullProgressMonitor()); assertTrue(result.isOK()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/PhaseTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/PhaseTest.java index 5f26f5e68..30b6b1d8c 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/PhaseTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/PhaseTest.java @@ -10,15 +10,17 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.engine; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import java.io.IOException; import java.util.*; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.engine.ParameterizedProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.p2.engine.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.ServiceReference; @@ -79,9 +81,9 @@ public class PhaseTest extends AbstractProvisioningTest { return super.initializePhase(monitor, profile, parameters); } - protected ProvisioningAction[] getActions(InstallableUnitOperand operand) { + protected List getActions(InstallableUnitOperand operand) { IInstallableUnit unit = operand.second(); - ProvisioningAction[] parsedActions = getActions(unit, phaseId); + List parsedActions = getActions(unit, phaseId); if (parsedActions != null) return parsedActions; @@ -94,7 +96,7 @@ public class PhaseTest extends AbstractProvisioningTest { if (action == null) { throw new IllegalArgumentException("action not found: " + phaseId); } - return new ProvisioningAction[] {action}; + return Collections.singletonList(action); } } @@ -160,7 +162,8 @@ public class PhaseTest extends AbstractProvisioningTest { PhaseSet phaseSet = new TestPhaseSet(new TestPhase()); IProfile profile = createProfile("PhaseTest"); - engine.perform(profile, phaseSet, new InstallableUnitOperand[0], null, new NullProgressMonitor()); + final InstallableUnitOperand[] operands = new InstallableUnitOperand[0]; + engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); } public void testInitCompletePhase() { @@ -186,7 +189,8 @@ public class PhaseTest extends AbstractProvisioningTest { PhaseSet phaseSet = new TestPhaseSet(phase); IProfile profile = createProfile("PhaseTest"); IInstallableUnit unit = createIU("unit"); - engine.perform(profile, phaseSet, new InstallableUnitOperand[] {new InstallableUnitOperand(null, unit)}, null, new NullProgressMonitor()); + final InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, unit)}; + engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); assertTrue(phase.initializePhase); assertTrue(phase.completePhase); } @@ -215,7 +219,8 @@ public class PhaseTest extends AbstractProvisioningTest { IProfile profile = createProfile("PhaseTest"); IInstallableUnit unit = createIU("testInitCompleteOperand"); - engine.perform(profile, phaseSet, new InstallableUnitOperand[] {new InstallableUnitOperand(null, unit)}, null, new NullProgressMonitor()); + final InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, unit)}; + engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); assertTrue(phase.initializeOperand); assertTrue(phase.completeOperand); } @@ -250,7 +255,8 @@ public class PhaseTest extends AbstractProvisioningTest { IProfile profile = createProfile("PhaseTest"); IInstallableUnit unit = createIU("testGetProfileDataArea"); - engine.perform(profile, phaseSet, new InstallableUnitOperand[] {new InstallableUnitOperand(null, unit)}, null, new NullProgressMonitor()); + final InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, unit)}; + engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); assertTrue(phase.initializePhase); assertTrue(phase.completePhase); } @@ -269,17 +275,17 @@ public class PhaseTest extends AbstractProvisioningTest { public void testGetAction() { final ArrayList actionsList1 = new ArrayList(); InstallableUnitPhase phase1 = new InstallableUnitPhase("test", 1) { - protected ProvisioningAction[] getActions(InstallableUnitOperand operand) { - ProvisioningAction[] actions = getActions(operand.second(), "test1"); - actionsList1.addAll(Arrays.asList(actions)); + protected List getActions(InstallableUnitOperand operand) { + List actions = getActions(operand.second(), "test1"); + actionsList1.addAll(actions); return actions; } }; final ArrayList actionsList2 = new ArrayList(); InstallableUnitPhase phase2 = new InstallableUnitPhase("test", 1) { - protected ProvisioningAction[] getActions(InstallableUnitOperand operand) { - ProvisioningAction[] actions = getActions(operand.second(), "test2"); - actionsList2.addAll(Arrays.asList(actions)); + protected List getActions(InstallableUnitOperand operand) { + List actions = getActions(operand.second(), "test2"); + actionsList2.addAll(actions); return actions; } }; @@ -291,8 +297,9 @@ public class PhaseTest extends AbstractProvisioningTest { instructions.put("test1", MetadataFactory.createTouchpointInstruction("test1.test()", null)); instructions.put("test2", MetadataFactory.createTouchpointInstruction("test2.test()", null)); ITouchpointData touchpointData = MetadataFactory.createTouchpointData(instructions); - IInstallableUnit unit = createIU("test", new Version("1.0.0"), null, NO_REQUIRES, new IProvidedCapability[0], NO_PROPERTIES, ITouchpointType.NONE, touchpointData, false); - IStatus status = engine.perform(profile, phaseSet, new InstallableUnitOperand[] {new InstallableUnitOperand(null, unit)}, null, new NullProgressMonitor()); + IInstallableUnit unit = createIU("test", Version.create("1.0.0"), null, NO_REQUIRES, new IProvidedCapability[0], NO_PROPERTIES, ITouchpointType.NONE, touchpointData, false); + final InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, unit)}; + IStatus status = engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); if (!status.isOK()) { fail(status.toString()); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileMetadataRepositoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileMetadataRepositoryTest.java index 6b5bcc5b8..40b612f58 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileMetadataRepositoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileMetadataRepositoryTest.java @@ -12,16 +12,14 @@ package org.eclipse.equinox.p2.tests.engine; import java.io.File; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepositoryFactory; import org.eclipse.equinox.internal.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.SimpleArtifactRepositoryFactory; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; -import org.eclipse.equinox.p2.tests.TestActivator; /** * Simple test of the engine API. @@ -73,7 +71,7 @@ public class ProfileMetadataRepositoryTest extends AbstractProvisioningTest { IProfile profile = registry.getProfile("SDKPatchingTest"); assertNotNull("0.3", profile); - Collector profileCollector = profile.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); + IQueryResult profileCollector = profile.query(InstallableUnitQuery.ANY, getMonitor()); assertFalse("0.4", profileCollector.isEmpty()); File simpleProfileFolder = new File(tempFolder, "SDKPatchingTest.profile"); @@ -87,9 +85,9 @@ public class ProfileMetadataRepositoryTest extends AbstractProvisioningTest { fail("0.99", e1); } - Collector repoCollector = repo.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); + IQueryResult repoCollector = repo.query(InstallableUnitQuery.ANY, getMonitor()); assertFalse("1.0", repoCollector.isEmpty()); - assertTrue("1.1", repoCollector.toCollection().containsAll(profileCollector.toCollection())); + assertContains("1.1", repoCollector, profileCollector); } public void testLoadTimestampedProfile() { @@ -101,7 +99,7 @@ public class ProfileMetadataRepositoryTest extends AbstractProvisioningTest { IProfile profile = registry.getProfile("SDKPatchingTest"); assertNotNull("0.3", profile); - Collector profileCollector = profile.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); + IQueryResult profileCollector = profile.query(InstallableUnitQuery.ANY, getMonitor()); assertFalse("0.4", profileCollector.isEmpty()); File simpleProfileFolder = new File(tempFolder, "SDKPatchingTest.profile"); @@ -118,9 +116,9 @@ public class ProfileMetadataRepositoryTest extends AbstractProvisioningTest { fail("0.99", e1); } - Collector repoCollector = repo.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); + IQueryResult repoCollector = repo.query(InstallableUnitQuery.ANY, getMonitor()); assertFalse("1.0", repoCollector.isEmpty()); - assertTrue("1.1", repoCollector.toCollection().containsAll(profileCollector.toCollection())); + assertContains("1.1", repoCollector, profileCollector); } public void DISABLED_testDefaultAgentRepoAndBundlePoolFromProfileRepo() throws InterruptedException { @@ -128,17 +126,19 @@ public class ProfileMetadataRepositoryTest extends AbstractProvisioningTest { // /p2/org.eclipse.equinox.p2.engine/profileRegistry"); File tempFolder = getTempFolder(); copy("0.2", testData, tempFolder); - new SimpleArtifactRepositoryFactory().create(tempFolder.toURI(), "", "", null); + final SimpleArtifactRepositoryFactory simpleFactory = new SimpleArtifactRepositoryFactory(); + simpleFactory.setAgent(getAgent()); + simpleFactory.create(tempFolder.toURI(), "", "", null); File defaultAgenRepositoryDirectory = new File(tempFolder, "p2/org.eclipse.equinox.p2.core/cache"); - new SimpleArtifactRepositoryFactory().create(defaultAgenRepositoryDirectory.toURI(), "", "", null); + simpleFactory.create(defaultAgenRepositoryDirectory.toURI(), "", "", null); File profileRegistryFolder = new File(tempFolder, "p2/org.eclipse.equinox.p2.engine/profileRegistry"); SimpleProfileRegistry registry = new SimpleProfileRegistry(profileRegistryFolder, null, false); IProfile profile = registry.getProfile("SDKPatchingTest"); assertNotNull("1.0", profile); - Collector profileCollector = profile.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); + IQueryResult profileCollector = profile.query(InstallableUnitQuery.ANY, getMonitor()); assertFalse("1.1", profileCollector.isEmpty()); File simpleProfileFolder = new File(profileRegistryFolder, "SDKPatchingTest.profile"); @@ -147,7 +147,7 @@ public class ProfileMetadataRepositoryTest extends AbstractProvisioningTest { File timeStampedProfile = new File(simpleProfileFolder, "" + profile.getTimestamp() + ".profile"); assertTrue("1.3", timeStampedProfile.exists()); - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.context, IArtifactRepositoryManager.class.getName()); + IArtifactRepositoryManager manager = getArtifactRepositoryManager(); assertNotNull("2.0", manager); assertFalse("2.1", manager.contains(tempFolder.toURI())); @@ -159,9 +159,9 @@ public class ProfileMetadataRepositoryTest extends AbstractProvisioningTest { fail("2.99", e1); } - Collector repoCollector = repo.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); + IQueryResult repoCollector = repo.query(InstallableUnitQuery.ANY, getMonitor()); assertFalse("3.0", repoCollector.isEmpty()); - assertTrue("3.1", repoCollector.toCollection().containsAll(profileCollector.toCollection())); + assertContains("3.1", repoCollector, profileCollector); int maxTries = 20; int current = 0; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfilePreferencesTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfilePreferencesTest.java index 6f9c50874..81b4a6be3 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfilePreferencesTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfilePreferencesTest.java @@ -10,12 +10,21 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.engine; +import java.io.File; +import java.net.URI; +import java.util.Hashtable; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.preferences.IPreferencesService; +import org.eclipse.equinox.internal.p2.core.ProvisioningAgent; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.engine.ProfilePreferences; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.ProfileScope; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; +import org.eclipse.equinox.security.storage.EncodingUtils; +import org.osgi.framework.ServiceRegistration; import org.osgi.service.prefs.BackingStoreException; import org.osgi.service.prefs.Preferences; @@ -34,20 +43,47 @@ public class ProfilePreferencesTest extends AbstractProvisioningTest { public void testInvalidProfile() { try { //reading and storing for a non-existent profile shouldn't cause any errors - Preferences node = prefServ.getRootNode().node("/profile/NonExistantProfile/testing"); + IAgentLocation agentLocation = (IAgentLocation) getAgent().getService(IAgentLocation.SERVICE_NAME); + String locationString = EncodingUtils.encodeSlashes(agentLocation.getRootLocation().toString()); + Preferences node = prefServ.getRootNode().node("/profile/" + locationString + "/NonExistantProfile/testing"); node.sync(); } catch (BackingStoreException e) { fail("1.0", e); } } + /** + * Profile preferences looks up the agent location using an LDAP filter. Make + * sure it can handle an agent location that contains characters that are not valid in an LDAP filter + */ + public void testInvalidFilterChars() { + File folder = getTestData("Prefs", "/testData/ProfilePreferencesTest/with(invalid)chars/"); + URI location = folder.toURI(); + ProvisioningAgent agent = new ProvisioningAgent(); + agent.setLocation(location); + agent.setBundleContext(TestActivator.getContext()); + IAgentLocation agentLocation = (IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME); + Hashtable props = new Hashtable(); + props.put("locationURI", location.toString()); + ServiceRegistration reg = TestActivator.getContext().registerService(IProvisioningAgent.SERVICE_NAME, agent, props); + try { + Preferences prefs = new ProfileScope(agentLocation, "TestProfile").getNode("org.eclipse.equinox.p2.ui.sdk"); + assertEquals("1.0", "always", prefs.get("allowNonOKPlan", "")); + } finally { + reg.unregister(); + } + + } + public void testProfilePreference() { Preferences pref = null; String key = "Test"; String value = "Value"; + IAgentLocation agentLocation = (IAgentLocation) getAgent().getService(IAgentLocation.SERVICE_NAME); + String locationString = EncodingUtils.encodeSlashes(agentLocation.getRootLocation().toString()); try { - pref = prefServ.getRootNode().node("/profile/_SELF_/testing"); + pref = prefServ.getRootNode().node("/profile/" + locationString + "/_SELF_/testing"); } catch (IllegalArgumentException e) { fail("IllegalArgumentException when accessing preferences for self profile"); } @@ -68,7 +104,7 @@ public class ProfilePreferencesTest extends AbstractProvisioningTest { // } waitForSave(); - pref = prefServ.getRootNode().node("/profile/_SELF_/testing"); + pref = prefServ.getRootNode().node("/profile/" + locationString + "/_SELF_/testing"); assertEquals("Value not present after load", value, pref.get(key, null)); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileRegistryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileRegistryTest.java index 7d4af1791..70014395b 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileRegistryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileRegistryTest.java @@ -10,25 +10,21 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.engine; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.Properties; +import java.util.HashMap; +import java.util.Map; import org.eclipse.core.runtime.FileLocator; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.core.eventbus.ProvisioningListener; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.ServiceReference; @@ -50,7 +46,7 @@ public class ProfileRegistryTest extends AbstractProvisioningTest { } protected void getServices() { - registryRef = TestActivator.getContext().getServiceReference(IProfileRegistry.class.getName()); + registryRef = TestActivator.getContext().getServiceReference(IProfileRegistry.SERVICE_NAME); registry = (IProfileRegistry) TestActivator.getContext().getService(registryRef); } @@ -75,12 +71,7 @@ public class ProfileRegistryTest extends AbstractProvisioningTest { private void restart() { try { ungetServices(); - TestActivator.getBundle("org.eclipse.equinox.p2.exemplarysetup").stop(); - TestActivator.getBundle("org.eclipse.equinox.p2.exemplarysetup").start(); - //ensure artifact repository manager is registered with event bus. See bug 247584 - IProvisioningEventBus bus = (IProvisioningEventBus) ServiceHelper.getService(TestActivator.getContext(), IProvisioningEventBus.SERVICE_NAME); - IArtifactRepositoryManager repoMan = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IArtifactRepositoryManager.class.getName()); - bus.addListener((ProvisioningListener) repoMan); + restartBundle(TestActivator.getBundle("org.eclipse.equinox.p2.exemplarysetup")); getServices(); } catch (Exception e) { fail(); @@ -123,7 +114,7 @@ public class ProfileRegistryTest extends AbstractProvisioningTest { public void testPropertyPeristence() throws ProvisionException { assertNull(registry.getProfile(PROFILE_NAME)); - Properties properties = new Properties(); + Map properties = new HashMap(); properties.put("test", "test"); Profile profile = (Profile) registry.addProfile(PROFILE_NAME, properties); assertTrue(profile.getProperties().containsKey("test")); @@ -148,28 +139,28 @@ public class ProfileRegistryTest extends AbstractProvisioningTest { public void testIUPeristence() throws ProvisionException { assertNull(registry.getProfile(PROFILE_NAME)); Profile profile = (Profile) registry.addProfile(PROFILE_NAME); - assertEquals(0, profile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertTrue(profile.query(InstallableUnitQuery.ANY, null).isEmpty()); profile.addInstallableUnit(createIU("test")); - assertEquals(1, profile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(1, queryResultSize(profile.query(InstallableUnitQuery.ANY, null))); saveProfile(registry, profile); restart(); profile = (Profile) registry.getProfile(PROFILE_NAME); - assertEquals(1, profile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(1, queryResultSize(profile.query(InstallableUnitQuery.ANY, null))); profile.removeInstallableUnit(createIU("test")); - assertEquals(0, profile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertTrue(profile.query(InstallableUnitQuery.ANY, null).isEmpty()); saveProfile(registry, profile); restart(); profile = (Profile) registry.getProfile(PROFILE_NAME); - assertEquals(0, profile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertTrue(profile.query(InstallableUnitQuery.ANY, null).isEmpty()); registry.removeProfile(PROFILE_NAME); restart(); assertNull(registry.getProfile(PROFILE_NAME)); } public void testIUPropertyPeristence() throws ProvisionException { - Properties properties = new Properties(); + Map properties = new HashMap(); properties.put("test", "test"); assertNull(registry.getProfile(PROFILE_NAME)); Profile profile = (Profile) registry.addProfile(PROFILE_NAME); @@ -202,7 +193,7 @@ public class ProfileRegistryTest extends AbstractProvisioningTest { public void testTimestampedProfiles() throws ProvisionException { assertNull(registry.getProfile(PROFILE_NAME)); - Properties properties = new Properties(); + Map properties = new HashMap(); properties.put("test", "test"); Profile profile = (Profile) registry.addProfile(PROFILE_NAME, properties); long oldtimestamp = profile.getTimestamp(); @@ -229,7 +220,7 @@ public class ProfileRegistryTest extends AbstractProvisioningTest { public void testIsCurrent() throws Exception { assertNull(registry.getProfile(PROFILE_NAME)); - Properties properties = new Properties(); + Map properties = new HashMap(); properties.put("test", "test"); Profile profile = (Profile) registry.addProfile(PROFILE_NAME, properties); @@ -255,7 +246,7 @@ public class ProfileRegistryTest extends AbstractProvisioningTest { profile = (Profile) registry.getProfile(PROFILE_NAME); assertTrue(registry.isCurrent(profile)); - AgentLocation agentLocation = (AgentLocation) ServiceHelper.getService(TestActivator.getContext(), AgentLocation.SERVICE_NAME); + IAgentLocation agentLocation = getAgentLocation(); SimpleProfileRegistry simpleRegistry2 = new SimpleProfileRegistry(SimpleProfileRegistry.getDefaultRegistryDirectory(agentLocation)); profile2 = (Profile) simpleRegistry2.getProfile(PROFILE_NAME); simpleRegistry2.lockProfile(profile2); @@ -672,7 +663,7 @@ public class ProfileRegistryTest extends AbstractProvisioningTest { public void testRemoveProfileTimestamps() throws ProvisionException { assertNull(registry.getProfile(PROFILE_NAME)); - Properties properties = new Properties(); + Map properties = new HashMap(); properties.put("test", "test"); Profile profile = (Profile) registry.addProfile(PROFILE_NAME, properties); assertTrue(profile.getProperties().containsKey("test")); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileTest.java index 914d5c89b..e6a70f064 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileTest.java @@ -10,21 +10,20 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.engine; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.*; import java.util.*; import java.util.Map.Entry; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; -import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.BundleContext; import org.xml.sax.*; @@ -62,9 +61,9 @@ public class ProfileTest extends AbstractProvisioningTest { } public void testAddRemoveProperty() throws ProvisionException { - IProfileRegistry registry = (IProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry registry = getProfileRegistry(); assertNull(registry.getProfile(PROFILE_NAME)); - Properties properties = new Properties(); + Map properties = new HashMap(); properties.put("test", "test"); Profile profile = (Profile) registry.addProfile(PROFILE_NAME, properties); assertTrue(profile.getProperties().containsKey("test")); @@ -80,57 +79,57 @@ public class ProfileTest extends AbstractProvisioningTest { } public void testAddRemoveIU() throws ProvisionException { - IProfileRegistry registry = (IProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry registry = getProfileRegistry(); assertNull(registry.getProfile(PROFILE_NAME)); Profile profile = (Profile) registry.addProfile(PROFILE_NAME); - assertTrue(profile.query(InstallableUnitQuery.ANY, new Collector(), null).isEmpty()); + assertTrue(profile.query(InstallableUnitQuery.ANY, null).isEmpty()); profile.addInstallableUnit(createIU("test")); - assertEquals(1, profile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(1, queryResultSize(profile.query(InstallableUnitQuery.ANY, null))); profile.removeInstallableUnit(createIU("test")); - assertTrue(profile.query(InstallableUnitQuery.ANY, new Collector(), null).isEmpty()); + assertTrue(profile.query(InstallableUnitQuery.ANY, null).isEmpty()); registry.removeProfile(PROFILE_NAME); assertNull(registry.getProfile(PROFILE_NAME)); } public void testAddIUTwice() throws ProvisionException { - IProfileRegistry registry = (IProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry registry = getProfileRegistry(); assertNull(registry.getProfile(PROFILE_NAME)); Profile profile = (Profile) registry.addProfile(PROFILE_NAME); - assertTrue(profile.query(InstallableUnitQuery.ANY, new Collector(), null).isEmpty()); + assertTrue(profile.query(InstallableUnitQuery.ANY, null).isEmpty()); profile.addInstallableUnit(createIU("test")); - assertEquals(1, profile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(1, queryResultSize(profile.query(InstallableUnitQuery.ANY, null))); profile.addInstallableUnit(createIU("test")); - assertEquals(1, profile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(1, queryResultSize(profile.query(InstallableUnitQuery.ANY, null))); registry.removeProfile(PROFILE_NAME); assertNull(registry.getProfile(PROFILE_NAME)); } public void testAddRemoveIUProperty() throws ProvisionException { - IProfileRegistry registry = (IProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry registry = getProfileRegistry(); assertNull(registry.getProfile(PROFILE_NAME)); Profile profile = (Profile) registry.addProfile(PROFILE_NAME); - assertTrue(profile.query(InstallableUnitQuery.ANY, new Collector(), null).isEmpty()); + assertTrue(profile.query(InstallableUnitQuery.ANY, null).isEmpty()); profile.addInstallableUnit(createIU("test")); assertNull(profile.getInstallableUnitProperty(createIU("test"), "test")); assertNull(profile.removeInstallableUnitProperty(createIU("test"), "test")); - Properties iuProperties = new Properties(); + Map iuProperties = new HashMap(); iuProperties.put("test", "test"); profile.addInstallableUnitProperties(createIU("test"), iuProperties); assertEquals("test", profile.getInstallableUnitProperty(createIU("test"), "test")); profile.removeInstallableUnitProperty(createIU("test"), "test"); assertNull(profile.getInstallableUnitProperty(createIU("test"), "test")); - assertEquals(1, profile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(1, queryResultSize(profile.query(InstallableUnitQuery.ANY, null))); registry.removeProfile(PROFILE_NAME); assertNull(registry.getProfile(PROFILE_NAME)); } public void testAvailable() throws ProvisionException { - IProfileRegistry registry = (IProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry registry = getProfileRegistry(); assertNull(registry.getProfile(PROFILE_NAME)); Profile profile = (Profile) registry.addProfile(PROFILE_NAME); - assertTrue(profile.available(InstallableUnitQuery.ANY, new Collector(), null).isEmpty()); + assertTrue(profile.available(InstallableUnitQuery.ANY, null).isEmpty()); profile.addInstallableUnit(createIU("test")); - assertEquals(1, profile.available(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(1, queryResultSize(profile.available(InstallableUnitQuery.ANY, null))); profile.setSurrogateProfileHandler(new ISurrogateProfileHandler() { public IProfile createProfile(String id) { return null; @@ -140,200 +139,22 @@ public class ProfileTest extends AbstractProvisioningTest { return false; } - public Collector queryProfile(IProfile profile, Query query, Collector collector, IProgressMonitor monitor) { - return collector; + public IQueryResult queryProfile(IProfile profile, IQuery query, IProgressMonitor monitor) { + return new Collector(); } public boolean updateProfile(IProfile selfProfile) { return false; } }); - assertTrue(profile.available(InstallableUnitQuery.ANY, new Collector(), null).isEmpty()); - assertTrue(profile.snapshot().available(InstallableUnitQuery.ANY, new Collector(), null).isEmpty()); + assertTrue(profile.available(InstallableUnitQuery.ANY, null).isEmpty()); + assertTrue(profile.snapshot().available(InstallableUnitQuery.ANY, null).isEmpty()); registry.removeProfile(PROFILE_NAME); assertNull(registry.getProfile(PROFILE_NAME)); } - public void testNestedProfileStructure() { - Properties properties = new Properties(); - properties.put("test", "test"); - IProfile parent = createProfile("parent", null, properties); - IProfile child = createProfile("child", "parent"); - parent = getProfile("parent"); - assertTrue(parent.hasSubProfiles()); - assertFalse(child.hasSubProfiles()); - assertNotNull(parent.getLocalProperty("test")); - assertNotNull(child.getProperty("test")); - assertNotNull(child.getProperties().get("test")); - assertNull(child.getLocalProperty("test")); - assertNull(child.getLocalProperties().get("test")); - - assertTrue("Parentless profile should be a root.", parent.isRootProfile()); - assertFalse("Child profile should not be a root.", child.isRootProfile()); - assertTrue("Parent should be parent of child", child.getParentProfile().getProfileId().equals(parent.getProfileId())); - assertTrue("Parent should have one child.", parent.getSubProfileIds().length == 1); - assertTrue("Child should have no children.", child.getSubProfileIds().length == 0); - - IProfile grandchild = createProfile("grand", "child"); - child = getProfile("child"); - assertFalse("Grandchild profile should not be a root.", grandchild.isRootProfile()); - assertTrue("Parent should have one child.", parent.getSubProfileIds().length == 1); - assertTrue("Child should have one child.", child.getSubProfileIds().length == 1); - assertTrue("Grandparent of grandchild should be parent of child.", grandchild.getParentProfile().getParentProfile().getProfileId().equals(parent.getProfileId())); - } - - /* The test profile has the following structure and properties where - * id{x,y} indicates a profile with id "id" and properties defined - * with keys "x" and "y" - * - * grandchild00{foo} - * / - * / - * child0{foo} | --- grandchild01{} - * / \ - * / \ - * / grandchild01{bar} - * parent{foo,bar} | - * \ grandchild10{foo} - * \ / - * child1{} | - * \ - * grandchild11{} - * - */ - private static String parentId = "parent"; - private static String child0Id = "child0"; - private static String grandchild00Id = "grand00"; - private static String grandchild01Id = "grand01"; - private static String grandchild02Id = "grand02"; - private static String child1Id = "child1"; - private static String grandchild10Id = "grand10"; - private static String grandchild11Id = "grand11"; - - private static String key = "org.eclipse.p2.foo"; - private static String parentValue = "parent"; - private static String child0Value = "child0"; - private static String grandchild00Value = "grandchild00"; - private static String grandchild02Value = "grandchild02"; - private static String grandchild10Value = "grandchild10"; - private static String otherKey = "org.eclipse.p2.bar"; - private static String otherValue = "other"; - - // Create the profiles and test get after set - // for associated properties. - private IProfile[] createTestProfiles() { - - Map properties = new HashMap(); - - properties.put(key, parentValue); - properties.put(otherKey, otherValue); - IProfile parent = createProfile(parentId, null, properties); - properties.clear(); - assertTrue(parentValue.equals(parent.getProperty(key))); - assertTrue(otherValue.equals(parent.getProperty(otherKey))); - - properties.put(key, child0Value); - IProfile child0 = createProfile(child0Id, parentId, properties); - properties.clear(); - assertTrue(child0Value.equals(child0.getProperty(key))); - - IProfile child1 = createProfile(child1Id, parentId, properties); - // no value in child1 - - properties.put(key, grandchild00Value); - IProfile grandchild00 = createProfile(grandchild00Id, child0Id, properties); - properties.clear(); - assertTrue(grandchild00Value.equals(grandchild00.getProperty(key))); - - IProfile grandchild01 = createProfile(grandchild01Id, child0Id); - // no value in grandchild01 - - properties.put(otherKey, grandchild02Value); - IProfile grandchild02 = createProfile(grandchild02Id, child0Id, properties); - properties.clear(); - assertTrue(grandchild02Value.equals(grandchild02.getProperty(otherKey))); - - properties.put(key, grandchild10Value); - IProfile grandchild10 = createProfile(grandchild10Id, child1Id, properties); - properties.clear(); - assertTrue(grandchild10Value.equals(grandchild10.getProperty(key))); - - IProfile grandchild11 = createProfile(grandchild11Id, child1Id); - // no value in grandchild11 - - parent = getProfile(parentId); - child0 = getProfile(child0Id); - child1 = getProfile(child1Id); - grandchild00 = getProfile(grandchild00Id); - grandchild01 = getProfile(grandchild01Id); - grandchild02 = getProfile(grandchild02Id); - grandchild10 = getProfile(grandchild10Id); - grandchild11 = getProfile(grandchild11Id); - - IProfile[] profiles = {parent, child0, child1, grandchild00, grandchild01, grandchild02, grandchild10, grandchild11}; - return profiles; - } - - public void testNestedProfileProperties() { - validateProfiles(createTestProfiles()); - } - - public void validateProfiles(IProfile[] profiles) { - IProfile parent = profiles[0]; - IProfile child0 = profiles[1]; - IProfile child1 = profiles[2]; - IProfile grandchild00 = profiles[3]; - IProfile grandchild01 = profiles[4]; - IProfile grandchild02 = profiles[5]; - IProfile grandchild10 = profiles[6]; - IProfile grandchild11 = profiles[7]; - - assertTrue(parentId.equals(parent.getProfileId())); - assertTrue("Profile should have 3 local properties", parent.getLocalProperties().size() == 2); - assertTrue(parentValue.equals(parent.getProperty(key))); - assertTrue(otherValue.equals(parent.getProperty(otherKey))); - assertTrue("Parent should have 2 children.", parent.getSubProfileIds().length == 2); - - assertTrue(child0Id.equals(child0.getProfileId())); - assertTrue("First Child should have 1 local properties.", child0.getLocalProperties().size() == 1); - assertTrue(child0Value.equals(child0.getProperty(key))); - assertTrue(otherValue.equals(child0.getProperty(otherKey))); - assertTrue("First Child should have 3 children.", child0.getSubProfileIds().length == 3); - - assertTrue(child1Id.equals(child1.getProfileId())); - assertTrue("Second Child should have 0 local properties.", child1.getLocalProperties().size() == 0); - assertTrue(parentValue.equals(child1.getProperty(key))); - assertTrue(otherValue.equals(child1.getProperty(otherKey))); - assertTrue("Second Child should have 2 children.", child1.getSubProfileIds().length == 2); - - assertTrue(grandchild00Id.equals(grandchild00.getProfileId())); - assertTrue("First Grandchild of first Child should have 1 property.", grandchild00.getLocalProperties().size() == 1); - assertTrue(grandchild00Value.equals(grandchild00.getProperty(key))); - assertTrue(otherValue.equals(grandchild00.getProperty(otherKey))); - - assertTrue(grandchild01Id.equals(grandchild01.getProfileId())); - assertTrue("Second Grandchild of first Child should have 0 properties.", grandchild01.getLocalProperties().size() == 0); - assertTrue(child0Value.equals(grandchild01.getProperty(key))); - assertTrue(otherValue.equals(grandchild01.getProperty(otherKey))); - - assertTrue(grandchild02Id.equals(grandchild02.getProfileId())); - assertTrue("Third Grandchild of first Child should have 1 property.", grandchild02.getLocalProperties().size() == 1); - assertTrue(child0Value.equals(grandchild02.getProperty(key))); - assertTrue(grandchild02Value.equals(grandchild02.getProperty(otherKey))); - - assertTrue(grandchild10Id.equals(grandchild10.getProfileId())); - assertTrue("First Grandchild of second Child should have 1 property.", grandchild10.getLocalProperties().size() == 1); - assertTrue(grandchild10Value.equals(grandchild10.getProperty(key))); - assertTrue(otherValue.equals(grandchild10.getProperty(otherKey))); - - assertTrue(grandchild11Id.equals(grandchild11.getProfileId())); - assertTrue("Second Grandchild of second Child should have 0 properties.", grandchild11.getLocalProperties().size() == 0); - assertTrue(parentValue.equals(grandchild11.getProperty(key))); - assertTrue(otherValue.equals(grandchild11.getProperty(otherKey))); - } - private static String PROFILE_TEST_TARGET = "profileTest"; - private static Version PROFILE_TEST_VERSION = new Version("0.0.1"); + private static Version PROFILE_TEST_VERSION = Version.create("0.0.1"); private static String PROFILE_TEST_ELEMENT = "test"; public static final String PROFILES_ELEMENT = "profiles"; //$NON-NLS-1$ @@ -529,35 +350,4 @@ public class ProfileTest extends AbstractProvisioningTest { return result; } } - - public void testProfilePersistence() throws IOException { - IProfile[] testProfiles = createTestProfiles(); - ByteArrayOutputStream output0 = new ByteArrayOutputStream(1492); - ProfileStringWriter writer0 = new ProfileStringWriter(output0); - writer0.writeTest(testProfiles); - String profileText0 = output0.toString(); - output0.close(); - - ProfileStringParser parser = new ProfileStringParser(TestActivator.context, TestActivator.PI_PROV_TESTS); - parser.parse(profileText0); - assertTrue("Error parsing test profile: " + parser.getStatus().getMessage(), parser.getStatus().isOK()); - Map profileMap = (Map) parser.getRootObject(); - IProfile parent = (IProfile) profileMap.get(parentId); - IProfile child0 = (IProfile) profileMap.get(child0Id); - IProfile child1 = (IProfile) profileMap.get(child1Id); - IProfile grandchild00 = (IProfile) profileMap.get(grandchild00Id); - IProfile grandchild01 = (IProfile) profileMap.get(grandchild01Id); - IProfile grandchild02 = (IProfile) profileMap.get(grandchild02Id); - IProfile grandchild10 = (IProfile) profileMap.get(grandchild10Id); - IProfile grandchild11 = (IProfile) profileMap.get(grandchild11Id); - IProfile[] profiles = {parent, child0, child1, grandchild00, grandchild01, grandchild02, grandchild10, grandchild11}; - validateProfiles(profiles); - ByteArrayOutputStream output1 = new ByteArrayOutputStream(1492); - ProfileStringWriter writer = new ProfileStringWriter(output1); - - writer.writeTest(profiles); - String profileText1 = output1.toString(); - output1.close(); - assertTrue("Profile write after read after write produced different XML", profileText1.equals(profileText0)); - } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/SurrogateProfileHandlerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/SurrogateProfileHandlerTest.java index bb172d214..26784f4a6 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/SurrogateProfileHandlerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/SurrogateProfileHandlerTest.java @@ -11,18 +11,14 @@ package org.eclipse.equinox.p2.tests.engine; import java.lang.reflect.Field; -import java.util.HashSet; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.equinox.internal.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; -import org.eclipse.equinox.p2.tests.TestActivator; -import org.osgi.framework.ServiceReference; public class SurrogateProfileHandlerTest extends AbstractProvisioningTest { private static final String PROFILE_NAME = "profile.SurrogateProfileHandlerTest"; @@ -33,7 +29,6 @@ public class SurrogateProfileHandlerTest extends AbstractProvisioningTest { return new TestSuite(SurrogateProfileHandlerTest.class); } - private ServiceReference registryRef; private IProfileRegistry registry; private SurrogateProfileHandler handler; @@ -51,13 +46,11 @@ public class SurrogateProfileHandlerTest extends AbstractProvisioningTest { } protected void getServices() { - registryRef = TestActivator.getContext().getServiceReference(IProfileRegistry.class.getName()); - registry = (IProfileRegistry) TestActivator.getContext().getService(registryRef); + registry = getProfileRegistry(); } private void ungetServices() { registry = null; - TestActivator.getContext().ungetService(registryRef); } protected void setUp() throws Exception { @@ -89,8 +82,8 @@ public class SurrogateProfileHandlerTest extends AbstractProvisioningTest { saveProfile(registry, profile); IProfile surrogateProfile = handler.createProfile(PROFILE_NAME); assertTrue(handler.isSurrogate(surrogateProfile)); - assertEquals(0, surrogateProfile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); - assertEquals(1, surrogateProfile.available(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(0, queryResultSize(surrogateProfile.query(InstallableUnitQuery.ANY, null))); + assertEquals(1, queryResultSize(surrogateProfile.available(InstallableUnitQuery.ANY, null))); } public void testUpdateProfile() throws ProvisionException { @@ -99,34 +92,34 @@ public class SurrogateProfileHandlerTest extends AbstractProvisioningTest { profile.setInstallableUnitProperty(createIU("test"), PROP_TYPE_ROOT, Boolean.TRUE.toString()); saveProfile(registry, profile); IProfile surrogateProfile = handler.createProfile(PROFILE_NAME); - assertEquals(1, surrogateProfile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(1, queryResultSize(surrogateProfile.query(InstallableUnitQuery.ANY, null))); // HashSet used here to eliminate duplicates - assertEquals(1, new HashSet(surrogateProfile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection()).size()); + assertEquals(1, queryResultUniqueSize(surrogateProfile.available(InstallableUnitQuery.ANY, null))); handler.updateProfile(surrogateProfile); - assertEquals(1, surrogateProfile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(1, queryResultSize(surrogateProfile.query(InstallableUnitQuery.ANY, null))); // HashSet used here to eliminate duplicates - assertEquals(1, new HashSet(surrogateProfile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection()).size()); + assertEquals(1, queryResultUniqueSize(surrogateProfile.available(InstallableUnitQuery.ANY, null))); Profile writeableSurrogateProfile = (Profile) surrogateProfile; writeableSurrogateProfile.addInstallableUnit(createIU("surrogate.test")); writeableSurrogateProfile.setInstallableUnitProperty(createIU("surrogate.test"), PROP_TYPE_ROOT, Boolean.TRUE.toString()); - assertEquals(2, surrogateProfile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(2, queryResultSize(surrogateProfile.query(InstallableUnitQuery.ANY, null))); // HashSet used here to eliminate duplicates - assertEquals(2, new HashSet(surrogateProfile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection()).size()); + assertEquals(2, queryResultUniqueSize(surrogateProfile.available(InstallableUnitQuery.ANY, null))); profile.addInstallableUnit(createIU("test2")); profile.setInstallableUnitProperty(createIU("test2"), PROP_TYPE_ROOT, Boolean.TRUE.toString()); saveProfile(registry, profile); - assertEquals(2, surrogateProfile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(2, queryResultSize(surrogateProfile.query(InstallableUnitQuery.ANY, null))); // HashSet used here to eliminate duplicates - assertEquals(3, new HashSet(surrogateProfile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection()).size()); + assertEquals(3, queryResultUniqueSize(surrogateProfile.available(InstallableUnitQuery.ANY, null))); //Strictly speaking this should not be necessary however without resetting the timestamp this test will sometimes fail writeableSurrogateProfile.setProperty(PROP_SHARED_TIMESTAMP, null); handler.updateProfile(surrogateProfile); - assertEquals(3, surrogateProfile.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(3, queryResultSize(surrogateProfile.query(InstallableUnitQuery.ANY, null))); // HashSet used here to eliminate duplicates - assertEquals(3, new HashSet(surrogateProfile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection()).size()); + assertEquals(3, queryResultUniqueSize(surrogateProfile.available(InstallableUnitQuery.ANY, null))); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/TouchpointManagerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/TouchpointManagerTest.java index c296e822c..762e0912e 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/TouchpointManagerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/TouchpointManagerTest.java @@ -46,7 +46,8 @@ public class TouchpointManagerTest extends AbstractProvisioningTest { assertNotNull(manager.getTouchpoint("phaseTest", null)); } - public void testDynamicTouchpoint() throws MalformedURLException, BundleException, InterruptedException { + // temporarily disabling this test until API is done + public void DISABLED_testDynamicTouchpoint() throws MalformedURLException, BundleException, InterruptedException { TouchpointManager manager = new TouchpointManager(); assertNull(manager.getTouchpoint("dummy", "1.0.0")); File dummy = getTestData("0.1", "/testData/engineTest/dummy.touchpointAndAction_1.0.0.jar"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/TouchpointTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/TouchpointTest.java index b386d6953..8bee0b3ce 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/TouchpointTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/TouchpointTest.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.engine; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.util.Map; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.internal.p2.engine.PhaseSet; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.Touchpoint; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.eclipse.equinox.p2.tests.engine.PhaseTest.TestPhaseSet; @@ -144,7 +146,8 @@ public class TouchpointTest extends AbstractProvisioningTest { testTouchpoint.resetCounters(); PhaseSet phaseSet = new TestPhaseSet(); IProfile profile = createProfile("testProfile"); - engine.perform(profile, phaseSet, new InstallableUnitOperand[] {new InstallableUnitOperand(null, createTestIU("operandTest"))}, null, new NullProgressMonitor()); + final InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, createTestIU("operandTest"))}; + engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); assertEquals(1, testTouchpoint.initializeOperand); assertEquals(1, testTouchpoint.completeOperand); } @@ -154,7 +157,8 @@ public class TouchpointTest extends AbstractProvisioningTest { testTouchpoint.resetCounters(); PhaseSet phaseSet = new TestPhaseSet(); IProfile profile = createProfile("testProfile"); - engine.perform(profile, phaseSet, new InstallableUnitOperand[] {new InstallableUnitOperand(null, createTestIU("phaseTest"))}, null, new NullProgressMonitor()); + final InstallableUnitOperand[] operands = new InstallableUnitOperand[] {new InstallableUnitOperand(null, createTestIU("phaseTest"))}; + engine.perform(engine.createCustomPlan(profile, operands, null), phaseSet, new NullProgressMonitor()); assertEquals(1, testTouchpoint.initializePhase); assertEquals(1, testTouchpoint.completePhase); } @@ -162,8 +166,8 @@ public class TouchpointTest extends AbstractProvisioningTest { private IInstallableUnit createTestIU(String touchpointName) { InstallableUnitDescription description = new MetadataFactory.InstallableUnitDescription(); description.setId("org.eclipse.test"); - description.setVersion(new Version("1.0.0")); - description.setTouchpointType(MetadataFactory.createTouchpointType(touchpointName, new Version("1.0.0"))); + description.setVersion(Version.create("1.0.0")); + description.setTouchpointType(MetadataFactory.createTouchpointType(touchpointName, Version.create("1.0.0"))); IInstallableUnit unit = MetadataFactory.createInstallableUnit(description); return createResolvedIU(unit); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/extensionlocation/ExtensionLocationArtifactRepositoryFactoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/extensionlocation/ExtensionLocationArtifactRepositoryFactoryTest.java index b304bdca0..7df721d5c 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/extensionlocation/ExtensionLocationArtifactRepositoryFactoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/extensionlocation/ExtensionLocationArtifactRepositoryFactoryTest.java @@ -16,9 +16,9 @@ import java.net.*; import org.eclipse.core.runtime.FileLocator; import org.eclipse.equinox.internal.p2.extensionlocation.Constants; import org.eclipse.equinox.internal.p2.extensionlocation.ExtensionLocationArtifactRepositoryFactory; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; @@ -172,7 +172,7 @@ public class ExtensionLocationArtifactRepositoryFactoryTest extends AbstractProv URI location = directory.toURI(); try { IArtifactRepository repo = factory.load(location, 0, getMonitor()); - if (repo.getArtifactKeys().length != 2) + if (getArtifactKeyCount(repo) != 2) fail("2.1"); } catch (ProvisionException ex) { fail("2.0"); @@ -188,7 +188,7 @@ public class ExtensionLocationArtifactRepositoryFactoryTest extends AbstractProv URI location = directory.toURI(); try { IArtifactRepository repo = factory.load(location, 0, getMonitor()); - if (repo.getArtifactKeys().length != 1) + if (getArtifactKeyCount(repo) != 1) fail("2.1"); } catch (ProvisionException ex) { fail("2.0"); @@ -204,7 +204,7 @@ public class ExtensionLocationArtifactRepositoryFactoryTest extends AbstractProv URI location = directory.toURI(); try { IArtifactRepository repo = factory.load(location, 0, getMonitor()); - if (repo.getArtifactKeys().length != 1) + if (getArtifactKeyCount(repo) != 1) fail("2.1"); } catch (ProvisionException ex) { fail("2.0"); @@ -218,7 +218,7 @@ public class ExtensionLocationArtifactRepositoryFactoryTest extends AbstractProv copy("1.1", getTestData("1.1", "/testData/extensionlocation"), eclipseDirectory); try { IArtifactRepository repo = factory.load(directory.toURI(), 0, getMonitor()); - if (repo.getArtifactKeys().length != 2) + if (getArtifactKeyCount(repo) != 2) fail("1.0"); } catch (ProvisionException e) { fail("0.5", e); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/extensionlocation/ExtensionLocationMetadataRepositoryFactoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/extensionlocation/ExtensionLocationMetadataRepositoryFactoryTest.java index 82af17cd1..0049f8def 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/extensionlocation/ExtensionLocationMetadataRepositoryFactoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/extensionlocation/ExtensionLocationMetadataRepositoryFactoryTest.java @@ -15,11 +15,10 @@ import java.io.IOException; import java.net.*; import org.eclipse.equinox.internal.p2.extensionlocation.Constants; import org.eclipse.equinox.internal.p2.extensionlocation.ExtensionLocationMetadataRepositoryFactory; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class ExtensionLocationMetadataRepositoryFactoryTest extends AbstractProvisioningTest { @@ -164,7 +163,7 @@ public class ExtensionLocationMetadataRepositoryFactoryTest extends AbstractProv URI location = directory.toURI(); try { IMetadataRepository repo = factory.load(location, 0, getMonitor()); - if (repo.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection().size() != 3) + if (queryResultSize(repo.query(InstallableUnitQuery.ANY, null)) != 3) fail("2.99"); } catch (ProvisionException ex) { fail("2.0"); @@ -180,7 +179,7 @@ public class ExtensionLocationMetadataRepositoryFactoryTest extends AbstractProv URI location = directory.toURI(); try { IMetadataRepository repo = factory.load(location, 0, getMonitor()); - if (repo.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection().size() != 2) + if (queryResultSize(repo.query(InstallableUnitQuery.ANY, null)) != 2) fail("3.0"); } catch (ProvisionException ex) { fail("2.0"); @@ -196,7 +195,7 @@ public class ExtensionLocationMetadataRepositoryFactoryTest extends AbstractProv URI location = directory.toURI(); try { IMetadataRepository repo = factory.load(location, 0, getMonitor()); - if (repo.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection().size() != 1) + if (queryResultSize(repo.query(InstallableUnitQuery.ANY, null)) != 1) fail("3.0"); } catch (ProvisionException ex) { fail("2.0"); @@ -210,7 +209,7 @@ public class ExtensionLocationMetadataRepositoryFactoryTest extends AbstractProv copy("1.0", getTestData("1.1", "/testData/extensionlocation"), eclipseDirectory); try { IMetadataRepository repo = factory.load(directory.toURI(), 0, getMonitor()); - if (repo.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection().size() != 3) + if (queryResultSize(repo.query(InstallableUnitQuery.ANY, null)) != 3) fail("3.0"); } catch (ProvisionException e) { fail("2.0"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/AllTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/AllTests.java index 7add26707..00f1b472e 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/AllTests.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/AllTests.java @@ -20,8 +20,8 @@ public class AllTests extends TestCase { public static Test suite() { TestSuite suite = new TestSuite(AllTests.class.getName()); suite.addTestSuite(End2EndTest.class); - // suite.addTest(From35to36.suite()); - // suite.addTest(Install36from35.suite()); + suite.addTest(From35to36.suite()); + suite.addTest(Install36from35.suite()); return suite; } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/DirectorTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/DirectorTest.java index b5413b610..7dc4ddb89 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/DirectorTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/DirectorTest.java @@ -10,23 +10,22 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.full; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.VersionRange; -import java.util.*; +import java.util.HashMap; +import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; import org.eclipse.equinox.internal.provisional.p2.director.IDirector; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.eclipse.osgi.service.environment.EnvironmentInfo; @@ -39,7 +38,7 @@ import org.osgi.framework.ServiceReference; public class DirectorTest extends AbstractProvisioningTest { public void testInstallIU() throws ProvisionException { - ServiceReference sr = TestActivator.context.getServiceReference(IDirector.class.getName()); + ServiceReference sr = TestActivator.context.getServiceReference(IDirector.SERVICE_NAME); if (sr == null) { throw new RuntimeException("Director service not available"); } @@ -48,23 +47,21 @@ public class DirectorTest extends AbstractProvisioningTest { throw new RuntimeException("Director could not be loaded"); } - ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.class.getName()); + ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.SERVICE_NAME); IMetadataRepositoryManager mgr = (IMetadataRepositoryManager) TestActivator.context.getService(sr2); if (mgr == null) { throw new RuntimeException("Repository manager could not be loaded"); } String autoInstall = System.getProperty("eclipse.p2.autoInstall"); - Collector allJobs = mgr.query(new InstallableUnitQuery(autoInstall, VersionRange.emptyRange), new Collector(), null); + IQueryResult allJobs = mgr.query(new InstallableUnitQuery(autoInstall, VersionRange.emptyRange), null); String installFolder = System.getProperty(IProfile.PROP_INSTALL_FOLDER); - ServiceReference profileRegSr = TestActivator.context.getServiceReference(IProfileRegistry.class.getName()); - IProfileRegistry profileRegistry = (IProfileRegistry) TestActivator.context.getService(profileRegSr); + IProfileRegistry profileRegistry = getProfileRegistry(); if (profileRegistry == null) { throw new RuntimeException("Profile registry service not available"); } - String newFlavor = System.getProperty("eclipse.p2.configurationFlavor"); boolean doUninstall = (Boolean.TRUE.equals(Boolean.valueOf(System.getProperty("eclipse.p2.doUninstall")))); IProfile p = null; @@ -75,12 +72,11 @@ public class DirectorTest extends AbstractProvisioningTest { } else { Map properties = new HashMap(); properties.put(IProfile.PROP_INSTALL_FOLDER, installFolder); - properties.put(IProfile.PROP_FLAVOR, newFlavor); EnvironmentInfo info = (EnvironmentInfo) ServiceHelper.getService(TestActivator.getContext(), EnvironmentInfo.class.getName()); if (info != null) properties.put(IProfile.PROP_ENVIRONMENTS, "osgi.os=" + info.getOS() + ",osgi.ws=" + info.getWS() + ",osgi.arch=" + info.getOSArch()); - p = createProfile(installFolder, null, properties); + p = createProfile(installFolder, properties); } IInstallableUnit[] allRoots = new IInstallableUnit[1]; @@ -100,24 +96,8 @@ public class DirectorTest extends AbstractProvisioningTest { if (!operationStatus.isOK()) fail("The installation has failed"); - IInstallableUnit[] result = (IInstallableUnit[]) p.query(new InstallableUnitQuery(allRoots[0].getId(), VersionRange.emptyRange), new Collector(), null).toArray(IInstallableUnit.class); + IInstallableUnit[] result = (IInstallableUnit[]) p.query(new InstallableUnitQuery(allRoots[0].getId(), VersionRange.emptyRange), null).toArray(IInstallableUnit.class); assertEquals(result.length, (!doUninstall ? 1 : 0)); - result = (IInstallableUnit[]) p.query(new InstallableUnitQuery("toolingdefault", VersionRange.emptyRange), new Collector(), null).toArray(IInstallableUnit.class); - - ensureFragmentAssociationIsNotPersisted(mgr); - } - - private void ensureFragmentAssociationIsNotPersisted(IMetadataRepositoryManager mgr) throws ProvisionException { - //Test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=177661 - AgentLocation location = (AgentLocation) ServiceHelper.getService(TestActivator.getContext(), AgentLocation.class.getName()); - mgr.removeRepository(location.getMetadataRepositoryURI()); - IMetadataRepository repo = null; - repo = mgr.loadRepository(location.getMetadataRepositoryURI(), null); - Iterator it = repo.query(new InstallableUnitQuery("org.eclipse.equinox.simpleconfigurator", VersionRange.emptyRange), new Collector(), null).iterator(); - if (!it.hasNext()) - return; - IInstallableUnit sc = (IInstallableUnit) it.next(); - if (sc.isResolved()) - fail("The repository should not store resolved installable units"); + result = (IInstallableUnit[]) p.query(new InstallableUnitQuery("toolingdefault", VersionRange.emptyRange), null).toArray(IInstallableUnit.class); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/End2EndTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/End2EndTest.java index 4cb0f640f..6508f93cf 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/End2EndTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/End2EndTest.java @@ -10,27 +10,29 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.full; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import java.io.IOException; import java.net.URI; -import java.net.URISyntaxException; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.provisional.frameworkadmin.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.director.IDirector; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IProvidedCapability; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.eclipse.osgi.service.environment.EnvironmentInfo; @@ -46,26 +48,21 @@ public class End2EndTest extends AbstractProvisioningTest { private ServiceTracker fwAdminTracker; + private static URI repositoryLocation = URI.create("http://download.eclipse.org/eclipse/updates/3.5"); + + private IProvisioningAgent end2endAgent = null; + protected void setUp() throws Exception { - ServiceReference sr = TestActivator.context.getServiceReference(IDirector.class.getName()); - if (sr == null) - throw new RuntimeException("Director service not available"); - director = createDirector(); - // planner = createPlanner(); - ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.class.getName()); - metadataRepoManager = (IMetadataRepositoryManager) TestActivator.context.getService(sr2); - if (metadataRepoManager == null) - throw new RuntimeException("Metadata repository manager could not be loaded"); - - ServiceReference sr3 = TestActivator.context.getServiceReference(IArtifactRepositoryManager.class.getName()); - artifactRepoManager = (IArtifactRepositoryManager) TestActivator.context.getService(sr3); - if (artifactRepoManager == null) - throw new RuntimeException("Artifact repo manager could not be loaded"); + ServiceReference sr = TestActivator.context.getServiceReference(IProvisioningAgentProvider.SERVICE_NAME); + IProvisioningAgentProvider agentFactory = (IProvisioningAgentProvider) TestActivator.context.getService(sr); + end2endAgent = agentFactory.createAgent(getTempFolder().toURI()); + metadataRepoManager = (IMetadataRepositoryManager) end2endAgent.getService(IMetadataRepositoryManager.SERVICE_NAME); + artifactRepoManager = (IArtifactRepositoryManager) end2endAgent.getService(IArtifactRepositoryManager.SERVICE_NAME); + director = (IDirector) end2endAgent.getService(IDirector.SERVICE_NAME); } protected IProfile createProfile(String profileId, String installFolder) { - ServiceReference profileRegSr = TestActivator.context.getServiceReference(IProfileRegistry.class.getName()); - IProfileRegistry profileRegistry = (IProfileRegistry) TestActivator.context.getService(profileRegSr); + IProfileRegistry profileRegistry = (IProfileRegistry) end2endAgent.getService(IProfileRegistry.SERVICE_NAME); if (profileRegistry == null) { throw new RuntimeException("Profile registry service not available"); } @@ -77,7 +74,11 @@ public class End2EndTest extends AbstractProvisioningTest { properties.put(IProfile.PROP_ENVIRONMENTS, "osgi.os=" + info.getOS() + ",osgi.ws=" + info.getWS() + ",osgi.arch=" + info.getOSArch()); properties.put("org.eclipse.update.install.features", "true"); properties.put(IProfile.PROP_CACHE, installFolder); - return createProfile(profileId, null, properties); + try { + return profileRegistry.addProfile(profileId, properties); + } catch (ProvisionException e) { + throw new IllegalArgumentException(e.getMessage()); + } } public void testInstallSDK35() { @@ -86,16 +87,13 @@ public class End2EndTest extends AbstractProvisioningTest { //Add repository of the release try { - URI location = new URI("http://download.eclipse.org/eclipse/updates/3.5"); - metadataRepoManager.addRepository(location); - metadataRepoManager.setEnabled(location, true); - metadataRepoManager.loadRepository(location, new NullProgressMonitor()); - artifactRepoManager.addRepository(location); - artifactRepoManager.setEnabled(location, true); + metadataRepoManager.addRepository(repositoryLocation); + metadataRepoManager.setEnabled(repositoryLocation, true); + metadataRepoManager.loadRepository(repositoryLocation, new NullProgressMonitor()); + artifactRepoManager.addRepository(repositoryLocation); + artifactRepoManager.setEnabled(repositoryLocation, true); } catch (ProvisionException e) { fail("Exception loading the repository.", e); - } catch (URISyntaxException e) { - fail("Invalid repository location", e); } installPlatform35(profile2, installFolder); @@ -113,19 +111,19 @@ public class End2EndTest extends AbstractProvisioningTest { } private void attemptToUninstallRCP35(IProfile profile2, File installFolder) { - Collector collect = profile2.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); - assertEquals(1, collect.size()); + IQueryResult collect = profile2.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); + assertEquals(1, queryResultSize(collect)); ProfileChangeRequest request = new ProfileChangeRequest(profile2); request.removeInstallableUnits(new IInstallableUnit[] {(IInstallableUnit) collect.iterator().next()}); IStatus s = director.provision(request, null, new NullProgressMonitor()); assertOK("Can not uninstall RCP", s); - assertEquals(1, profile2.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()).size()); + assertEquals(1, queryResultSize(profile2.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()))); } protected void uninstallPlatform(IProfile profile2, File installFolder) { System.out.println("Uninstall the platform"); - Collector collect = profile2.query(new InstallableUnitQuery("org.eclipse.platform.ide"), new Collector(), new NullProgressMonitor()); - assertEquals(1, collect.size()); + IQueryResult collect = profile2.query(new InstallableUnitQuery("org.eclipse.platform.ide"), new NullProgressMonitor()); + assertEquals(1, queryResultSize(collect)); // Collector collect2 = profile2.query(new InstallableUnitQuery("org.eclipse.platform.source.feature.group"), new Collector(), new NullProgressMonitor()); ProfileChangeRequest request = new ProfileChangeRequest(profile2); request.removeInstallableUnits(new IInstallableUnit[] {(IInstallableUnit) collect.iterator().next()});//, (IInstallableUnit) collect2.iterator().next()}); @@ -134,7 +132,7 @@ public class End2EndTest extends AbstractProvisioningTest { } private void rollbackPlatformSource35(IProfile profile2, File installFolder) { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = (IProfileRegistry) end2endAgent.getService(IProfileRegistry.SERVICE_NAME); long[] timestamps = profileRegistry.listProfileTimestamps(profile2.getProfileId()); assertEquals(3, timestamps.length); @@ -149,11 +147,9 @@ public class End2EndTest extends AbstractProvisioningTest { private void installPlatformSource35(IProfile profile2, File installFolder) { final String id = "org.eclipse.platform.source.feature.group"; - final Version version = new Version("3.5.0.v20090611a-9gEeG1HFtQcmRThO4O3aR_fqSMvJR2sJ"); + final Version version = Version.create("3.5.0.v20090611a-9gEeG1HFtQcmRThO4O3aR_fqSMvJR2sJ"); IInstallableUnit toInstall = getIU(id, version); - if (toInstall == null) - assertNotNull(toInstall); ProfileChangeRequest request = new ProfileChangeRequest(profile2); request.addInstallableUnits(new IInstallableUnit[] {toInstall}); @@ -168,13 +164,13 @@ public class End2EndTest extends AbstractProvisioningTest { private void installBogusIU(IProfile profile, File installFolder) { InstallableUnitDescription iud = new MetadataFactory.InstallableUnitDescription(); iud.setId("org.eclipse.equinox.p2.tests.bogusIU.end2end"); - iud.setVersion(new Version("1.0.0")); - iud.setCapabilities(new IProvidedCapability[] {MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, "org.eclipse.equinox.p2.tests.bogusIU.end2end", new Version("1.0.0"))}); + iud.setVersion(Version.create("1.0.0")); + iud.setCapabilities(new IProvidedCapability[] {MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, "org.eclipse.equinox.p2.tests.bogusIU.end2end", Version.create("1.0.0"))}); Map data = new HashMap(); data.put("install", "org.eclipse.equinox.p2.osgi.removeJvmArg(programArg:-XX:+UnlockDiagnosticVMOptions);"); iud.addTouchpointData(MetadataFactory.createTouchpointData(data)); IInstallableUnit bogusIU = MetadataFactory.createInstallableUnit(iud); - iud.setTouchpointType(MetadataFactory.createTouchpointType("org.eclipse.equinox.p2.osgi", new Version("1.0.0"))); + iud.setTouchpointType(MetadataFactory.createTouchpointType("org.eclipse.equinox.p2.osgi", Version.create("1.0.0"))); ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {bogusIU}); IStatus s = director.provision(request, null, new NullProgressMonitor()); @@ -183,13 +179,11 @@ public class End2EndTest extends AbstractProvisioningTest { private void installPlatform35(IProfile profile2, File installFolder) { final String id = "org.eclipse.platform.ide"; - final Version version = new Version("3.5.0.I20090611-1540"); + final Version version = Version.create("3.5.0.I20090611-1540"); //First we install the platform ProfileChangeRequest request = new ProfileChangeRequest(profile2); IInstallableUnit platformIU = getIU(id, version); - if (platformIU == null) - assertNotNull(platformIU); request.addInstallableUnits(new IInstallableUnit[] {platformIU}); IStatus s = director.provision(request, null, new NullProgressMonitor()); @@ -203,11 +197,31 @@ public class End2EndTest extends AbstractProvisioningTest { assertFalse(new File(installFolder, "configuration/org.eclipse.equinox.source").exists()); } + /** + * Returns the IU corresponding to the given id and version. Fails if the IU could + * not be found. Never returns null. + */ public IInstallableUnit getIU(String id, Version v) { - Iterator it = metadataRepoManager.query(new InstallableUnitQuery(id, v), new Collector(), null).iterator(); + final InstallableUnitQuery query = new InstallableUnitQuery(id, v); + Iterator it = metadataRepoManager.query(query, null).iterator(); if (it.hasNext()) return (IInstallableUnit) it.next(); - return null; + //try the repository location directly - retry because eclipse.org can be flaky + Exception failure = null; + for (int i = 0; i < 3; i++) { + try { + IMetadataRepository repo = metadataRepoManager.loadRepository(repositoryLocation, null); + it = repo.query(query, null).iterator(); + if (it.hasNext()) + return (IInstallableUnit) it.next(); + } catch (ProvisionException e) { + failure = e; + } + } + if (failure == null) + failure = new RuntimeException("IU not found"); + fail("Failed to obtain " + id + " version: " + v + " from: " + repositoryLocation, failure); + return null;//will never get here } private void validateInstallContentFor35(File installFolder) { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/RepoValidator.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/RepoValidator.java index d59876f3f..3f4ffac2a 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/RepoValidator.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/RepoValidator.java @@ -14,15 +14,17 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.*; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.ServiceReference; @@ -30,7 +32,7 @@ import org.osgi.framework.ServiceReference; public class RepoValidator extends AbstractProvisioningTest { public void testValidate() throws ProvisionException, URISyntaxException { URI repoLoc = new URI("http://fullmoon.ottawa.ibm.com/eclipse/updates/3.5-I-builds/"); - ServiceReference sr = TestActivator.context.getServiceReference(IPlanner.class.getName()); + ServiceReference sr = TestActivator.context.getServiceReference(IPlanner.SERVICE_NAME); if (sr == null) { throw new RuntimeException("Planner service not available"); } @@ -39,7 +41,7 @@ public class RepoValidator extends AbstractProvisioningTest { throw new RuntimeException("Planner could not be loaded"); } - ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.class.getName()); + ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.SERVICE_NAME); IMetadataRepositoryManager mgr = (IMetadataRepositoryManager) TestActivator.context.getService(sr2); if (mgr == null) { throw new RuntimeException("Repository manager could not be loaded"); @@ -47,18 +49,17 @@ public class RepoValidator extends AbstractProvisioningTest { IMetadataRepository validatedRepo = mgr.loadRepository(repoLoc, null); Map properties = new HashMap(); - properties.put(IInstallableUnit.NAMESPACE_FLAVOR, "tooling"); properties.put("osgi.os", "win32"); properties.put("osgi.ws", "win32"); properties.put("osgi.arch", "x86"); - IProfile p = createProfile("repoValidator", null, properties); + IProfile p = createProfile("repoValidator", properties); - Query q; + IQuery q; q = new InstallableUnitQuery("org.eclipse.rcp.feature.group"); // q = InstallableUnitQuery.ANY; - Collector iusToTest = validatedRepo.query(q, new Collector(), null); + IQueryResult iusToTest = validatedRepo.query(q, null); ProvisioningContext pc = new ProvisioningContext(new URI[] {repoLoc}); for (Iterator iterator = iusToTest.iterator(); iterator.hasNext();) { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/EclipseSDK33Test.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/EclipseSDK33Test.java index 292f19f5e..78ccc09a8 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/EclipseSDK33Test.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/EclipseSDK33Test.java @@ -17,11 +17,11 @@ import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.internal.provisional.p2.metadata.generator.Generator; import org.eclipse.equinox.internal.provisional.p2.metadata.generator.IGeneratorInfo; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.GroupQuery; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; import org.eclipse.equinox.p2.tests.*; import org.osgi.framework.Bundle; @@ -88,15 +88,14 @@ public class EclipseSDK33Test extends AbstractProvisioningTest { assertGroup(unit); IArtifactRepository artifactRepo = generatorInfo.getArtifactRepository(); - IArtifactKey[] keys = artifactRepo.getArtifactKeys(); - assertTrue(keys.length == 11); + assertTrue(getArtifactKeyCount(artifactRepo) == 11); } /** * Asserts that the given IU represents a group. */ private void assertGroup(IInstallableUnit unit) { - assertEquals("IU is not a group", Boolean.TRUE.toString(), unit.getProperty(IInstallableUnit.PROP_TYPE_GROUP)); + assertEquals("IU is not a group", Boolean.TRUE.toString(), GroupQuery.isGroup(unit)); } private IGeneratorInfo createGeneratorInfo() { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/FeatureToIU.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/FeatureToIU.java index 5f677588a..4593802dd 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/FeatureToIU.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/FeatureToIU.java @@ -9,9 +9,9 @@ package org.eclipse.equinox.p2.tests.generator; import org.eclipse.equinox.internal.p2.metadata.generator.features.FeatureParser; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.internal.provisional.p2.metadata.generator.Feature; import org.eclipse.equinox.internal.provisional.p2.metadata.generator.MetadataGeneratorHelper; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class FeatureToIU extends AbstractProvisioningTest { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/PatchIUGeneration.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/PatchIUGeneration.java index 5d015fcb9..5e11a2f35 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/PatchIUGeneration.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/PatchIUGeneration.java @@ -8,13 +8,16 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.generator; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.VersionRange; +import junit.framework.TestCase; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.p2.metadata.generator.features.FeatureParser; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnitPatch; import org.eclipse.equinox.internal.provisional.p2.metadata.generator.Feature; import org.eclipse.equinox.internal.provisional.p2.metadata.generator.MetadataGeneratorHelper; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IInstallableUnitPatch; +import org.eclipse.equinox.p2.metadata.query.PatchQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchIUGeneration extends AbstractProvisioningTest { @@ -31,19 +34,19 @@ public class PatchIUGeneration extends AbstractProvisioningTest { assertEquals(patchIU.getId(), "org.eclipse.jdt.3.2.1.patch.feature.group"); //Check applicability scope - assertEquals(IInstallableUnit.NAMESPACE_IU_ID, patchIU.getApplicabilityScope()[0][0].getNamespace()); - assertEquals("org.eclipse.jdt.feature.group", patchIU.getApplicabilityScope()[0][0].getName()); - assertEquals(new VersionRange("[3.2.1.r321_v20060905-R4CM1Znkvre9wC-,3.2.1.r321_v20060905-R4CM1Znkvre9wC-]"), patchIU.getApplicabilityScope()[0][0].getRange()); + assertEquals(IInstallableUnit.NAMESPACE_IU_ID, ((IRequiredCapability) patchIU.getApplicabilityScope()[0][0]).getNamespace()); + assertEquals("org.eclipse.jdt.feature.group", ((TestCase) patchIU.getApplicabilityScope()[0][0]).getName()); + assertEquals(new VersionRange("[3.2.1.r321_v20060905-R4CM1Znkvre9wC-,3.2.1.r321_v20060905-R4CM1Znkvre9wC-]"), ((IRequiredCapability) patchIU.getApplicabilityScope()[0][0]).getRange()); - assertEquals("org.eclipse.jdt.core", patchIU.getRequirementsChange()[0].applyOn().getName()); - assertEquals(VersionRange.emptyRange, patchIU.getRequirementsChange()[0].applyOn().getRange()); - assertEquals("org.eclipse.jdt.core", patchIU.getRequirementsChange()[0].newValue().getName()); - assertEquals(new VersionRange("[3.2.2,3.2.2]"), patchIU.getRequirementsChange()[0].newValue().getRange()); - assertEquals(Boolean.TRUE.toString(), patchIU.getProperty(IInstallableUnit.PROP_TYPE_PATCH)); - assertEquals(1, patchIU.getRequiredCapabilities().length); - assertEquals(featureIU.getId(), patchIU.getRequiredCapabilities()[0].getName()); - assertEquals("org.eclipse.jdt.feature.group", patchIU.getLifeCycle().getName()); + assertEquals("org.eclipse.jdt.core", patchIU.getRequirementsChange().get(0).applyOn().getName()); + assertEquals(VersionRange.emptyRange, patchIU.getRequirementsChange().get(0).applyOn().getRange()); + assertEquals("org.eclipse.jdt.core", patchIU.getRequirementsChange().get(0).newValue().getName()); + assertEquals(new VersionRange("[3.2.2,3.2.2]"), patchIU.getRequirementsChange().get(0).newValue().getRange()); + assertTrue(PatchQuery.isPatch(patchIU)); + assertEquals(1, patchIU.getRequiredCapabilities().size()); + assertEquals(featureIU.getId(), ((IRequiredCapability) patchIU.getRequiredCapabilities().iterator().next()).getName()); + assertEquals("org.eclipse.jdt.feature.group", ((IRequiredCapability) patchIU.getLifeCycle()).getName()); assertFalse(patchIU.getLifeCycle().isGreedy()); - assertFalse(patchIU.getLifeCycle().isOptional()); + assertFalse(patchIU.getLifeCycle().getMin() == 0); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/TestGeneratorInfo.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/TestGeneratorInfo.java index ea46ad3c3..ef6dc5013 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/TestGeneratorInfo.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/generator/TestGeneratorInfo.java @@ -15,10 +15,10 @@ import java.net.URI; import java.util.*; import org.eclipse.equinox.internal.provisional.frameworkadmin.ConfigData; import org.eclipse.equinox.internal.provisional.frameworkadmin.LauncherData; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.internal.provisional.p2.metadata.generator.IGeneratorInfo; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.TestArtifactRepository; import org.eclipse.equinox.p2.tests.TestMetadataRepository; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/installer/InstallDescriptionParserTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/installer/InstallDescriptionParserTest.java index ceb2ec938..5d6e11047 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/installer/InstallDescriptionParserTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/installer/InstallDescriptionParserTest.java @@ -10,9 +10,7 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.installer; -import org.eclipse.equinox.internal.provisional.p2.metadata.IVersionedId; - -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import java.io.IOException; @@ -20,6 +18,7 @@ import java.net.*; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.installer.InstallDescriptionParser; import org.eclipse.equinox.internal.provisional.p2.installer.InstallDescription; +import org.eclipse.equinox.p2.metadata.IVersionedId; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestData; @@ -117,9 +116,9 @@ public class InstallDescriptionParserTest extends AbstractProvisioningTest { IVersionedId[] roots = description.getRoots(); assertEquals("1.7", 2, roots.length); assertEquals("1.8", "testRoot", roots[0].getId()); - assertEquals("1.9", new Version("2.0"), roots[0].getVersion()); + assertEquals("1.9", Version.create("2.0"), roots[0].getVersion()); assertEquals("1.8", "anotherRoot", roots[1].getId()); - assertEquals("1.9", new Version("1.0.1"), roots[1].getVersion()); + assertEquals("1.9", Version.create("1.0.1"), roots[1].getVersion()); assertTrue("1.10", !description.isAutoStart()); assertEquals("1.11", new Path("/tmp/agent/"), description.getAgentLocation()); assertEquals("1.12", new Path("/tmp/bundles/"), description.getBundleLocation()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/ArtifactKeyParsingTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/ArtifactKeyParsingTest.java index c1b43a84a..0b7e19c85 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/ArtifactKeyParsingTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/ArtifactKeyParsingTest.java @@ -10,11 +10,11 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.metadata; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import junit.framework.TestCase; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; /** * Test ArtifactkeyDeSerializer @@ -22,12 +22,12 @@ import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; public class ArtifactKeyParsingTest extends TestCase { public void testSerialize() { - IArtifactKey key = new ArtifactKey("classifier", "identifier", new Version("1.0")); + IArtifactKey key = new ArtifactKey("classifier", "identifier", Version.create("1.0")); assertEquals("classifier,identifier,1.0.0", key.toExternalForm()); } public void testSerializeEmptyClassifier() { - IArtifactKey key = new ArtifactKey("", "identifier", new Version("1.0")); + IArtifactKey key = new ArtifactKey("", "identifier", Version.create("1.0")); assertEquals(",identifier,1.0.0", key.toExternalForm()); } @@ -36,7 +36,7 @@ public class ArtifactKeyParsingTest extends TestCase { assertNotNull(key); assertEquals("classifier", key.getClassifier()); assertEquals("identifier", key.getId()); - assertEquals(new Version("1.0"), key.getVersion()); + assertEquals(Version.create("1.0"), key.getVersion()); } public void testDeserializeEmptyClassifier() { @@ -44,7 +44,7 @@ public class ArtifactKeyParsingTest extends TestCase { assertNotNull(key); assertEquals("", key.getClassifier()); assertEquals("identifier", key.getId()); - assertEquals(new Version("1.0"), key.getVersion()); + assertEquals(Version.create("1.0"), key.getVersion()); } public void testDeserializeEmptyIdentifier() { @@ -52,7 +52,7 @@ public class ArtifactKeyParsingTest extends TestCase { assertNotNull(key); assertEquals("classifier", key.getClassifier()); assertEquals("", key.getId()); - assertEquals(new Version("1.0"), key.getVersion()); + assertEquals(Version.create("1.0"), key.getVersion()); } public void testDeserializeEmptyVersion() { @@ -60,7 +60,7 @@ public class ArtifactKeyParsingTest extends TestCase { assertNotNull(key); assertEquals("classifier", key.getClassifier()); assertEquals("identifier", key.getId()); - assertEquals(new Version("0.0"), key.getVersion()); + assertEquals(Version.create("0.0"), key.getVersion()); } public void testDeserializeEmptyEverything() { @@ -68,7 +68,7 @@ public class ArtifactKeyParsingTest extends TestCase { assertNotNull(key); assertEquals("", key.getClassifier()); assertEquals("", key.getId()); - assertEquals(new Version("0.0"), key.getVersion()); + assertEquals(Version.create("0.0"), key.getVersion()); } public void testDeserializeTooFewPartsI() { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/FragmentMethodTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/FragmentMethodTest.java index e41a590f2..e6ad021f2 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/FragmentMethodTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/FragmentMethodTest.java @@ -10,16 +10,18 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.metadata; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; -import java.util.HashSet; -import java.util.Iterator; +import java.util.*; import junit.framework.AssertionFailedError; import junit.framework.TestCase; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.metadata.*; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitFragmentDescription; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IProvidedCapability; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class FragmentMethodTest extends TestCase { @@ -28,10 +30,8 @@ public class FragmentMethodTest extends TestCase { private static final String TEST_REQUIRED = "testRequired"; IInstallableUnit iu1; IInstallableUnit iu3; - IRequiredCapability[] iu1Deps; - IRequiredCapability[] iu3Deps; - IProvidedCapability[] iu1Caps; - IProvidedCapability[] iu3Caps; + Collection iu1Caps; + Collection iu3Caps; protected void setUp() throws Exception { super.setUp(); @@ -39,8 +39,6 @@ public class FragmentMethodTest extends TestCase { iu3 = createIUFragment("iu.fragment"); iu1Caps = iu1.getProvidedCapabilities(); iu3Caps = iu3.getProvidedCapabilities(); - iu1Deps = iu1.getRequiredCapabilities(); - iu3Deps = iu3.getRequiredCapabilities(); HashSet hash = new HashSet(); hash.add(iu1); hash.add(iu3); @@ -57,34 +55,30 @@ public class FragmentMethodTest extends TestCase { protected void tearDown() throws Exception { iu1 = null; iu3 = null; - iu1Deps = null; - iu3Deps = null; iu1Caps = null; iu3Caps = null; super.tearDown(); } public void testCapabilities() { - IProvidedCapability[] iuCapabilities = iu1Caps; - IProvidedCapability[] initialFragmentCapabilities = iu3Caps; - - IProvidedCapability[] mergedCapabilities = iu1.getProvidedCapabilities(); - for (int i = 0; i < iuCapabilities.length; i++) { - FragmentTest.assertContainsWithEquals(mergedCapabilities, iuCapabilities[i]); + Collection mergedCapabilities = iu1.getProvidedCapabilities(); + for (IProvidedCapability capability : mergedCapabilities) { + FragmentTest.assertContainsWithEquals(mergedCapabilities, capability); } //The fragment property is not set - assertNull(iu1.getProperty(IInstallableUnit.PROP_TYPE_FRAGMENT)); + assertNull(iu1.getProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT)); //The fragment does not contain iu namespace - for (int i = 0; i < initialFragmentCapabilities.length; i++) { - if (initialFragmentCapabilities[i].getNamespace().equals(IInstallableUnit.NAMESPACE_IU_ID)) { - assertDoesNotContain(mergedCapabilities, initialFragmentCapabilities[i]); + Collection initialFragmentCapabilities = iu3Caps; + for (IProvidedCapability capability : initialFragmentCapabilities) { + if (capability.getNamespace().equals(IInstallableUnit.NAMESPACE_IU_ID)) { + assertDoesNotContain(mergedCapabilities, capability); break; } } - assertEquals("The fragment capabilities should not change", initialFragmentCapabilities, iu3.getProvidedCapabilities(), false); + assertEquals("The fragment capabilities should not change", initialFragmentCapabilities, iu3.getProvidedCapabilities()); } protected void assertEquals(String message, Object[] expected, Object[] actual) { @@ -98,38 +92,22 @@ public class FragmentMethodTest extends TestCase { assertEquals(message, expected[i], actual[i]); } - protected void assertEquals(String message, Object[] expected, Object[] actual, boolean orderImportant) { - // if the order in the array must match exactly, then call the other method - if (orderImportant) { - assertEquals(message, expected, actual); - return; - } - // otherwise use this method and check that the arrays are equal in any order + protected void assertEquals(String message, Collection expected, Collection actual) { if (expected == null && actual == null) return; if (expected == actual) return; if (expected == null || actual == null) assertTrue(message + ".1", false); - if (expected.length != actual.length) + if (expected.size() != actual.size()) assertTrue(message + ".2", false); - boolean[] found = new boolean[expected.length]; - for (int i = 0; i < expected.length; i++) { - for (int j = 0; j < expected.length; j++) { - if (!found[j] && expected[i].equals(actual[j])) - found[j] = true; - } - } - for (int i = 0; i < found.length; i++) - if (!found[i]) - assertTrue(message + ".3." + i, false); + if (!expected.containsAll(actual)) + fail(message + ".3"); } - public static void assertDoesNotContain(Object[] objects, Object searched) { - for (int i = 0; i < objects.length; i++) { - if (objects[i].equals(searched)) - throw new AssertionFailedError("The array should not contain the searched element"); - } + public static void assertDoesNotContain(Collection objects, Object searched) { + if (objects.contains(searched)) + throw new AssertionFailedError("The array should not contain the searched element"); } public void testProperties() { @@ -141,12 +119,12 @@ public class FragmentMethodTest extends TestCase { public IInstallableUnit createIUFragment(String name) { InstallableUnitFragmentDescription iu = new InstallableUnitFragmentDescription(); iu.setId(name); - iu.setVersion(new Version(1, 0, 0)); + iu.setVersion(Version.createOSGi(1, 0, 0)); iu.setTouchpointType(AbstractProvisioningTest.TOUCHPOINT_OSGI); iu.setProperty(PROP_FRAG, "value"); IRequiredCapability[] reqs = new IRequiredCapability[] {MetadataFactory.createRequiredCapability("eclipse.touchpoint", "bundle", VersionRange.emptyRange, null, false, true), MetadataFactory.createRequiredCapability(TEST_REQUIRED, TEST_REQUIRED, VersionRange.emptyRange, null, true, false)}; iu.setHost(reqs); - IProvidedCapability[] cap = new IProvidedCapability[] {MetadataFactory.createProvidedCapability("testCapabilityInFragment", "testCapabilityInFragment", new Version(1, 0, 0))}; + IProvidedCapability[] cap = new IProvidedCapability[] {MetadataFactory.createProvidedCapability("testCapabilityInFragment", "testCapabilityInFragment", Version.createOSGi(1, 0, 0))}; iu.setCapabilities(cap); return MetadataFactory.createInstallableUnitFragment(iu); } @@ -154,10 +132,10 @@ public class FragmentMethodTest extends TestCase { public IInstallableUnit createIU(String name) { InstallableUnitDescription iu = new MetadataFactory.InstallableUnitDescription(); iu.setId(name); - iu.setVersion(new Version(1, 0, 0)); + iu.setVersion(Version.createOSGi(1, 0, 0)); iu.setTouchpointType(AbstractProvisioningTest.TOUCHPOINT_OSGI); iu.setProperty(PROP_IU, "valueIU"); - IProvidedCapability[] cap = new IProvidedCapability[] {MetadataFactory.createProvidedCapability("eclipse.touchpoint", "bundle", new Version(1, 0, 0)), MetadataFactory.createProvidedCapability("testCapability", "testCapability", new Version(1, 0, 0))}; + IProvidedCapability[] cap = new IProvidedCapability[] {MetadataFactory.createProvidedCapability("eclipse.touchpoint", "bundle", Version.createOSGi(1, 0, 0)), MetadataFactory.createProvidedCapability("testCapability", "testCapability", Version.createOSGi(1, 0, 0))}; iu.setCapabilities(cap); return MetadataFactory.createInstallableUnit(iu); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/FragmentTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/FragmentTest.java index 2e8e460ce..e51f887e5 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/FragmentTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/FragmentTest.java @@ -10,13 +10,13 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.metadata; -import java.util.HashMap; -import java.util.Iterator; +import java.util.*; import junit.framework.AssertionFailedError; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.FragmentQuery; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class FragmentTest extends AbstractProvisioningTest { @@ -27,7 +27,7 @@ public class FragmentTest extends AbstractProvisioningTest { IInstallableUnit iu2 = createBundleFragment("iuFragment.test1"); ProfileChangeRequest req = new ProfileChangeRequest(createProfile(getName())); createTestMetdataRepository(new IInstallableUnit[] {iu1, iu2}); - Iterator iterator = createPlanner().getProvisioningPlan(req, null, null).getAdditions().query(InstallableUnitQuery.ANY, new Collector(), null).iterator(); + Iterator iterator = createPlanner().getProvisioningPlan(req, null, null).getAdditions().query(InstallableUnitQuery.ANY, null).iterator(); // ResolutionHelper rh = new ResolutionHelper(new Hashtable(), null); // HashSet set = new HashSet(); // set.add(iu1); @@ -36,8 +36,8 @@ public class FragmentTest extends AbstractProvisioningTest { for (; iterator.hasNext();) { IInstallableUnit iu = (IInstallableUnit) iterator.next(); if (iu.getId().equals(ID)) { - assertEquals(iu.getFragments().length, 1); - assertEquals(iu.getFragments()[0].getId(), "iuFragment.test1"); + assertEquals(iu.getFragments().size(), 1); + assertEquals(iu.getFragments().get(0).getId(), "iuFragment.test1"); } } } @@ -50,48 +50,48 @@ public class FragmentTest extends AbstractProvisioningTest { IInstallableUnit iu2 = createBundleFragment("iuFragment.test1"); ProfileChangeRequest req = new ProfileChangeRequest(createProfile(getName())); createTestMetdataRepository(new IInstallableUnit[] {iu1, iu2, iu3}); - Iterator iterator = createPlanner().getProvisioningPlan(req, null, null).getAdditions().query(InstallableUnitQuery.ANY, new Collector(), null).iterator(); + Iterator iterator = createPlanner().getProvisioningPlan(req, null, null).getAdditions().query(InstallableUnitQuery.ANY, null).iterator(); for (; iterator.hasNext();) { IInstallableUnit iu = (IInstallableUnit) iterator.next(); if (iu.getId().equals(ID1)) { - assertEquals(iu.getFragments().length, 1); - assertEquals(iu.getFragments()[0].getId(), "iuFragment.test1"); + assertEquals(iu.getFragments().size(), 1); + assertEquals(iu.getFragments().get(0).getId(), "iuFragment.test1"); } if (iu.getId().equals(ID3)) { - assertEquals(iu.getFragments().length, 1); - assertEquals(iu.getFragments()[0].getId(), "iuFragment.test1"); + assertEquals(iu.getFragments().size(), 1); + assertEquals(iu.getFragments().get(0).getId(), "iuFragment.test1"); } } } public void testTouchpointData() { - assertEquals(createIUWithTouchpointData().getTouchpointData().length, 1); - assertEquals(createBundleFragment("iuFragment.test1").getTouchpointData().length, 1); + assertEquals(createIUWithTouchpointData().getTouchpointData().size(), 1); + assertEquals(createBundleFragment("iuFragment.test1").getTouchpointData().size(), 1); IInstallableUnit iu1 = createIUWithTouchpointData(); IInstallableUnit iu2 = createBundleFragment("iuFragment.test1"); ProfileChangeRequest req = new ProfileChangeRequest(createProfile(getName())); createTestMetdataRepository(new IInstallableUnit[] {iu1, iu2}); - Iterator iterator = createPlanner().getProvisioningPlan(req, null, null).getAdditions().query(InstallableUnitQuery.ANY, new Collector(), null).iterator(); + Iterator iterator = createPlanner().getProvisioningPlan(req, null, null).getAdditions().query(InstallableUnitQuery.ANY, null).iterator(); for (; iterator.hasNext();) { IInstallableUnit iu = (IInstallableUnit) iterator.next(); if (iu.getId().equals(iu1.getId())) - assertEquals(2, iu.getTouchpointData().length); + assertEquals(2, iu.getTouchpointData().size()); } } public void testFragmentCapability() { IInstallableUnit iu = createBundleFragment("iuFragment.test1"); - assertEquals(Boolean.TRUE.toString(), iu.getProperty(IInstallableUnit.PROP_TYPE_FRAGMENT)); + assertTrue(FragmentQuery.isFragment(iu)); } public void testDefaultIUCapability() { IInstallableUnit iu = createEclipseIU("ui.test1"); - IProvidedCapability[] cap = iu.getProvidedCapabilities(); - for (int i = 0; i < cap.length; i++) { - if (cap[i].getNamespace().equals(IInstallableUnit.NAMESPACE_IU_ID)) { - assertEquals(cap[i].getNamespace(), IInstallableUnit.NAMESPACE_IU_ID); - assertEquals(cap[i].getName(), iu.getId()); + Collection capabilities = iu.getProvidedCapabilities(); + for (IProvidedCapability c : capabilities) { + if (c.getNamespace().equals(IInstallableUnit.NAMESPACE_IU_ID)) { + assertEquals(c.getNamespace(), IInstallableUnit.NAMESPACE_IU_ID); + assertEquals(c.getName(), iu.getId()); return; } } @@ -106,11 +106,10 @@ public class FragmentTest extends AbstractProvisioningTest { throw new AssertionFailedError("The array does not contain the searched element"); } - public static void assertContainsWithEquals(Object[] objects, Object searched) { - for (int i = 0; i < objects.length; i++) { - if (objects[i].equals(searched)) - return; - } + public static void assertContainsWithEquals(Collection objects, Object searched) { + if (objects.contains(searched)) + return; + throw new AssertionFailedError("The array does not contain the searched element"); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPatchPersistenceTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPatchPersistenceTest.java index cb384633f..fb301060c 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPatchPersistenceTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPatchPersistenceTest.java @@ -10,21 +10,20 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.metadata; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.io.*; import java.util.*; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; -import org.eclipse.equinox.internal.p2.metadata.InstallableUnit; -import org.eclipse.equinox.internal.p2.metadata.InstallableUnitPatch; +import org.eclipse.equinox.internal.p2.metadata.*; import org.eclipse.equinox.internal.p2.metadata.repository.io.MetadataParser; import org.eclipse.equinox.internal.p2.metadata.repository.io.MetadataWriter; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.BundleContext; +import org.osgi.framework.Filter; import org.xml.sax.*; public class IUPatchPersistenceTest extends AbstractProvisioningTest { @@ -34,8 +33,8 @@ public class IUPatchPersistenceTest extends AbstractProvisioningTest { private static String PackagesNS = "osgi.packages"; private static String id = "org.eclipse.osgi.services"; - private static Version version = new Version("3.1.200.v20070605"); - private static String filter = "(& (osgi.ws=win32) (osgi.os=win32) (osgi.arch=x86))"; // not really + private static Version version = Version.create("3.1.200.v20070605"); + private static Filter filter = ExpressionUtil.parseLDAP("(& (osgi.ws=win32) (osgi.os=win32) (osgi.arch=x86))"); // not really private static String[][] properties = new String[][] {new String[] {"equinox.p2.name", "OSGi Release 4.0.1 Services"}, // new String[] {"equinox.p2.description", "OSGi Service Platform Release 4.0.1 Service Interfaces and Classes"}, // @@ -95,7 +94,7 @@ public class IUPatchPersistenceTest extends AbstractProvisioningTest { IProvidedCapability[] provided = new IProvidedCapability[provideTuples.length]; for (int i = 0; i < provideTuples.length; i++) { String[] nextTuple = provideTuples[i]; - provided[i] = MetadataFactory.createProvidedCapability(nextTuple[0], nextTuple[1], new Version(nextTuple[2])); + provided[i] = MetadataFactory.createProvidedCapability(nextTuple[0], nextTuple[1], Version.create(nextTuple[2])); } // provided[provideTuples.length] = BUNDLE_CAPABILITY; return provided; @@ -105,7 +104,7 @@ public class IUPatchPersistenceTest extends AbstractProvisioningTest { IRequiredCapability[] required = new IRequiredCapability[requireTuples.length]; for (int i = 0; i < requireTuples.length; i++) { String[] nextTuple = requireTuples[i]; - required[i] = MetadataFactory.createRequiredCapability(nextTuple[0], nextTuple[1], new VersionRange(nextTuple[2]), null, Boolean.valueOf(nextTuple[3]).booleanValue(), false); + required[i] = (IRequiredCapability) MetadataFactory.createRequiredCapability(nextTuple[0], nextTuple[1], new VersionRange(nextTuple[2]), null, Boolean.valueOf(nextTuple[3]).booleanValue(), false); } return required; } @@ -120,7 +119,7 @@ public class IUPatchPersistenceTest extends AbstractProvisioningTest { } private static String IU_TEST_TARGET = "installableUnitTest"; - private static Version IU_TEST_VERSION = new Version("0.0.1"); + private static Version IU_TEST_VERSION = Version.create("0.0.1"); private static String IU_TEST_ELEMENT = "test"; @@ -286,8 +285,8 @@ public class IUPatchPersistenceTest extends AbstractProvisioningTest { IRequirementChange change1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequirementChange change2 = MetadataFactory.createRequirementChange(null, MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequirementChange change3 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), null); - IRequiredCapability[][] scope = new IRequiredCapability[][] { {MetadataFactory.createRequiredCapability("foo", "bar", null, null, true, true), MetadataFactory.createRequiredCapability("foo", "bar", null, null, true, true)}, {MetadataFactory.createRequiredCapability("zoo", "far", null, null, true, true)}}; - IRequiredCapability lifeCycle = MetadataFactory.createRequiredCapability("zoo", "x", null, null, false, false, false); + IRequiredCapability[][] scope = new IRequiredCapability[][] { {(IRequiredCapability) MetadataFactory.createRequiredCapability("foo", "bar", null, null, true, true), (IRequiredCapability) MetadataFactory.createRequiredCapability("foo", "bar", null, null, true, true)}, {(IRequiredCapability) MetadataFactory.createRequiredCapability("zoo", "far", null, null, true, true)}}; + IRequiredCapability lifeCycle = (IRequiredCapability) MetadataFactory.createRequiredCapability("zoo", "x", null, null, false, false, false); IInstallableUnitPatch iu = createIUPatch(id, version, filter, requirements, additionalProvides, propertyMap, TOUCHPOINT_OSGI, tpData, singleton, update, new IRequirementChange[] {change1, change2, change3}, scope, lifeCycle, metaRequirements); return iu; } @@ -296,11 +295,11 @@ public class IUPatchPersistenceTest extends AbstractProvisioningTest { validateIU(iu); assertTrue(iu.getApplicabilityScope() != null); assertTrue(iu.getRequiredCapabilities() != null); - assertEquals(3, iu.getRequirementsChange().length); - assertEquals(null, iu.getRequirementsChange()[1].applyOn()); - assertNotNull(iu.getRequirementsChange()[1].newValue()); - assertEquals(null, iu.getRequirementsChange()[2].newValue()); - assertNotNull(iu.getRequirementsChange()[2].applyOn()); + assertEquals(3, iu.getRequirementsChange().size()); + assertEquals(null, iu.getRequirementsChange().get(1).applyOn()); + assertNotNull(iu.getRequirementsChange().get(1).newValue()); + assertEquals(null, iu.getRequirementsChange().get(2).newValue()); + assertNotNull(iu.getRequirementsChange().get(2).applyOn()); assertEquals(2, iu.getApplicabilityScope().length); assertEquals(2, iu.getApplicabilityScope()[0].length); assertEquals(1, iu.getApplicabilityScope()[1].length); @@ -346,31 +345,33 @@ public class IUPatchPersistenceTest extends AbstractProvisioningTest { } private static String[][] extractProvides(IInstallableUnit iu) { - IProvidedCapability[] provydes = iu.getProvidedCapabilities(); - String[][] tuples = new String[provydes.length][3]; - for (int i = 0; i < provydes.length; i++) { - IProvidedCapability next = provydes[i]; - tuples[i] = new String[] {next.getNamespace(), next.getName(), next.getVersion().toString()}; + Collection provydes = iu.getProvidedCapabilities(); + String[][] tuples = new String[provydes.size()][3]; + int i = 0; + for (IProvidedCapability capability : provydes) { + tuples[i++] = new String[] {capability.getNamespace(), capability.getName(), capability.getVersion().toString()}; } return tuples; } private static String[][] extractRequires(IInstallableUnit iu) { - IRequiredCapability[] requyres = iu.getRequiredCapabilities(); - String[][] tuples = new String[requyres.length][4]; - for (int i = 0; i < requyres.length; i++) { - IRequiredCapability next = requyres[i]; - tuples[i] = new String[] {next.getNamespace(), next.getName(), next.getRange().toString(), Boolean.valueOf(next.isOptional()).toString()}; + Collection reqs = iu.getRequiredCapabilities(); + String[][] tuples = new String[reqs.size()][4]; + int i = 0; + for (Iterator iterator = reqs.iterator(); iterator.hasNext();) { + IRequiredCapability next = (IRequiredCapability) iterator.next(); + tuples[i++] = new String[] {next.getNamespace(), next.getName(), next.getRange().toString(), Boolean.valueOf(next.getMin() == 0).toString()}; } return tuples; } private static String[][] extractMetaRequires(IInstallableUnit iu) { - IRequiredCapability[] requyres = iu.getMetaRequiredCapabilities(); - String[][] tuples = new String[requyres.length][4]; - for (int i = 0; i < requyres.length; i++) { - IRequiredCapability next = requyres[i]; - tuples[i] = new String[] {next.getNamespace(), next.getName(), next.getRange().toString(), Boolean.valueOf(next.isOptional()).toString()}; + Collection requyres = iu.getMetaRequiredCapabilities(); + String[][] tuples = new String[requyres.size()][4]; + int i = 0; + for (Iterator iterator = requyres.iterator(); iterator.hasNext();) { + IRequiredCapability next = (IRequiredCapability) iterator.next(); + tuples[i++] = new String[] {next.getNamespace(), next.getName(), next.getRange().toString(), Boolean.valueOf(next.getMin() == 0).toString()}; } return tuples; } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPersistenceTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPersistenceTest.java index b4f5feba1..3f7989298 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPersistenceTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/IUPersistenceTest.java @@ -10,21 +10,22 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.metadata; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.io.*; +import java.net.URI; import java.util.*; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; -import org.eclipse.equinox.internal.p2.metadata.InstallableUnit; -import org.eclipse.equinox.internal.p2.metadata.InstallableUnitPatch; +import org.eclipse.equinox.internal.p2.metadata.*; import org.eclipse.equinox.internal.p2.metadata.repository.io.MetadataParser; import org.eclipse.equinox.internal.p2.metadata.repository.io.MetadataWriter; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.BundleContext; +import org.osgi.framework.Filter; import org.xml.sax.*; public class IUPersistenceTest extends AbstractProvisioningTest { @@ -134,7 +135,7 @@ public class IUPersistenceTest extends AbstractProvisioningTest { } } - private static String filter = "(& (osgi.ws=win32) (osgi.os=win32) (osgi.arch=x86))"; // not really + private static Filter filter = ExpressionUtil.parseLDAP("(& (osgi.ws=win32) (osgi.os=win32) (osgi.arch=x86))"); // not really private static String id = "org.eclipse.osgi.services"; private static String[][] instructions = new String[][] {new String[] {"manifest", "Manifest-Version: 1.0\\Bundle-Vendor: Eclipse.org\\Bundle-ContactAddress: www.eclipse.org\\...a whole bunch of other manifest content..."}, new String[] {"zipped", "true"}, // @@ -144,7 +145,7 @@ public class IUPersistenceTest extends AbstractProvisioningTest { private static String IU_TEST_TARGET = "installableUnitTest"; - private static Version IU_TEST_VERSION = new Version("0.0.1"); + private static Version IU_TEST_VERSION = Version.create("0.0.1"); // Randomly chose org.eclipse.osgi.services as the IU for testing persistence // but 'enhanced' it for better coverage. @@ -176,7 +177,7 @@ public class IUPersistenceTest extends AbstractProvisioningTest { private static String[][] metaRequires = new String[][] {new String[] {PackagesNS, "some.actions1", "0.0.0", "true"}, // new String[] {PackagesNS, "some.actions2", "1.2.0", "false"}}; // - private static Version version = new Version("3.1.200.v20070605"); + private static Version version = Version.create("3.1.200.v20070605"); private Map propertyMap; @@ -203,7 +204,7 @@ public class IUPersistenceTest extends AbstractProvisioningTest { IProvidedCapability[] provided = new IProvidedCapability[provideTuples.length]; for (int i = 0; i < provideTuples.length; i++) { String[] nextTuple = provideTuples[i]; - provided[i] = MetadataFactory.createProvidedCapability(nextTuple[0], nextTuple[1], new Version(nextTuple[2])); + provided[i] = MetadataFactory.createProvidedCapability(nextTuple[0], nextTuple[1], Version.create(nextTuple[2])); } // provided[provideTuples.length] = BUNDLE_CAPABILITY; return provided; @@ -213,7 +214,7 @@ public class IUPersistenceTest extends AbstractProvisioningTest { IRequiredCapability[] required = new IRequiredCapability[requireTuples.length]; for (int i = 0; i < requireTuples.length; i++) { String[] nextTuple = requireTuples[i]; - required[i] = MetadataFactory.createRequiredCapability(nextTuple[0], nextTuple[1], new VersionRange(nextTuple[2]), null, Boolean.valueOf(nextTuple[3]).booleanValue(), false); + required[i] = (IRequiredCapability) MetadataFactory.createRequiredCapability(nextTuple[0], nextTuple[1], new VersionRange(nextTuple[2]), null, Boolean.valueOf(nextTuple[3]).booleanValue(), false); } return required; } @@ -232,38 +233,40 @@ public class IUPersistenceTest extends AbstractProvisioningTest { } private static String[][] extractProvides(IInstallableUnit iu) { - IProvidedCapability[] provydes = iu.getProvidedCapabilities(); - String[][] tuples = new String[provydes.length][3]; - for (int i = 0; i < provydes.length; i++) { - IProvidedCapability next = provydes[i]; - tuples[i] = new String[] {next.getNamespace(), next.getName(), next.getVersion().toString()}; + Collection provydes = iu.getProvidedCapabilities(); + String[][] tuples = new String[provydes.size()][3]; + int i = 0; + for (IProvidedCapability capability : provydes) { + tuples[i++] = new String[] {capability.getNamespace(), capability.getName(), capability.getVersion().toString()}; } return tuples; } private static String[][] extractRequires(IInstallableUnit iu) { - IRequiredCapability[] requyres = iu.getRequiredCapabilities(); - String[][] tuples = new String[requyres.length][4]; - for (int i = 0; i < requyres.length; i++) { - IRequiredCapability next = requyres[i]; - tuples[i] = new String[] {next.getNamespace(), next.getName(), next.getRange().toString(), Boolean.valueOf(next.isOptional()).toString()}; + Collection requyres = iu.getRequiredCapabilities(); + String[][] tuples = new String[requyres.size()][4]; + int i = 0; + for (Iterator iterator = requyres.iterator(); iterator.hasNext();) { + IRequiredCapability next = (IRequiredCapability) iterator.next(); + tuples[i++] = new String[] {next.getNamespace(), next.getName(), next.getRange().toString(), Boolean.valueOf(next.getMin() == 0).toString()}; } return tuples; } private static String[][] extractMetaRequires(IInstallableUnit iu) { - IRequiredCapability[] requyres = iu.getMetaRequiredCapabilities(); - String[][] tuples = new String[requyres.length][4]; - for (int i = 0; i < requyres.length; i++) { - IRequiredCapability next = requyres[i]; - tuples[i] = new String[] {next.getNamespace(), next.getName(), next.getRange().toString(), Boolean.valueOf(next.isOptional()).toString()}; + Collection requyres = iu.getMetaRequiredCapabilities(); + String[][] tuples = new String[requyres.size()][4]; + int i = 0; + for (Iterator iterator = requyres.iterator(); iterator.hasNext();) { + IRequiredCapability next = (IRequiredCapability) iterator.next(); + tuples[i++] = new String[] {next.getNamespace(), next.getName(), next.getRange().toString(), Boolean.valueOf(next.getMin() == 0).toString()}; } return tuples; } private IInstallableUnitPatch createPatchIU() { propertyMap = createProperties(properties); - propertyMap.put(IInstallableUnit.PROP_TYPE_PATCH, "true"); + propertyMap.put(InstallableUnitDescription.PROP_TYPE_PATCH, "true"); IProvidedCapability[] additionalProvides = createProvided(provides); IRequiredCapability[] requirements = createRequired(requires); IRequiredCapability[] metaRequirements = createRequired(metaRequires); @@ -273,14 +276,14 @@ public class IUPersistenceTest extends AbstractProvisioningTest { IRequirementChange change1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequirementChange change2 = MetadataFactory.createRequirementChange(null, MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequirementChange change3 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), null); - IRequiredCapability[][] scope = new IRequiredCapability[][] { {MetadataFactory.createRequiredCapability("foo", "bar", null, null, true, true), MetadataFactory.createRequiredCapability("foo", "bar", null, null, true, true)}, {MetadataFactory.createRequiredCapability("zoo", "far", null, null, true, true)}}; + IRequiredCapability[][] scope = new IRequiredCapability[][] { {(IRequiredCapability) MetadataFactory.createRequiredCapability("foo", "bar", null, null, true, true), (IRequiredCapability) MetadataFactory.createRequiredCapability("foo", "bar", null, null, true, true)}, {(IRequiredCapability) MetadataFactory.createRequiredCapability("zoo", "far", null, null, true, true)}}; IInstallableUnitPatch iu = createIUPatch(id, version, filter, requirements, additionalProvides, propertyMap, TOUCHPOINT_OSGI, tpData, singleton, update, new IRequirementChange[] {change1, change2, change3}, scope, null, metaRequirements); return iu; } private IInstallableUnitPatch createPatchWithEmptyScope() { propertyMap = createProperties(properties); - propertyMap.put(IInstallableUnit.PROP_TYPE_PATCH, "true"); + propertyMap.put(InstallableUnitDescription.PROP_TYPE_PATCH, "true"); IProvidedCapability[] additionalProvides = createProvided(provides); IRequiredCapability[] requirements = createRequired(requires); IRequiredCapability[] metaRequirements = createRequired(metaRequires); @@ -300,10 +303,35 @@ public class IUPersistenceTest extends AbstractProvisioningTest { IProvidedCapability[] additionalProvides = createProvided(provides); IRequiredCapability[] requirements = createRequired(requires); IRequiredCapability[] metaRequirements = createRequired(metaRequires); + ILicense[] licenses = new ILicense[] {MetadataFactory.createLicense(URI.create("http://eclipse.org"), "license text"), MetadataFactory.createLicense(URI.create("http://apache.org"), "license text2")}; ITouchpointData tpData = createTouchpointData(instructions); IUpdateDescriptor update = createUpdateDescriptor(); - boolean singleton = false; - IInstallableUnit iu = createIU(id, version, filter, requirements, additionalProvides, propertyMap, TOUCHPOINT_OSGI, tpData, singleton, update, metaRequirements); + InstallableUnitDescription iu1 = new MetadataFactory.InstallableUnitDescription(); + iu1.setId(id); + iu1.setVersion(version); + iu1.setFilter(filter); + iu1.setLicenses(licenses); + IProvidedCapability[] provides1 = new IProvidedCapability[additionalProvides.length + 1]; + provides1[0] = getSelfCapability(id, version); + for (int i = 0; i < additionalProvides.length; i++) { + provides1[i + 1] = additionalProvides[i]; + } + for (Iterator iter = propertyMap.keySet().iterator(); iter.hasNext();) { + String nextKey = (String) iter.next(); + String nextValue = (String) propertyMap.get(nextKey); + iu1.setProperty(nextKey, nextValue); + } + iu1.setCapabilities(provides1); + iu1.setRequiredCapabilities(requirements); + iu1.setTouchpointType(TOUCHPOINT_OSGI); + if (tpData != null) + iu1.addTouchpointData(tpData); + iu1.setSingleton(false); + iu1.setUpdateDescriptor(update); + if (metaRequirements == null) + metaRequirements = NO_REQUIRES; + iu1.setMetaRequiredCapabilities(metaRequirements); + IInstallableUnit iu = MetadataFactory.createInstallableUnit(iu1); return iu; } @@ -370,6 +398,7 @@ public class IUPersistenceTest extends AbstractProvisioningTest { assertTrue("Error parsing test iu: " + parser.getStatus().getMessage(), parser.getStatus().isOK()); InstallableUnit iu1 = (InstallableUnit) parser.getRootObject(); validateIU(iu1); + assertEquals(2, iu1.getLicenses().size()); ByteArrayOutputStream output1 = new ByteArrayOutputStream(1492); IUStringWriter writer = new IUStringWriter(output1); writer.writeTest(iu1); @@ -381,7 +410,7 @@ public class IUPersistenceTest extends AbstractProvisioningTest { private void validateIU(IInstallableUnit iu) { assertTrue("Installable unit id is not correct", id.equals(iu.getId())); assertTrue("Installable unit version is not correct", version.equals(iu.getVersion())); - assertTrue("Installable unit filter is not correct", filter.equals(iu.getFilter())); + assertTrue("Installable unit filter is not correct", filter.equals(iu.getFilter() == null ? null : iu.getFilter())); assertEquals("Installable unit properties are not correct", propertyMap, iu.getProperties()); assertTrue("Installable unit provided capabilities are not correct", equal(addSelfCapability(iu, provides), extractProvides(iu))); assertTrue("Installable unit required capabilities are not correct", equal(requires, extractRequires(iu))); @@ -396,11 +425,11 @@ public class IUPersistenceTest extends AbstractProvisioningTest { validateIU(iu); assertTrue(iu.getApplicabilityScope() != null); assertTrue(iu.getRequiredCapabilities() != null); - assertEquals(3, iu.getRequirementsChange().length); - assertEquals(null, iu.getRequirementsChange()[1].applyOn()); - assertNotNull(iu.getRequirementsChange()[1].newValue()); - assertEquals(null, iu.getRequirementsChange()[2].newValue()); - assertNotNull(iu.getRequirementsChange()[2].applyOn()); + assertEquals(3, iu.getRequirementsChange().size()); + assertEquals(null, iu.getRequirementsChange().get(1).applyOn()); + assertNotNull(iu.getRequirementsChange().get(1).newValue()); + assertEquals(null, iu.getRequirementsChange().get(2).newValue()); + assertNotNull(iu.getRequirementsChange().get(2).applyOn()); assertEquals(2, iu.getApplicabilityScope().length); assertEquals(2, iu.getApplicabilityScope()[0].length); assertEquals(1, iu.getApplicabilityScope()[1].length); @@ -411,11 +440,11 @@ public class IUPersistenceTest extends AbstractProvisioningTest { validateIU(iu); assertTrue(iu.getApplicabilityScope() != null); assertTrue(iu.getRequiredCapabilities() != null); - assertEquals(3, iu.getRequirementsChange().length); - assertEquals(null, iu.getRequirementsChange()[1].applyOn()); - assertNotNull(iu.getRequirementsChange()[1].newValue()); - assertEquals(null, iu.getRequirementsChange()[2].newValue()); - assertNotNull(iu.getRequirementsChange()[2].applyOn()); + assertEquals(3, iu.getRequirementsChange().size()); + assertEquals(null, iu.getRequirementsChange().get(1).applyOn()); + assertNotNull(iu.getRequirementsChange().get(1).newValue()); + assertEquals(null, iu.getRequirementsChange().get(2).newValue()); + assertNotNull(iu.getRequirementsChange().get(2).applyOn()); assertEquals(0, iu.getApplicabilityScope().length); assertNull(iu.getLifeCycle()); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/InstallableUnitTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/InstallableUnitTest.java index c51bf173b..68d6dd67f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/InstallableUnitTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/InstallableUnitTest.java @@ -10,10 +10,13 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.metadata; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IProvidedCapability; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** @@ -24,7 +27,7 @@ public class InstallableUnitTest extends AbstractProvisioningTest { * Tests for {@link org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit#satisfies(org.eclipse.equinox.internal.provisional.p2.metadata.RequiredCapability)}. */ public void testSatisfies() { - IProvidedCapability[] provides = new IProvidedCapability[] {MetadataFactory.createProvidedCapability("testNamespace", "name", new Version(1, 0, 0))}; + IProvidedCapability[] provides = new IProvidedCapability[] {MetadataFactory.createProvidedCapability("testNamespace", "name", Version.createOSGi(1, 0, 0))}; IInstallableUnit iu = createIU("iu", provides); IRequiredCapability wrongNamespace = MetadataFactory.createRequiredCapability("wrongNamespace", "name", VersionRange.emptyRange, null, false, false); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/LatestIUTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/LatestIUTest.java index 525e15c7c..8814ae826 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/LatestIUTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/LatestIUTest.java @@ -9,14 +9,13 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.metadata; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.net.URI; -import java.util.Collection; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.LatestIUVersionQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.internal.p2.metadata.query.LatestIUVersionQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestData; @@ -36,10 +35,9 @@ public class LatestIUTest extends AbstractProvisioningTest { IMetadataRepositoryManager metadataRepositoryManager = getMetadataRepositoryManager(); metadataRepositoryManager.addRepository(location); - Collector query = metadataRepositoryManager.query(new LatestIUVersionQuery(), new Collector(), null); - Collection collection = query.toCollection(); - assertEquals("1.0", 1, collection.size()); - assertEquals("1.1", new Version(2, 1, 0), ((IInstallableUnit) collection.iterator().next()).getVersion()); + IQueryResult query = metadataRepositoryManager.query(new LatestIUVersionQuery(), null); + assertEquals("1.0", 1, queryResultSize(query)); + assertEquals("1.1", Version.createOSGi(2, 1, 0), ((IInstallableUnit) query.iterator().next()).getVersion()); } public void testLatestIUSingleRepo2() throws Exception { @@ -53,10 +51,9 @@ public class LatestIUTest extends AbstractProvisioningTest { IMetadataRepositoryManager metadataRepositoryManager = getMetadataRepositoryManager(); metadataRepositoryManager.addRepository(location); - Collector query = metadataRepositoryManager.query(new LatestIUVersionQuery(), new Collector(), null); - Collection collection = query.toCollection(); - assertEquals("1.0", 1, collection.size()); - assertEquals("1.1", new Version(3, 0, 0), ((IInstallableUnit) collection.iterator().next()).getVersion()); + IQueryResult query = metadataRepositoryManager.query(new LatestIUVersionQuery(), null); + assertEquals("1.0", 1, queryResultSize(query)); + assertEquals("1.1", Version.createOSGi(3, 0, 0), ((IInstallableUnit) query.iterator().next()).getVersion()); } public void testLatestIUMultiRepo() throws Exception { @@ -73,9 +70,8 @@ public class LatestIUTest extends AbstractProvisioningTest { metadataRepositoryManager.addRepository(location1); metadataRepositoryManager.addRepository(location2); - Collector collector = metadataRepositoryManager.query(new LatestIUVersionQuery(), new Collector(), null); - Collection collection = collector.toCollection(); - assertEquals("1.0", 1, collection.size()); - assertEquals("1.1", new Version(3, 0, 0), ((IInstallableUnit) collection.iterator().next()).getVersion()); + IQueryResult queryResult = metadataRepositoryManager.query(new LatestIUVersionQuery(), null); + assertEquals("1.0", 1, queryResultSize(queryResult)); + assertEquals("1.1", Version.createOSGi(3, 0, 0), ((IInstallableUnit) queryResult.iterator().next()).getVersion()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/LicenseTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/LicenseTest.java index c51d3097c..c62b1d75d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/LicenseTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/LicenseTest.java @@ -12,8 +12,8 @@ package org.eclipse.equinox.p2.tests.metadata; import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.ILicense; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.ILicense; /** * Tests for License class @@ -22,10 +22,10 @@ public class LicenseTest extends TestCase { public void testNormalize() { ILicense licenseOne = MetadataFactory.createLicense(null, "a b"); ILicense licenseTwo = MetadataFactory.createLicense(null, "a\t\n\r \t\n\r b"); - assertEquals("1.0", licenseOne.getDigest(), licenseTwo.getDigest()); + assertEquals("1.0", licenseOne.getUUID(), licenseTwo.getUUID()); licenseOne = MetadataFactory.createLicense(null, " a b c "); licenseTwo = MetadataFactory.createLicense(null, "a\t\nb\r \t\n\r c"); - assertEquals("1.1", licenseOne.getDigest(), licenseTwo.getDigest()); + assertEquals("1.1", licenseOne.getUUID(), licenseTwo.getUUID()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/MultipleIUAndFragmentTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/MultipleIUAndFragmentTest.java index 44c186449..e917893f3 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/MultipleIUAndFragmentTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/MultipleIUAndFragmentTest.java @@ -10,14 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.metadata; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.Collection; import java.util.Iterator; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MultipleIUAndFragmentTest extends AbstractProvisioningTest { @@ -40,16 +41,16 @@ public class MultipleIUAndFragmentTest extends AbstractProvisioningTest { iu3 = createBundleFragment("fragment"); ProfileChangeRequest req = new ProfileChangeRequest(createProfile(getName())); createTestMetdataRepository(new IInstallableUnit[] {iu1, iu2, iu3}); - Iterator iterator = createPlanner().getProvisioningPlan(req, null, null).getAdditions().query(InstallableUnitQuery.ANY, new Collector(), null).iterator(); + Iterator iterator = createPlanner().getProvisioningPlan(req, null, null).getAdditions().query(InstallableUnitQuery.ANY, null).iterator(); for (; iterator.hasNext();) { IInstallableUnit iu = (IInstallableUnit) iterator.next(); if (iu.getId().equals(iu1.getId())) { - assertEquals(1, iu.getFragments().length); - assertEquals(iu.getFragments()[0].getId(), iu3.getId()); + assertEquals(1, iu.getFragments().size()); + assertEquals(iu.getFragments().get(0).getId(), iu3.getId()); } if (iu.getId().equals(iu2.getId())) { - assertEquals(1, iu.getFragments().length); - assertEquals(iu.getFragments()[0].getId(), iu3.getId()); + assertEquals(1, iu.getFragments().size()); + assertEquals(iu.getFragments().get(0).getId(), iu3.getId()); } if (iu.getId().equals(iu3.getId())) { //fragments don't have fragments diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/ProvidedCapabilityTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/ProvidedCapabilityTest.java index d78a65e24..316d64c50 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/ProvidedCapabilityTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/ProvidedCapabilityTest.java @@ -10,10 +10,10 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.metadata; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.IProvidedCapability; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.IProvidedCapability; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** @@ -23,7 +23,7 @@ public class ProvidedCapabilityTest extends AbstractProvisioningTest { public void testEquals() { IProvidedCapability cap = MetadataFactory.createProvidedCapability("namespace", "name", DEFAULT_VERSION); IProvidedCapability equal = MetadataFactory.createProvidedCapability("namespace", "name", DEFAULT_VERSION); - IProvidedCapability notEqual = MetadataFactory.createProvidedCapability("namespace", "name", new Version(2, 0, 0)); + IProvidedCapability notEqual = MetadataFactory.createProvidedCapability("namespace", "name", Version.createOSGi(2, 0, 0)); assertEquals("1.0", cap, equal); assertFalse("1.1", cap.equals(notEqual)); assertFalse("1.1", notEqual.equals(cap)); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/AllTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/AllTests.java new file mode 100644 index 000000000..39fed0b38 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/AllTests.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.tests.metadata.expression; + +import junit.framework.*; + +/** + * Performs all automated director tests. + */ +public class AllTests extends TestCase { + + public static Test suite() { + TestSuite suite = new TestSuite(AllTests.class.getName()); + suite.addTestSuite(ExpressionTest.class); + suite.addTestSuite(FilterTest.class); + return suite; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/ExpressionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/ExpressionTest.java new file mode 100644 index 000000000..9c7407c63 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/ExpressionTest.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.tests.metadata.expression; + +import org.eclipse.equinox.p2.metadata.expression.*; +import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; + +public class ExpressionTest extends AbstractProvisioningTest { + private static final IExpressionFactory factory = ExpressionUtil.getFactory(); + + protected void testExpression(String exprStr, Object expectedOutcome) throws Exception { + IExpression expr = ExpressionUtil.parse(exprStr); + assertEquals(expr.evaluate(factory.createContext()), expectedOutcome); + } + + protected void testMatch(String expr, boolean expectedOutcome) throws Exception { + testExpression(expr, Boolean.valueOf(expectedOutcome)); + } + + public void testCompare() throws Exception { + testMatch("'foo' == 'foo'", true); + testMatch("'foo' == 'fooo'", false); + testMatch("'foo' != 'foo'", false); + testMatch("'foo' != 'fooo'", true); + testMatch("2 < 1", false); + testMatch("2 <= 1", false); + testMatch("2 < 2", false); + testMatch("2 <= 2", true); + testMatch("2 < 3", true); + testMatch("2 <= 3", true); + testMatch("1 > 2", false); + testMatch("1 >= 2", false); + testMatch("2 > 2", false); + testMatch("2 >= 2", true); + testMatch("3 > 2", true); + testMatch("3 >= 2", true); + } + + public void testAutoCoerce() throws Exception { + testMatch("'12' == 12", true); + testMatch("'012' == 12", true); + testMatch("'2' > '10'", true); + testMatch("'2' > 10", false); + testMatch("true == 'true'", true); + testMatch("true == 'True'", true); + testMatch("false == 'false'", true); + testMatch("false == 'False'", true); + } + + public void testLeftToRigthAssociativity() throws Exception { + testMatch("2 < 10 == true", true); + try { + testMatch("true == 2 < 10", false); + fail("Auto coercion from boolean to integer succeded"); + } catch (IllegalArgumentException e) { + // OK + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/FilterTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/FilterTest.java new file mode 100644 index 000000000..cf3cba552 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/expression/FilterTest.java @@ -0,0 +1,267 @@ +package org.eclipse.equinox.p2.tests.metadata.expression; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.*; +import junit.framework.*; +import org.eclipse.equinox.p2.metadata.expression.*; +import org.osgi.framework.*; + +public class FilterTest extends TestCase { + private static class DictionaryServiceReference implements ServiceReference { + private final Map dictionary; + + private final String[] keys; + + DictionaryServiceReference(Map dictionary) { + if (dictionary == null) { + this.dictionary = null; + this.keys = new String[] {}; + return; + } + this.dictionary = dictionary; + List keyList = new ArrayList(dictionary.size()); + for (Iterator e = dictionary.keySet().iterator(); e.hasNext();) { + String key = e.next(); + for (Iterator i = keyList.iterator(); i.hasNext();) { + if (key.equalsIgnoreCase((String) i.next())) { + throw new IllegalArgumentException(); + } + } + keyList.add(key); + } + this.keys = keyList.toArray(new String[keyList.size()]); + } + + public int compareTo(Object reference) { + throw new UnsupportedOperationException(); + } + + public Bundle getBundle() { + return null; + } + + public Object getProperty(String k) { + for (int i = 0, length = keys.length; i < length; i++) { + String key = keys[i]; + if (key.equalsIgnoreCase(k)) { + return dictionary.get(key); + } + } + return null; + } + + public String[] getPropertyKeys() { + return keys.clone(); + } + + public Bundle[] getUsingBundles() { + throw new UnsupportedOperationException(); + } + + public boolean isAssignableTo(Bundle bundle, String className) { + throw new UnsupportedOperationException(); + } + } + + private static class SampleComparable implements Comparable { + private int value = -1; + + public SampleComparable(String value) { + this.value = Integer.parseInt(value); + } + + public boolean equals(Object o) { + return o instanceof SampleComparable && value == ((SampleComparable) o).value; + } + + public int compareTo(Object o) { + return value - ((SampleComparable) o).value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + static final int ISTRUE = 1; + + static final int ISFALSE = 2; + + static final int ISILLEGAL = 3; + + public static Test suite() { + return new TestSuite(FilterTest.class); + } + + public void testComparable() throws Exception { + IFilterExpression f1 = ExpressionUtil.parseLDAP("(comparable=42)"); //$NON-NLS-1$ + Object comp; + Map hash = new HashMap(); + + comp = new SampleComparable("42"); //$NON-NLS-1$ + hash.put("comparable", comp); //$NON-NLS-1$ + assertTrue("does not match filter", f1.match(hash)); //$NON-NLS-1$ + assertTrue("does not match filter", f1.match(new DictionaryServiceReference(hash))); //$NON-NLS-1$ + + comp = new Long(42); + hash.put("comparable", comp); //$NON-NLS-1$ + assertTrue("does not match filter", f1.match(hash)); //$NON-NLS-1$ + assertTrue("does not match filter", f1.match(new DictionaryServiceReference(hash))); //$NON-NLS-1$ + + IFilterExpression f2 = ExpressionUtil.parseLDAP("(comparable=42)"); //$NON-NLS-1$ + hash = new Hashtable(); + + comp = new SampleComparable("42"); //$NON-NLS-1$ + hash.put("comparable", comp); //$NON-NLS-1$ + assertTrue("does not match filter", f2.match(hash)); //$NON-NLS-1$ + assertTrue("does not match filter", f2.match(new DictionaryServiceReference(hash))); //$NON-NLS-1$ + + comp = new Long(42); + hash.put("comparable", comp); //$NON-NLS-1$ + assertTrue("does not match filter", f2.match(hash)); //$NON-NLS-1$ + assertTrue("does not match filter", f2.match(new DictionaryServiceReference(hash))); //$NON-NLS-1$ + + assertEquals("not equal", f1, f2); //$NON-NLS-1$ + } + + public void testFilter() { + Properties props = new Properties(); + props.put("room", "bedroom"); //$NON-NLS-1$ //$NON-NLS-2$ + props.put("channel", new Integer(34)); //$NON-NLS-1$ + props.put("status", "(on\\)*"); //$NON-NLS-1$//$NON-NLS-2$ + props.put("max record time", new Long(150)); //$NON-NLS-1$ + props.put("canrecord", "true(x)"); //$NON-NLS-1$ //$NON-NLS-2$ + props.put("shortvalue", new Short((short) 1000)); //$NON-NLS-1$ + props.put("bytevalue", new Byte((byte) 10)); //$NON-NLS-1$ + props.put("floatvalue", new Float(1.01)); //$NON-NLS-1$ + props.put("doublevalue", new Double(2.01)); //$NON-NLS-1$ + props.put("charvalue", new Character('A')); //$NON-NLS-1$ + props.put("booleanvalue", new Boolean(false)); //$NON-NLS-1$ + props.put("weirdvalue", new Hashtable()); //$NON-NLS-1$ + try { + props.put("bigintvalue", new BigInteger("4123456")); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (NoClassDefFoundError e) { + // ignore + } + try { + props.put("bigdecvalue", new BigDecimal("4.123456")); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (NoClassDefFoundError e) { + // ignore + } + + testFilter("(room=*)", props, ISTRUE); //$NON-NLS-1$ + testFilter("(rooom=*)", props, ISFALSE); //$NON-NLS-1$ + testFilter("(room=bedroom)", props, ISTRUE); //$NON-NLS-1$ + testFilter("(room~= B E D R O O M )", props, ISTRUE); //$NON-NLS-1$ + testFilter("(room=abc)", props, ISFALSE); //$NON-NLS-1$ + testFilter(" ( room >=aaaa)", props, ISTRUE); //$NON-NLS-1$ + testFilter("(room <=aaaa)", props, ISFALSE); //$NON-NLS-1$ + testFilter(" ( room =b*) ", props, ISTRUE); //$NON-NLS-1$ + testFilter(" ( room =*m) ", props, ISTRUE); //$NON-NLS-1$ + testFilter("(room=bed*room)", props, ISTRUE); //$NON-NLS-1$ + testFilter(" ( room =b*oo*m) ", props, ISTRUE); //$NON-NLS-1$ + testFilter(" ( room =*b*oo*m*) ", props, ISTRUE); //$NON-NLS-1$ + testFilter(" ( room =b*b* *m*) ", props, ISFALSE); //$NON-NLS-1$ + testFilter(" (& (room =bedroom) (channel = 34))", props, ISTRUE); //$NON-NLS-1$ + testFilter(" (& (room =b*) (room =*x) (channel=34))", props, ISFALSE); //$NON-NLS-1$ + testFilter("(| (room =bed*)(channel=222)) ", props, ISTRUE); //$NON-NLS-1$ + testFilter("(| (room =boom*)(channel=34)) ", props, ISTRUE); //$NON-NLS-1$ + testFilter(" (! (room =ab*b*oo*m*) ) ", props, ISTRUE); //$NON-NLS-1$ + testFilter(" (status =\\(o*\\\\\\)\\*) ", props, ISTRUE); //$NON-NLS-1$ + testFilter(" (status =\\28o*\\5c\\29\\2a) ", props, ISTRUE); //$NON-NLS-1$ + testFilter(" (status =\\28o*\\5C\\29\\2A) ", props, ISTRUE); //$NON-NLS-1$ + testFilter(" (canRecord =true\\(x\\)) ", props, ISTRUE); //$NON-NLS-1$ + testFilter("(max Record Time <=150) ", props, ISTRUE); //$NON-NLS-1$ + testFilter("(shortValue >= 100) ", props, ISTRUE); //$NON-NLS-1$ + testFilter(" ( & ( byteValue <= 100 ) ( byteValue >= 10 ) ) ", props, ISTRUE); //$NON-NLS-1$ + testFilter("(bigIntValue = 4123456) ", props, ISTRUE); //$NON-NLS-1$ + testFilter("(bigDecValue = 4.123456) ", props, ISTRUE); //$NON-NLS-1$ + testFilter("(floatValue >= 1.0) ", props, ISTRUE); //$NON-NLS-1$ + testFilter("(doubleValue <= 2.011) ", props, ISTRUE); //$NON-NLS-1$ + testFilter("(charValue ~= a) ", props, ISTRUE); //$NON-NLS-1$ + testFilter("(booleanValue = false) ", props, ISTRUE); //$NON-NLS-1$ + testFilter("(& (| (room =d*m) (room =bed*) (room=abc)) (! (channel=999)))", props, ISTRUE); //$NON-NLS-1$ + testFilter("(room=bedroom)", null, ISFALSE); //$NON-NLS-1$ + + testFilter("()", props, ISILLEGAL); //$NON-NLS-1$ + testFilter("(=foo)", props, ISILLEGAL); //$NON-NLS-1$ + testFilter("(", props, ISILLEGAL); //$NON-NLS-1$ + testFilter("(abc = ))", props, ISILLEGAL); //$NON-NLS-1$ + testFilter("(& (abc = xyz) (& (345))", props, ISILLEGAL); //$NON-NLS-1$ + testFilter(" (room = b**oo!*m*) ) ", props, ISILLEGAL); //$NON-NLS-1$ + testFilter(" (room = b**oo)*m*) ) ", props, ISILLEGAL); //$NON-NLS-1$ + testFilter(" (room = *=b**oo*m*) ) ", props, ISILLEGAL); //$NON-NLS-1$ + testFilter(" (room = =b**oo*m*) ) ", props, ISILLEGAL); //$NON-NLS-1$ + + try { + Filter f1 = ExpressionUtil.parseLDAP("( a = bedroom )"); //$NON-NLS-1$ + Filter f2 = ExpressionUtil.parseLDAP(" (a= bedroom ) "); //$NON-NLS-1$ + assertEquals("not equal", "(a= bedroom )", f1.toString()); //$NON-NLS-1$ //$NON-NLS-2$ + assertEquals("not equal", "(a= bedroom )", f2.toString()); //$NON-NLS-1$ //$NON-NLS-2$ + assertEquals("not equal", f1, f2); //$NON-NLS-1$ + assertEquals("not equal", f2, f1); //$NON-NLS-1$ + assertEquals("not equal", f1.hashCode(), f2.hashCode()); //$NON-NLS-1$ + + f1 = ExpressionUtil.parseLDAP("(status =\\28o*\\5c\\29\\2a)"); + assertEquals("not equal", "(status=\\28o*\\5c\\29\\2a)", f1.toString()); //$NON-NLS-1$ //$NON-NLS-2$ + + f1 = ExpressionUtil.parseLDAP("(|(a=1)(&(a=1)(b=1)))"); //$NON-NLS-1$ + f2 = ExpressionUtil.parseLDAP("(a=1)"); //$NON-NLS-1$ + System.out.println(f2.toString()); + System.out.println(f1.toString()); + + f1 = ExpressionUtil.parseLDAP("(|(&(os=macos)(ws=cocoa)(arch=x86))(&(ws=cocoa)(os=macos)(arch=ppc)))"); //$NON-NLS-1$ + f2 = ExpressionUtil.parseLDAP("(&(os=macos)(ws=cocoa)(|(arch=x86)(arch=ppc)))"); //$NON-NLS-1$ + System.out.println(f2.toString()); + System.out.println(f1.toString()); + assertEquals("not equal", f1, f2); //$NON-NLS-1$ + + f1 = ExpressionUtil.parseLDAP("(&(|(x=a)(y=b)(z=a))(|(x=a)(y=b)(z=b)))"); //$NON-NLS-1$ + f2 = ExpressionUtil.parseLDAP("(|(x=a)(y=b)(&(z=a)(z=b)))"); //$NON-NLS-1$ + System.out.println(f2.toString()); + System.out.println(f1.toString()); + assertEquals("not equal", f1, f2); //$NON-NLS-1$ + + f1 = ExpressionUtil.parseLDAP("(&(a=1)(|(a=1)(b=1)))"); //$NON-NLS-1$ + f2 = ExpressionUtil.parseLDAP("(a=1)"); //$NON-NLS-1$ + System.out.println(f2.toString()); + System.out.println(f1.toString()); + + f1 = ExpressionUtil.parseLDAP("(|(a=1)(&(a=1)(b=1)))"); //$NON-NLS-1$ + f2 = ExpressionUtil.parseLDAP("(a=1)"); //$NON-NLS-1$ + System.out.println(f2.toString()); + System.out.println(f1.toString()); + assertEquals("not equal", f1, f2); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + fail("unexpected invalid syntax: " + e); //$NON-NLS-1$ + } + testFilter("(weirdValue = 100) ", props, ISFALSE); //$NON-NLS-1$ + + } + + private void testFilter(String query, Dictionary props, int expect) { + final ServiceReference ref = new DictionaryServiceReference((Map) props); + Filter f1; + try { + f1 = ExpressionUtil.parseLDAP(query); + + if (expect == ISILLEGAL) { + fail("expected exception"); //$NON-NLS-1$ + } + } catch (ExpressionParseException e) { + System.out.println(e.toString()); + if (expect != ISILLEGAL) { + fail("exception: " + e.toString()); //$NON-NLS-1$ + } + return; + } + + boolean val = f1.match(props); + assertEquals("wrong result", expect == ISTRUE, val); //$NON-NLS-1$ + + val = f1.match(ref); + assertEquals("wrong result", expect == ISTRUE, val); //$NON-NLS-1$ + } +} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/AuthTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/AuthTest.java index 6da986266..0338eb8ad 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/AuthTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/AuthTest.java @@ -13,8 +13,8 @@ import java.security.cert.Certificate; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.equinox.internal.p2.repository.RepositoryPreferences; import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.ServiceReference; @@ -30,7 +30,7 @@ public class AuthTest extends ServerBasedTestCase { super.setUp(); PRIVATE_REPO = super.getBaseURL() + "/private/mdr/composite/one"; NEVER_REPO = super.getBaseURL() + "/proxy/never"; - ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.class.getName()); + ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.SERVICE_NAME); mgr = (IMetadataRepositoryManager) TestActivator.context.getService(sr2); if (mgr == null) { throw new RuntimeException("Repository manager could not be loaded"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/CompositeMetadataRepositoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/CompositeMetadataRepositoryTest.java index 7c7bd9a86..990e6b2c0 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/CompositeMetadataRepositoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/CompositeMetadataRepositoryTest.java @@ -12,24 +12,26 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.metadata.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.metadata.query.LatestIUVersionQuery; import org.eclipse.equinox.internal.p2.metadata.repository.CompositeMetadataRepository; import org.eclipse.equinox.internal.p2.metadata.repository.CompositeMetadataRepositoryFactory; import org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryState; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestData; import org.eclipse.equinox.p2.tests.core.CompoundQueryableTest.CompoundQueryTestProgressMonitor; @@ -101,7 +103,7 @@ public class CompositeMetadataRepositoryTest extends AbstractProvisioningTest { try { InstallableUnitDescription descriptor = new MetadataFactory.InstallableUnitDescription(); descriptor.setId("testIuId"); - descriptor.setVersion(new Version("3.2.1")); + descriptor.setVersion(Version.create("3.2.1")); IInstallableUnit iu = MetadataFactory.createInstallableUnit(descriptor); compRepo.addInstallableUnits(new IInstallableUnit[] {iu}); fail("Should not be able to insert InstallableUnit"); @@ -116,7 +118,8 @@ public class CompositeMetadataRepositoryTest extends AbstractProvisioningTest { //Try to remove an InstallableUnit. try { - compRepo.removeInstallableUnits(InstallableUnitQuery.ANY, null); + IQueryResult queryResult = compRepo.query(InstallableUnitQuery.ANY, null); + compRepo.removeInstallableUnits((IInstallableUnit[]) queryResult.toArray(IInstallableUnit.class), null); fail("Should not be able to remove InstallableUnit"); } catch (UnsupportedOperationException e) { //expected. fall through @@ -265,7 +268,7 @@ public class CompositeMetadataRepositoryTest extends AbstractProvisioningTest { assertContains("Assert child1's content is in composite repo", repo1, compRepo); assertContains("Assert child2's content is in composite repo", repo2, compRepo); //checks that the destination has the correct number of keys (no extras) - assertEquals("Assert correct number of IUs", getNumUnique(repo1.query(InstallableUnitQuery.ANY, new Collector(), null), repo2.query(InstallableUnitQuery.ANY, new Collector(), null)), compRepo.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals("Assert correct number of IUs", getNumUnique(repo1.query(InstallableUnitQuery.ANY, null), repo2.query(InstallableUnitQuery.ANY, null)), queryResultSize(compRepo.query(InstallableUnitQuery.ANY, null))); } public void testRemoveNonexistantChild() { @@ -430,7 +433,7 @@ public class CompositeMetadataRepositoryTest extends AbstractProvisioningTest { compRepo.addChild(repo2Location.toURI()); //force composite repository to load all children - compRepo.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()); + compRepo.query(InstallableUnitQuery.ANY, new NullProgressMonitor()); assertTrue("Ensuring previously loaded repo is enabled", getMetadataRepositoryManager().isEnabled(repo1Location.toURI())); String repo1System = getMetadataRepositoryManager().getRepositoryProperty(repo1Location.toURI(), IRepository.PROP_SYSTEM); @@ -456,10 +459,9 @@ public class CompositeMetadataRepositoryTest extends AbstractProvisioningTest { CompositeMetadataRepository compositeRepo = createRepo(false); compositeRepo.addChild(location1); compositeRepo.addChild(location2); - Collector collector = compositeRepo.query(new LatestIUVersionQuery(), new Collector(), monitor); - Collection collection = collector.toCollection(); - assertEquals("1.0", 1, collection.size()); - assertEquals("1.1", new Version(3, 0, 0), ((IInstallableUnit) collection.iterator().next()).getVersion()); + IQueryResult queryResult = compositeRepo.query(new LatestIUVersionQuery(), monitor); + assertEquals("1.0", 1, queryResultSize(queryResult)); + assertEquals("1.1", Version.createOSGi(3, 0, 0), ((IInstallableUnit) queryResult.iterator().next()).getVersion()); assertTrue("1.2", monitor.isDone()); assertTrue("1.3", monitor.isWorkDone()); } @@ -478,20 +480,19 @@ public class CompositeMetadataRepositoryTest extends AbstractProvisioningTest { CompositeMetadataRepository compositeRepo = createRepo(false); compositeRepo.addChild(location1); compositeRepo.addChild(location2); - CompositeQuery cQuery = new CompositeQuery(new Query[] {new MatchQuery() { + PipedQuery cQuery = new PipedQuery(new MatchQuery() { public boolean isMatch(Object candidate) { if (candidate instanceof IInstallableUnit) { IInstallableUnit iInstallableUnit = (IInstallableUnit) candidate; - if (iInstallableUnit.getVersion().compareTo(new Version(3, 0, 0)) < 0) + if (iInstallableUnit.getVersion().compareTo(Version.createOSGi(3, 0, 0)) < 0) return true; } return false; } - }, new LatestIUVersionQuery()}); - Collector collector = compositeRepo.query(cQuery, new Collector(), monitor); - Collection collection = collector.toCollection(); - assertEquals("1.0", 1, collection.size()); - assertEquals("1.1", new Version(2, 2, 0), ((IInstallableUnit) collection.iterator().next()).getVersion()); + }, new LatestIUVersionQuery()); + IQueryResult queryResult = compositeRepo.query(cQuery, monitor); + assertEquals("1.0", 1, queryResultSize(queryResult)); + assertEquals("1.1", Version.createOSGi(2, 2, 0), ((IInstallableUnit) queryResult.iterator().next()).getVersion()); assertTrue("1.2", monitor.isDone()); assertTrue("1.3", monitor.isWorkDone()); } @@ -535,7 +536,7 @@ public class CompositeMetadataRepositoryTest extends AbstractProvisioningTest { assertContains("Assert child1's content is in composite repo", repo1, compRepo); assertContains("Assert child2's content is in composite repo", repo2, compRepo); //checks that the destination has the correct number of keys (no extras) - assertEquals("Assert correct number of IUs", getNumUnique(repo1.query(InstallableUnitQuery.ANY, new Collector(), null), repo2.query(InstallableUnitQuery.ANY, new Collector(), null)), compRepo.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals("Assert correct number of IUs", getNumUnique(repo1.query(InstallableUnitQuery.ANY, null), repo2.query(InstallableUnitQuery.ANY, null)), queryResultSize(compRepo.query(InstallableUnitQuery.ANY, null))); } private CompositeMetadataRepository createRepo(boolean compressed) { @@ -560,9 +561,9 @@ public class CompositeMetadataRepositoryTest extends AbstractProvisioningTest { * Takes 2 collectors, compares them, and returns the number of unique keys * Needed to verify that only the appropriate number of files have been transfered by the mirror application */ - private int getNumUnique(Collector c1, Collector c2) { - Object[] repo1 = c1.toCollection().toArray(); - Object[] repo2 = c2.toCollection().toArray(); + private int getNumUnique(IQueryResult c1, IQueryResult c2) { + Object[] repo1 = c1.toArray(IInstallableUnit.class); + Object[] repo2 = c2.toArray(IInstallableUnit.class); //initialize to the size of both collectors int numKeys = repo1.length + repo2.length; @@ -584,11 +585,11 @@ public class CompositeMetadataRepositoryTest extends AbstractProvisioningTest { */ public void testNonLocalRepo() { try { - URI location = new URI("memory:/in/memory"); - URI childOne = new URI("memory:/in/memory/one"); - URI childTwo = new URI("memory:/in/memory/two"); - URI childThree = new URI("memory:/in/memory/three"); - CompositeMetadataRepository repository = new CompositeMetadataRepository(location, "in memory test", null); + URI location = new URI("http://foo.org/in/memory"); + URI childOne = new URI("http://foo.org/in/memory/one"); + URI childTwo = new URI("http://foo.org/in/memory/two"); + URI childThree = new URI("http://foo.org/in/memory/three"); + CompositeMetadataRepository repository = createRepository(location, "in memory test"); repository.addChild(childOne); repository.addChild(childTwo); repository.addChild(childThree); @@ -606,6 +607,12 @@ public class CompositeMetadataRepositoryTest extends AbstractProvisioningTest { } } + protected CompositeMetadataRepository createRepository(URI location, String name) { + CompositeMetadataRepositoryFactory factory = new CompositeMetadataRepositoryFactory(); + factory.setAgent(getAgent()); + return (CompositeMetadataRepository) factory.create(location, name, CompositeMetadataRepository.REPOSITORY_TYPE, null); + } + public void testRelativeChildren() { // setup File one = getTestData("0.0", "testData/testRepos/simple.1"); @@ -616,7 +623,7 @@ public class CompositeMetadataRepositoryTest extends AbstractProvisioningTest { // create the composite repository and add the children URI location = new File(temp, "comp").toURI(); - CompositeMetadataRepository repository = new CompositeMetadataRepository(location, "test", null); + CompositeMetadataRepository repository = createRepository(location, "test"); try { repository.addChild(new URI("../one")); repository.addChild(new URI("../two")); @@ -627,8 +634,8 @@ public class CompositeMetadataRepositoryTest extends AbstractProvisioningTest { // query the number of IUs List children = repository.getChildren(); assertEquals("2.0", 2, children.size()); - Collector collector = repository.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); - assertEquals("2.1", 2, collector.size()); + IQueryResult queryResult = repository.query(InstallableUnitQuery.ANY, getMonitor()); + assertEquals("2.1", 2, queryResultSize(queryResult)); // ensure the child URIs are stored as relative CompositeRepositoryState state = repository.toState(); @@ -644,10 +651,10 @@ public class CompositeMetadataRepositoryTest extends AbstractProvisioningTest { public void testRelativeRemoveChild() { try { - URI location = new URI("memory:/in/memory"); + URI location = new URI("http://foo.org/in/memory"); URI one = new URI("one"); URI two = new URI("two"); - CompositeMetadataRepository repository = new CompositeMetadataRepository(location, "in memory test", null); + CompositeMetadataRepository repository = createRepository(location, "in memory test"); repository.addChild(one); repository.addChild(two); List children = repository.getChildren(); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/HttpStatusTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/HttpStatusTest.java index e05f0fb08..7091fc0ec 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/HttpStatusTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/HttpStatusTest.java @@ -16,8 +16,8 @@ import java.text.ParseException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.ServiceReference; @@ -31,7 +31,7 @@ public class HttpStatusTest extends ServerBasedTestCase { public void setUp() throws Exception { super.setUp(); - ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.class.getName()); + ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.SERVICE_NAME); mgr = (IMetadataRepositoryManager) TestActivator.context.getService(sr2); if (mgr == null) { throw new RuntimeException("Repository manager could not be loaded"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/JarURLMetadataRepositoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/JarURLMetadataRepositoryTest.java index 37a794bcf..d127b2417 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/JarURLMetadataRepositoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/JarURLMetadataRepositoryTest.java @@ -11,31 +11,27 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.metadata.repository; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; -import junit.framework.TestCase; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.p2.tests.TestActivator; -import org.osgi.framework.ServiceReference; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; -public class JarURLMetadataRepositoryTest extends TestCase { +public class JarURLMetadataRepositoryTest extends AbstractProvisioningTest { - private ServiceReference managerRef; private IMetadataRepositoryManager manager; private File testRepoJar; @@ -48,8 +44,7 @@ public class JarURLMetadataRepositoryTest extends TestCase { } protected void setUp() throws Exception { - managerRef = TestActivator.getContext().getServiceReference(IMetadataRepositoryManager.class.getName()); - manager = (IMetadataRepositoryManager) TestActivator.getContext().getService(managerRef); + manager = getMetadataRepositoryManager(); String tempDir = System.getProperty("java.io.tmpdir"); File testRepo = new File(tempDir, "testRepo"); @@ -61,7 +56,7 @@ public class JarURLMetadataRepositoryTest extends TestCase { InstallableUnitDescription descriptor = new MetadataFactory.InstallableUnitDescription(); descriptor.setId("testIuId"); - descriptor.setVersion(new Version("3.2.1")); + descriptor.setVersion(Version.create("3.2.1")); IInstallableUnit iu = MetadataFactory.createInstallableUnit(descriptor); repo.addInstallableUnits(new IInstallableUnit[] {iu}); @@ -73,7 +68,6 @@ public class JarURLMetadataRepositoryTest extends TestCase { protected void tearDown() throws Exception { manager = null; FileUtils.deleteAll(testRepoJar.getParentFile()); - TestActivator.getContext().ungetService(managerRef); } public void testJarURLRepository() throws ProvisionException { @@ -85,7 +79,7 @@ public class JarURLMetadataRepositoryTest extends TestCase { } IMetadataRepository repo = manager.loadRepository(jarRepoLocation, null); - assertTrue(!repo.query(InstallableUnitQuery.ANY, new Collector(), null).isEmpty()); + assertTrue(!repo.query(InstallableUnitQuery.ANY, null).isEmpty()); URI[] local = manager.getKnownRepositories(IRepositoryManager.REPOSITORIES_LOCAL); boolean found = false; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/LocalMetadataRepositoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/LocalMetadataRepositoryTest.java index c00214dc5..c87edf31d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/LocalMetadataRepositoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/LocalMetadataRepositoryTest.java @@ -11,20 +11,23 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.metadata.repository; +import org.eclipse.equinox.p2.metadata.Version; + import java.io.File; import java.net.URI; import java.util.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.ProvisioningListener; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.SynchronousProvisioningListener; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** @@ -57,7 +60,7 @@ public class LocalMetadataRepositoryTest extends AbstractProvisioningTest { InstallableUnitDescription descriptor = new MetadataFactory.InstallableUnitDescription(); descriptor.setId("testIuId"); - descriptor.setVersion(new Version("3.2.1")); + descriptor.setVersion(Version.create("3.2.1")); IInstallableUnit iu = MetadataFactory.createInstallableUnit(descriptor); repo.addInstallableUnits(new IInstallableUnit[] {iu}); @@ -122,10 +125,10 @@ public class LocalMetadataRepositoryTest extends AbstractProvisioningTest { IMetadataRepository repo = manager.createRepository(repoLocation.toURI(), "TestRepo", IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, null); IInstallableUnit iu = createIU("foo"); repo.addInstallableUnits(new IInstallableUnit[] {iu}); - Collector result = repo.query(new InstallableUnitQuery((String) null), new Collector(), getMonitor()); - assertTrue("1.0", result.size() == 1); + IQueryResult result = repo.query(new InstallableUnitQuery((String) null), getMonitor()); + assertEquals("1.0", 1, queryResultSize(result)); repo.removeAll(); - result = repo.query(new InstallableUnitQuery((String) null), new Collector(), getMonitor()); + result = repo.query(new InstallableUnitQuery((String) null), getMonitor()); assertTrue("1.1", result.isEmpty()); } @@ -135,13 +138,13 @@ public class LocalMetadataRepositoryTest extends AbstractProvisioningTest { IInstallableUnit iu = createIU("foo"); IInstallableUnit iu2 = createIU("bar"); repo.addInstallableUnits(new IInstallableUnit[] {iu, iu2}); - Collector result = repo.query(new InstallableUnitQuery((String) null), new Collector(), getMonitor()); - assertTrue("1.0", result.size() == 2); - repo.removeInstallableUnits(new InstallableUnitQuery("foo"), getMonitor()); - result = repo.query(new InstallableUnitQuery((String) null), new Collector(), getMonitor()); - assertTrue("1.1", result.size() == 1); - repo.removeInstallableUnits(new InstallableUnitQuery("bar"), getMonitor()); - result = repo.query(new InstallableUnitQuery((String) null), new Collector(), getMonitor()); + IQueryResult result = repo.query(new InstallableUnitQuery((String) null), getMonitor()); + assertEquals("1.0", 2, queryResultSize(result)); + repo.removeInstallableUnits(new IInstallableUnit[] {iu}, getMonitor()); + result = repo.query(new InstallableUnitQuery((String) null), getMonitor()); + assertEquals("1.1", 1, queryResultSize(result)); + repo.removeInstallableUnits(new IInstallableUnit[] {iu2}, getMonitor()); + result = repo.query(new InstallableUnitQuery((String) null), getMonitor()); assertTrue("1.2", result.isEmpty()); } @@ -154,7 +157,7 @@ public class LocalMetadataRepositoryTest extends AbstractProvisioningTest { InstallableUnitDescription descriptor = new MetadataFactory.InstallableUnitDescription(); descriptor.setId("testIuId"); - descriptor.setVersion(new Version("3.2.1")); + descriptor.setVersion(Version.create("3.2.1")); IInstallableUnit iu = MetadataFactory.createInstallableUnit(descriptor); repo.addInstallableUnits(new IInstallableUnit[] {iu}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/MetadataRepositoryManagerExceptionsTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/MetadataRepositoryManagerExceptionsTest.java index 890e5df46..8c7d4a509 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/MetadataRepositoryManagerExceptionsTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/MetadataRepositoryManagerExceptionsTest.java @@ -18,11 +18,11 @@ import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.internal.p2.metadata.repository.SimpleMetadataRepositoryFactory; import org.eclipse.equinox.internal.p2.updatesite.metadata.UpdateSiteMetadataRepositoryFactory; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.SimpleMetadataRepositoryFactory; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; @@ -42,7 +42,7 @@ public class MetadataRepositoryManagerExceptionsTest extends AbstractProvisionin protected void setUp() throws Exception { super.setUp(); - manager = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.context, IMetadataRepositoryManager.class.getName()); + manager = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.context, IMetadataRepositoryManager.SERVICE_NAME); } protected void tearDown() throws Exception { @@ -64,6 +64,7 @@ public class MetadataRepositoryManagerExceptionsTest extends AbstractProvisionin MetadataRepositoryFactory factory; factory = new SimpleMetadataRepositoryFactory(); + factory.setAgent(getAgent()); try { factory.load(location, 0, new NullProgressMonitor()); } catch (ProvisionException e) { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/MetadataRepositoryManagerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/MetadataRepositoryManagerTest.java index 004752c03..bbe260e64 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/MetadataRepositoryManagerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/MetadataRepositoryManagerTest.java @@ -13,27 +13,29 @@ package org.eclipse.equinox.p2.tests.metadata.repository; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; -import java.net.*; +import java.net.URI; +import java.net.URISyntaxException; import java.util.*; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.core.helpers.URLUtil; +import org.eclipse.equinox.internal.p2.metadata.repository.SimpleMetadataRepositoryFactory; import org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager; import org.eclipse.equinox.internal.p2.updatesite.metadata.UpdateSiteMetadataRepositoryFactory; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.ProvisioningListener; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.SynchronousProvisioningListener; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.*; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.SimpleMetadataRepositoryFactory; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory; import org.eclipse.equinox.p2.tests.*; /** @@ -52,7 +54,7 @@ public class MetadataRepositoryManagerTest extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - manager = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.context, IMetadataRepositoryManager.class.getName()); + manager = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.context, IMetadataRepositoryManager.SERVICE_NAME); //only enable the failing repository factory for this test to avoid noise in other tests. FailingMetadataRepositoryFactory.FAIL = true; } @@ -121,6 +123,7 @@ public class MetadataRepositoryManagerTest extends AbstractProvisioningTest { MetadataRepositoryFactory factory; factory = new SimpleMetadataRepositoryFactory(); + factory.setAgent(getAgent()); try { factory.load(location, 0, new NullProgressMonitor()); } catch (ProvisionException e) { @@ -327,9 +330,9 @@ public class MetadataRepositoryManagerTest extends AbstractProvisioningTest { */ public void testMetadataCachingLocalRepo() throws ProvisionException { File repoLocation = getTempLocation(); - AgentLocation agentLocation = (AgentLocation) ServiceHelper.getService(TestActivator.getContext(), AgentLocation.class.getName()); - URL dataArea = agentLocation.getDataArea("org.eclipse.equinox.p2.metadata.repository/cache/"); - File dataAreaFile = URLUtil.toFile(dataArea); + IAgentLocation agentLocation = (IAgentLocation) ServiceHelper.getService(TestActivator.getContext(), IAgentLocation.class.getName()); + URI dataArea = agentLocation.getDataArea("org.eclipse.equinox.p2.metadata.repository/cache/"); + File dataAreaFile = URIUtil.toFile(dataArea); File cacheFileXML = new File(dataAreaFile, "content" + repoLocation.hashCode() + ".xml"); File cacheFileJAR = new File(dataAreaFile, "content" + repoLocation.hashCode() + ".jar"); @@ -349,9 +352,9 @@ public class MetadataRepositoryManagerTest extends AbstractProvisioningTest { URI repoLocation = new URI("http://download.eclipse.org/eclipse/updates/3.4milestones/"); if (!repoAvailable(repoLocation)) return; - AgentLocation agentLocation = (AgentLocation) ServiceHelper.getService(TestActivator.getContext(), AgentLocation.class.getName()); - URL dataArea = agentLocation.getDataArea("org.eclipse.equinox.p2.metadata.repository/cache/"); - File dataAreaFile = URLUtil.toFile(dataArea); + IAgentLocation agentLocation = (IAgentLocation) ServiceHelper.getService(TestActivator.getContext(), IAgentLocation.class.getName()); + URI dataArea = agentLocation.getDataArea("org.eclipse.equinox.p2.metadata.repository/cache/"); + File dataAreaFile = URIUtil.toFile(dataArea); File cacheFileXML = new File(dataAreaFile, "content" + repoLocation.hashCode() + ".xml"); File cacheFileJAR = new File(dataAreaFile, "content" + repoLocation.hashCode() + ".jar"); File cacheFile; @@ -406,8 +409,8 @@ public class MetadataRepositoryManagerTest extends AbstractProvisioningTest { URI location = site.toURI(); try { IMetadataRepository repository = manager.loadRepository(location, getMonitor()); - Collector result = repository.query(new InstallableUnitQuery("test.bundle"), new Collector(), getMonitor()); - assertEquals("1.0", 1, result.size()); + IQueryResult result = repository.query(new InstallableUnitQuery("test.bundle"), getMonitor()); + assertEquals("1.0", 1, queryResultSize(result)); } catch (ProvisionException e) { fail("=.99", e); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/NoFailOver.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/NoFailOver.java index 84752a35d..e15e1eee5 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/NoFailOver.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/NoFailOver.java @@ -11,7 +11,7 @@ package org.eclipse.equinox.p2.tests.metadata.repository; import java.io.File; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.core.ProvisionException; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/ResumeDownloadTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/ResumeDownloadTest.java index 2f70b5321..692cf93ea 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/ResumeDownloadTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/ResumeDownloadTest.java @@ -15,8 +15,8 @@ import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.ecf.filetransfer.IFileRangeSpecification; import org.eclipse.ecf.filetransfer.IIncomingFileTransfer; import org.eclipse.equinox.internal.p2.repository.FileReader; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.ServiceReference; @@ -31,7 +31,7 @@ public class ResumeDownloadTest extends TestCase { repoLoc = new URI(UPDATE_SITE); originalResumeProp = System.getProperty("org.eclipse.equinox.p2.metadata.repository.resumable", "true"); - ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.class.getName()); + ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.SERVICE_NAME); mgr = (IMetadataRepositoryManager) TestActivator.context.getService(sr2); if (mgr == null) { throw new RuntimeException("Repository manager could not be loaded"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/SPIMetadataRepositoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/SPIMetadataRepositoryTest.java index 0b2dacd4f..6d64263a4 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/SPIMetadataRepositoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/SPIMetadataRepositoryTest.java @@ -18,17 +18,22 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; import org.eclipse.equinox.internal.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitPatchDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.MatchQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil; +import org.eclipse.equinox.p2.metadata.expression.IMatchExpression; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.query.MatchQuery; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; +import org.osgi.framework.Filter; /** * Test API of the metadata interfaces with an SPI implementation. @@ -50,25 +55,23 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { super.tearDown(); } - class SPIRequiredCapability implements IRequiredCapability { - String filter; + class SPIRequiredCapability extends MatchQuery implements IRequiredCapability { + Filter filter; String name; String namespace; VersionRange versionRange; - String[] selectors = new String[0]; boolean isGreedy; - boolean isMultiple; - boolean isOptional; + int min; + int max; - public SPIRequiredCapability(String namespace, String name, VersionRange versionRange, String filter, String[] selectors, boolean isGreedy, boolean isMultiple, boolean isOptional) { + public SPIRequiredCapability(String namespace, String name, VersionRange versionRange, String filter, boolean isGreedy, boolean isMultiple, boolean isOptional) { this.namespace = namespace; this.name = name; this.versionRange = versionRange; - this.filter = filter; - this.selectors = selectors; + setFilter(filter); this.isGreedy = isGreedy; - this.isMultiple = isMultiple; - this.isOptional = isOptional; + this.min = isOptional ? 0 : 1; + this.max = 1; } public SPIRequiredCapability(String namespace, String name, VersionRange versionRange) { @@ -77,7 +80,7 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { this.versionRange = versionRange; } - public String getFilter() { + public Filter getFilter() { return this.filter; } @@ -93,28 +96,12 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { return this.versionRange; } - public String[] getSelectors() { - return selectors; - } - public boolean isGreedy() { return isGreedy; } - public boolean isMultiple() { - return this.isMultiple; - } - - public boolean isOptional() { - return this.isOptional; - } - public void setFilter(String filter) { - this.filter = filter; - } - - public void setSelectors(String[] selectors) { - this.selectors = selectors; + this.filter = filter == null ? null : ExpressionUtil.parseLDAP(filter); } public boolean equals(Object obj) { @@ -130,13 +117,13 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { return false; } else if (!filter.equals(other.getFilter())) return false; - if (isMultiple != other.isMultiple()) - return false; if (!name.equals(other.getName())) return false; if (!namespace.equals(other.getNamespace())) return false; - if (isOptional != other.isOptional()) + if (other.getMin() != this.getMin()) + return false; + if (other.getMax() != this.getMax()) return false; if (!versionRange.equals(other.getRange())) return false; @@ -155,6 +142,28 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { return getRange().isIncluded(cap.getVersion()); } + public int getMin() { + return min; + } + + public int getMax() { + return max; + } + + public boolean isMatch(IInstallableUnit candidate) { + if (!candidate.satisfies(this)) + return false; + return true; + } + + public boolean isVersionStrict() { + // TODO Auto-generated method stub + return false; + } + + public IMatchExpression getMatches() { + return ExpressionUtil.getFactory().matchExpression(ExpressionUtil.parse("providedCapabilities.exists(x | x.name == $0 && x.namespace == $1 && x.version ~= $2"), name, namespace, versionRange); + } } class SPIProvidedCapability implements IProvidedCapability { @@ -194,7 +203,7 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { return this.version; } - public boolean satisfies(IRequiredCapability candidate) { + public boolean satisfies(IRequirement candidate) { return false; } @@ -208,9 +217,9 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { List providedCapabilities = new ArrayList(); List touchpointData = new ArrayList(); ICopyright copyright = null; - String filter = null; + Filter filter = null; String id = null; - ILicense license = null; + ILicense[] license = null; Map properties = new HashMap(); ITouchpointType touchpointType = null; IUpdateDescriptor updateDescriptor = null; @@ -228,28 +237,28 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { this.providedCapabilities.add(providedCapability); } - public IArtifactKey[] getArtifacts() { - return (IArtifactKey[]) this.artifacts.toArray(new IArtifactKey[artifacts.size()]); + public Collection getArtifacts() { + return artifacts; } public ICopyright getCopyright() { return this.copyright; } - public String getFilter() { + public Filter getFilter() { return this.filter; } - public IInstallableUnitFragment[] getFragments() { - return (IInstallableUnitFragment[]) this.fragments.toArray(new IInstallableUnitFragment[fragments.size()]); + public List getFragments() { + return fragments; } public String getId() { return this.id; } - public ILicense getLicense() { - return this.license; + public Collection getLicenses() { + return CollectionUtils.unmodifiableList(license); } public Map getProperties() { @@ -260,16 +269,16 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { return (String) this.properties.get(key); } - public IProvidedCapability[] getProvidedCapabilities() { - return (IProvidedCapability[]) this.providedCapabilities.toArray(new IProvidedCapability[profilesToRemove.size()]); + public List getProvidedCapabilities() { + return providedCapabilities; } - public IRequiredCapability[] getRequiredCapabilities() { - return (IRequiredCapability[]) this.requiredCapabilities.toArray(new IRequiredCapability[requiredCapabilities.size()]); + public List getRequiredCapabilities() { + return requiredCapabilities; } - public ITouchpointData[] getTouchpointData() { - return (ITouchpointData[]) this.touchpointData.toArray(new ITouchpointData[touchpointData.size()]); + public List getTouchpointData() { + return touchpointData; } public ITouchpointType getTouchpointType() { @@ -298,32 +307,36 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { return this.isSingleton; } - public boolean satisfies(IRequiredCapability candidate) { - IProvidedCapability[] provides = getProvidedCapabilities(); - for (int i = 0; i < provides.length; i++) - if (provides[i].satisfies(candidate)) - return true; - return false; + public boolean satisfies(IRequirement candidate) { + return candidate.isMatch(this); } public IInstallableUnit unresolved() { return this; } - public int compareTo(Object toCompareTo) { - if (!(toCompareTo instanceof IInstallableUnit)) { - return -1; - } - IInstallableUnit other = (IInstallableUnit) toCompareTo; + public int compareTo(IInstallableUnit other) { if (getId().compareTo(other.getId()) == 0) return (getVersion().compareTo(other.getVersion())); return getId().compareTo(other.getId()); } - public IRequiredCapability[] getMetaRequiredCapabilities() { + public List getMetaRequiredCapabilities() { return null; } + public String getProperty(String key, String locale) { + return getProperty(key); + } + + public ILicense[] getLicenses(String locale) { + return license; + } + + public ICopyright getCopyright(String locale) { + return copyright; + } + } class SPITouchpointData implements ITouchpointData { @@ -538,6 +551,7 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { private String body; private URI location; + private String uuid; public SPILicense(String body, URI location) { this.body = body; @@ -548,8 +562,10 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { return this.body; } - public BigInteger getDigest() { - return this.calculateLicenseDigest(); + public String getUUID() { + if (uuid == null) + uuid = this.calculateLicenseDigest().toString(16); + return uuid; } public URI getLocation() { @@ -563,7 +579,7 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { return false; if (obj instanceof ILicense) { ILicense other = (ILicense) obj; - if (other.getDigest().equals(getDigest())) + if (other.getUUID().equals(getUUID())) return true; } return false; @@ -624,22 +640,20 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { properties.put(IRepository.PROP_COMPRESSED, "true"); IMetadataRepository repo = manager.createRepository(repoLocation.toURI(), "TestRepo", IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); - repo.addInstallableUnits(new IInstallableUnit[] {new SPIInstallableUnit("foo", new Version(1, 1, 1))}); + repo.addInstallableUnits(new IInstallableUnit[] {new SPIInstallableUnit("foo", Version.createOSGi(1, 1, 1))}); - Collector collector = repo.query(new AllAcceptingQuery(), new Collector(), new NullProgressMonitor()); + IQueryResult queryResult = repo.query(new AllAcceptingQuery(), new NullProgressMonitor()); - Collection collection = collector.toCollection(); - assertEquals(1, collection.size()); + assertEquals(1, queryResultSize(queryResult)); - assertTrue("Repo contains SPI IU)", collection.iterator().next() instanceof SPIInstallableUnit); + assertTrue("Repo contains SPI IU)", queryResult.iterator().next() instanceof SPIInstallableUnit); repo = manager.refreshRepository(repoLocation.toURI(), null); - collector = repo.query(new AllAcceptingQuery(), new Collector(), new NullProgressMonitor()); + queryResult = repo.query(new AllAcceptingQuery(), new NullProgressMonitor()); - collection = collector.toCollection(); - assertEquals(1, collection.size()); + assertEquals(1, queryResultSize(queryResult)); - assertTrue("Refreshed repo contains default IU", collection.iterator().next() instanceof InstallableUnit); + assertTrue("Refreshed repo contains default IU", queryResult.iterator().next() instanceof InstallableUnit); } /** @@ -655,32 +669,30 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { properties.put(IRepository.PROP_COMPRESSED, "true"); IMetadataRepository repo = manager.createRepository(repoLocation.toURI(), "TestRepo", IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); - IProvidedCapability providedCapability = MetadataFactory.createProvidedCapability("foo", "bar", new Version(1, 0, 0)); + IProvidedCapability providedCapability = MetadataFactory.createProvidedCapability("foo", "bar", Version.createOSGi(1, 0, 0)); - SPIInstallableUnit spiInstallableUnit = new SPIInstallableUnit("foo", new Version(1, 1, 1)); + SPIInstallableUnit spiInstallableUnit = new SPIInstallableUnit("foo", Version.createOSGi(1, 1, 1)); spiInstallableUnit.addProvidedCapability(providedCapability); repo.addInstallableUnits(new IInstallableUnit[] {spiInstallableUnit}); - Collector collector = repo.query(new AllAcceptingQuery(), new Collector(), new NullProgressMonitor()); + IQueryResult queryResult = repo.query(new AllAcceptingQuery(), new NullProgressMonitor()); - Collection collection = collector.toCollection(); - assertEquals(1, collection.size()); + assertEquals(1, queryResultSize(queryResult)); - IInstallableUnit spiUnit = (IInstallableUnit) collection.iterator().next(); + IInstallableUnit spiUnit = (IInstallableUnit) queryResult.iterator().next(); assertTrue("Repo contains SPI IU)", spiUnit instanceof SPIInstallableUnit); - assertEquals(spiUnit.getProvidedCapabilities().length, 1); - assertTrue(spiUnit.getProvidedCapabilities()[0] instanceof ProvidedCapability); + assertEquals(spiUnit.getProvidedCapabilities().size(), 1); + assertTrue(spiUnit.getProvidedCapabilities().iterator().next() instanceof ProvidedCapability); repo = manager.refreshRepository(repoLocation.toURI(), null); - collector = repo.query(new AllAcceptingQuery(), new Collector(), new NullProgressMonitor()); + queryResult = repo.query(new AllAcceptingQuery(), new NullProgressMonitor()); - collection = collector.toCollection(); - assertEquals(1, collection.size()); + assertEquals(1, queryResultSize(queryResult)); - IInstallableUnit defaultUnit = (IInstallableUnit) collection.iterator().next(); + IInstallableUnit defaultUnit = (IInstallableUnit) queryResult.iterator().next(); assertTrue("Repo contains SPI IU)", defaultUnit instanceof InstallableUnit); - assertEquals(spiUnit.getProvidedCapabilities().length, 1); - assertTrue(spiUnit.getProvidedCapabilities()[0] instanceof ProvidedCapability); + assertEquals(spiUnit.getProvidedCapabilities().size(), 1); + assertTrue(spiUnit.getProvidedCapabilities().iterator().next() instanceof ProvidedCapability); } /** @@ -698,33 +710,31 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { IMetadataRepository repo = manager.createRepository(repoLocation.toURI(), "TestRepo", IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); InstallableUnitDescription iuDescription = new InstallableUnitDescription(); iuDescription.setId("foo"); - iuDescription.setVersion(new Version(1, 1, 1)); - IRequiredCapability spiRequiredCapability = new SPIRequiredCapability("com.example", "bar", new VersionRange(new Version(1, 0, 0), true, new Version(2, 0, 0), true)); + iuDescription.setVersion(Version.createOSGi(1, 1, 1)); + IRequiredCapability spiRequiredCapability = new SPIRequiredCapability("com.example", "bar", new VersionRange(Version.createOSGi(1, 0, 0), true, Version.createOSGi(2, 0, 0), true)); Collection list = new ArrayList(); list.add(spiRequiredCapability); iuDescription.addRequiredCapabilities(list); repo.addInstallableUnits(new IInstallableUnit[] {MetadataFactory.createInstallableUnit(iuDescription)}); - Collector collector = repo.query(new AllAcceptingQuery(), new Collector(), new NullProgressMonitor()); + IQueryResult queryResult = repo.query(new AllAcceptingQuery(), new NullProgressMonitor()); - Collection collection = collector.toCollection(); - assertEquals(1, collection.size()); + assertEquals(1, queryResultSize(queryResult)); - IInstallableUnit unit = (IInstallableUnit) collection.iterator().next(); - assertEquals(unit.getRequiredCapabilities().length, 1); - assertTrue(unit.getRequiredCapabilities()[0] instanceof SPIRequiredCapability); + IInstallableUnit unit = (IInstallableUnit) queryResult.iterator().next(); + assertEquals(unit.getRequiredCapabilities().size(), 1); + assertTrue(unit.getRequiredCapabilities().iterator().next() instanceof SPIRequiredCapability); repo = manager.refreshRepository(repoLocation.toURI(), null); - collector = repo.query(new AllAcceptingQuery(), new Collector(), new NullProgressMonitor()); + queryResult = repo.query(new AllAcceptingQuery(), new NullProgressMonitor()); - collection = collector.toCollection(); - assertEquals(1, collection.size()); + assertEquals(1, queryResultSize(queryResult)); - unit = (IInstallableUnit) collection.iterator().next(); - assertEquals(unit.getRequiredCapabilities().length, 1); - assertTrue(unit.getRequiredCapabilities()[0] instanceof RequiredCapability); - assertTrue(unit.getRequiredCapabilities()[0].getName().equals("bar")); + unit = (IInstallableUnit) queryResult.iterator().next(); + assertEquals(unit.getRequiredCapabilities().size(), 1); + assertTrue(unit.getRequiredCapabilities().iterator().next() instanceof RequiredCapability); + assertTrue(((IRequiredCapability) unit.getRequiredCapabilities().iterator().next()).getName().equals("bar")); } /** @@ -741,16 +751,16 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { InstallableUnitDescription iuDescription = new InstallableUnitDescription(); InstallableUnitPatchDescription iuPatchDescription = new InstallableUnitPatchDescription(); iuDescription.setId("foo"); - iuDescription.setVersion(new Version(1, 1, 1)); + iuDescription.setVersion(Version.createOSGi(1, 1, 1)); - SPIRequiredCapability spiRequiredCapability1 = new SPIRequiredCapability("com.example", "bar", new VersionRange(new Version(1, 0, 0), true, new Version(2, 0, 0), true), "bar", new String[] {"foo", "bar"}, true, true, true); - IRequiredCapability requiredCapability1 = MetadataFactory.createRequiredCapability("com.example2", "foo", new VersionRange(new Version(1, 0, 0), true, new Version(2, 0, 0), true), "bar", false, false, false); + SPIRequiredCapability spiRequiredCapability1 = new SPIRequiredCapability("com.example", "bar", new VersionRange(Version.createOSGi(1, 0, 0), true, Version.createOSGi(2, 0, 0), true), "(bar=foo)", true, true, true); + IRequiredCapability requiredCapability1 = MetadataFactory.createRequiredCapability("com.example2", "foo", new VersionRange(Version.createOSGi(1, 0, 0), true, Version.createOSGi(2, 0, 0), true), "(bar=foo)", false, false, false); SPIRequirementChange spiRequirementChange = new SPIRequirementChange(spiRequiredCapability1, requiredCapability1); iuPatchDescription.setRequirementChanges(new IRequirementChange[] {spiRequirementChange}); - IRequiredCapability spiRequiredCapability = new SPIRequiredCapability("com.example", "bar", new VersionRange(new Version(1, 0, 0), true, new Version(2, 0, 0), true), "bar", new String[] {"foo", "bar"}, true, true, true); - IProvidedCapability spiProvidedCapability = new SPIProvidedCapability("bar", "foo", new Version(1, 1, 1)); + IRequiredCapability spiRequiredCapability = new SPIRequiredCapability("com.example", "bar", new VersionRange(Version.createOSGi(1, 0, 0), true, Version.createOSGi(2, 0, 0), true), "(bar=foo)", true, true, true); + IProvidedCapability spiProvidedCapability = new SPIProvidedCapability("bar", "foo", Version.createOSGi(1, 1, 1)); ITouchpointData spiTouchpointData = new SPITouchpointData(); ITouchpointInstruction spiTouchpointInstruction = new SPITouchpointInstruction("the body", "the import attribute"); @@ -758,9 +768,9 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { iuDescription.addTouchpointData(spiTouchpointData); SPILicense spiLicense = new SPILicense("body", new URI("http://example.com")); - iuDescription.setLicense(spiLicense); + iuDescription.setLicenses(new ILicense[] {spiLicense}); - SPITouchpointType spiTouchpointType = new SPITouchpointType("foo", new Version(3, 3, 3)); + SPITouchpointType spiTouchpointType = new SPITouchpointType("foo", Version.createOSGi(3, 3, 3)); iuDescription.setTouchpointType(spiTouchpointType); Collection requiredCapabilityList = new ArrayList(); @@ -774,11 +784,10 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { repo.addInstallableUnits(new IInstallableUnit[] {MetadataFactory.createInstallableUnit(iuDescription), MetadataFactory.createInstallableUnitPatch(iuPatchDescription)}); repo = manager.refreshRepository(repoLocation.toURI(), null); - Collector collector = repo.query(new AllAcceptingQuery(), new Collector(), new NullProgressMonitor()); + IQueryResult queryResult = repo.query(new AllAcceptingQuery(), new NullProgressMonitor()); - Collection collection = collector.toCollection(); - assertEquals(2, collection.size()); - Iterator iterator = collection.iterator(); + assertEquals(2, queryResultSize(queryResult)); + Iterator iterator = queryResult.iterator(); IInstallableUnit unit = null; IInstallableUnitPatch patchUnit = null; @@ -793,30 +802,32 @@ public class SPIMetadataRepositoryTest extends AbstractProvisioningTest { assertFalse(unit == null); assertFalse(patchUnit == null); - assertEquals(unit.getRequiredCapabilities().length, 1); - assertEquals(unit.getProvidedCapabilities().length, 1); - assertEquals(unit.getTouchpointData().length, 1); - assertEquals(unit.getRequiredCapabilities()[0], spiRequiredCapability); - assertEquals(unit.getProvidedCapabilities()[0], spiProvidedCapability); - assertEquals(unit.getTouchpointData()[0], spiTouchpointData); + assertEquals(unit.getRequiredCapabilities().size(), 1); + assertEquals(unit.getProvidedCapabilities().size(), 1); + assertEquals(unit.getTouchpointData().size(), 1); + assertEquals(((IRequiredCapability) unit.getRequiredCapabilities().iterator().next()).getNamespace(), spiRequiredCapability.getNamespace()); + assertEquals(((IRequiredCapability) unit.getRequiredCapabilities().iterator().next()).getName(), spiRequiredCapability.getName()); + assertEquals(((IRequiredCapability) unit.getRequiredCapabilities().iterator().next()).getMin(), spiRequiredCapability.getMin()); + assertEquals(((IRequiredCapability) unit.getRequiredCapabilities().iterator().next()).getMax(), spiRequiredCapability.getMax()); + assertEquals(unit.getProvidedCapabilities().iterator().next(), spiProvidedCapability); + assertEquals(unit.getTouchpointData().get(0), spiTouchpointData); assertEquals(unit.getTouchpointType(), spiTouchpointType); - assertEquals(unit.getLicense(), spiLicense); - assertEquals(spiRequiredCapability, unit.getRequiredCapabilities()[0]); - assertEquals(spiProvidedCapability, unit.getProvidedCapabilities()[0]); - assertEquals(spiTouchpointData, unit.getTouchpointData()[0]); + assertEquals(unit.getLicenses().iterator().next(), spiLicense); + assertEquals(spiProvidedCapability, unit.getProvidedCapabilities().iterator().next()); + assertEquals(spiTouchpointData, unit.getTouchpointData().get(0)); assertEquals(spiTouchpointType, unit.getTouchpointType()); - assertEquals(spiLicense, unit.getLicense()); + assertEquals(spiLicense, unit.getLicenses().iterator().next()); - assertEquals(patchUnit.getRequirementsChange().length, 1); - assertEquals(patchUnit.getRequirementsChange()[0], spiRequirementChange); - assertEquals(spiRequirementChange, patchUnit.getRequirementsChange()[0]); + assertEquals(patchUnit.getRequirementsChange().size(), 1); + assertEquals(patchUnit.getRequirementsChange().get(0), spiRequirementChange); + assertEquals(spiRequirementChange, patchUnit.getRequirementsChange().get(0)); // Check to make sure the actual objects are not equal. This is because the repo has // been refreshed, and re-parsed, thus using the default implementations. - assertFalse(spiTouchpointData == unit.getTouchpointData()[0]); - assertFalse(spiRequiredCapability == unit.getRequiredCapabilities()[0]); - assertFalse(spiProvidedCapability == unit.getProvidedCapabilities()[0]); + assertFalse(spiTouchpointData == unit.getTouchpointData().get(0)); + assertFalse(spiRequiredCapability == unit.getRequiredCapabilities().iterator().next()); + assertFalse(spiProvidedCapability == unit.getProvidedCapabilities().iterator().next()); assertFalse(spiTouchpointType == unit.getTouchpointType()); - assertFalse(spiLicense == unit.getLicense()); + assertFalse(spiLicense == unit.getLicenses().iterator().next()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/TimeoutTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/TimeoutTest.java index e5e267130..ca68bbfd0 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/TimeoutTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/TimeoutTest.java @@ -12,8 +12,8 @@ import java.net.URI; import java.security.cert.Certificate; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.framework.ServiceReference; @@ -27,7 +27,7 @@ public class TimeoutTest extends ServerBasedTestCase { public void setUp() throws Exception { super.setUp(); - ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.class.getName()); + ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.SERVICE_NAME); mgr = (IMetadataRepositoryManager) TestActivator.context.getService(sr2); if (mgr == null) { throw new RuntimeException("Repository manager could not be loaded"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/ArtifactMirrorApplicationTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/ArtifactMirrorApplicationTest.java index 7b137916b..f3f7d67f4 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/ArtifactMirrorApplicationTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/ArtifactMirrorApplicationTest.java @@ -10,29 +10,31 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.mirror; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.*; import java.net.*; import java.util.*; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.app.IApplicationContext; -import org.eclipse.equinox.internal.p2.artifact.mirror.MirrorApplication; import org.eclipse.equinox.internal.p2.artifact.processors.md5.Messages; import org.eclipse.equinox.internal.p2.artifact.repository.*; import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository; import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.internal.repository.comparator.MD5ArtifactComparator; +import org.eclipse.equinox.p2.internal.repository.tools.MirrorApplication; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; import org.eclipse.osgi.framework.log.FrameworkLog; import org.eclipse.osgi.util.NLS; -import org.osgi.framework.Bundle; /** * Test API of the basic mirror application functionality's implementation. @@ -81,43 +83,11 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { */ private void runMirrorApplication(String message, final String[] args) throws Exception { MirrorApplication application = new MirrorApplication(); - application.start(new IApplicationContext() { - - public void applicationRunning() { - } - - public Map getArguments() { - Map arguments = new HashMap(); - - arguments.put(IApplicationContext.APPLICATION_ARGS, args); - - return arguments; - } - - public String getBrandingApplication() { - return null; - } - - public Bundle getBrandingBundle() { - return null; - } - - public String getBrandingDescription() { - return null; - } - - public String getBrandingId() { - return null; - } - - public String getBrandingName() { - return null; - } - - public String getBrandingProperty(String key) { - return null; - } - }); + Map map = new HashMap(); + map.put("metadataOrArtifacts", "artifacts"); + application.setInitializationData(null, null, map); + application.initializeFromArguments(args); + application.run(null); } /** @@ -319,15 +289,15 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { * Not Biconditional. */ private void assertFileSizes(String message, SimpleArtifactRepository expected, SimpleArtifactRepository actual) { - IArtifactKey[] expectedKeys = expected.getArtifactKeys(); - - for (int i = 0; i < expectedKeys.length; i++) { - IArtifactDescriptor[] expectedDescriptors = expected.getArtifactDescriptors(expectedKeys[i]); - IArtifactDescriptor[] actualDescriptors = actual.getArtifactDescriptors(expectedKeys[i]); + IQueryResult expectedKeys = expected.query(ArtifactKeyQuery.ALL_KEYS, null); + for (Iterator iterator = expectedKeys.iterator(); iterator.hasNext();) { + IArtifactKey key = (IArtifactKey) iterator.next(); + IArtifactDescriptor[] expectedDescriptors = expected.getArtifactDescriptors(key); + IArtifactDescriptor[] actualDescriptors = actual.getArtifactDescriptors(key); if (expectedDescriptors == null || actualDescriptors == null) if (!(expectedDescriptors == null && actualDescriptors == null)) - fail(message + " missing key " + expectedKeys[i]); + fail(message + " missing key " + key); top: for (int j = 0; j < expectedDescriptors.length; j++) { for (int k = 0; k < actualDescriptors.length; k++) { @@ -429,7 +399,7 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { assertContains("5.1", getArtifactRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("5.2", getArtifactRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("5.3", getArtifactRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).getArtifactKeys().length + getArtifactRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).getArtifactKeys().length, getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null).getArtifactKeys().length); + assertEquals("5.3", getArtifactKeyCount(sourceRepoLocation.toURI()) + getArtifactKeyCount(sourceRepo2Location.toURI()), getArtifactKeyCount(destRepoLocation.toURI())); } catch (ProvisionException e) { fail("5.4", e); } @@ -534,7 +504,7 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { assertContains("11.1", getArtifactRepositoryManager().loadRepository(sourceRepo3Location.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("11.2", getArtifactRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("11.3", getArtifactRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).getArtifactKeys().length + getArtifactRepositoryManager().loadRepository(sourceRepo3Location.toURI(), null).getArtifactKeys().length, getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null).getArtifactKeys().length); + assertEquals("11.3", getArtifactKeyCount(sourceRepo2Location.toURI()) + getArtifactKeyCount(sourceRepo3Location.toURI()), getArtifactKeyCount(destRepoLocation.toURI())); } catch (ProvisionException e) { fail("11.4", e); } @@ -587,7 +557,7 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { basicRunMirrorApplication("14.1", sourceRepoLocation.toURL(), invalidDestRepository.toURL(), true); //we're expecting an UnsupportedOperationException so we should never get here fail("14.0 UnsupportedOperationException not thrown"); - } catch (UnsupportedOperationException e) { + } catch (ProvisionException e) { return; //correct type of exception has been thrown } catch (Exception e) { fail("14.2", e); @@ -722,7 +692,7 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { assertContains("20.2", getArtifactRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("20.3", getArtifactRepositoryManager().loadRepository(sourceRepo4Location.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("20.4", getArtifactRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).getArtifactKeys().length + getArtifactRepositoryManager().loadRepository(sourceRepo4Location.toURI(), null).getArtifactKeys().length, getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null).getArtifactKeys().length); + assertEquals("20.4", getArtifactKeyCount(sourceRepoLocation.toURI()) + getArtifactKeyCount(sourceRepo4Location.toURI()), getArtifactKeyCount(destRepoLocation.toURI())); } catch (ProvisionException e) { fail("20.5", e); } @@ -735,13 +705,13 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { String[] args = null; //create arguments without a "-source" - args = new String[] {"-destination", destRepoLocation.toURI().toString()}; + args = new String[] {"-destination", "file:" + destRepoLocation.getAbsolutePath()}; try { runMirrorApplication("21.1", args); //We expect the IllegalStateException to be thrown fail("21.3 IllegalStateException not thrown"); - } catch (IllegalStateException e) { + } catch (IllegalArgumentException e) { return; //expected type of exception has been thrown } catch (Exception e) { fail("21.2", e); @@ -755,13 +725,13 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { String[] args = null; //create arguments without a "-destination" - args = new String[] {"-source", sourceRepoLocation.toURI().toString()}; + args = new String[] {"-source", "file:" + sourceRepoLocation.getAbsolutePath()}; try { runMirrorApplication("22.1", args); //We expect the IllegalStateException to be thrown fail("22.3 IllegalStateException not thrown"); - } catch (IllegalStateException e) { + } catch (IllegalArgumentException e) { return; //expected type of exception has been thrown } catch (Exception e) { fail("22.2", e); @@ -779,7 +749,7 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { runMirrorApplication("23.0", args); //We expect the IllegalStateException to be thrown fail("23.2 IllegalStateException not thrown"); - } catch (IllegalStateException e) { + } catch (IllegalArgumentException e) { return; //expected type of exception has been thrown } catch (Exception e) { fail("23.1", e); @@ -926,15 +896,15 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { fail(""); } - IArtifactKey[] keys = packedRepo.getArtifactKeys(); - - for (int i = 0; i < keys.length; i++) { - IArtifactDescriptor[] srcDescriptors = packedRepo.getArtifactDescriptors(keys[i]); + IQueryResult keys = packedRepo.query(ArtifactKeyQuery.ALL_KEYS, null); + for (Iterator iterator = keys.iterator(); iterator.hasNext();) { + IArtifactKey key = (IArtifactKey) iterator.next(); + IArtifactDescriptor[] srcDescriptors = packedRepo.getArtifactDescriptors(key); for (int j = 0; j < srcDescriptors.length; j++) { - if (!(srcDescriptors[j].getProperty(IArtifactDescriptor.FORMAT) == null) && srcDescriptors[j].getProperty(IArtifactDescriptor.FORMAT).equals("packed")) { + if (!(srcDescriptors[j].getProperty(IArtifactDescriptor.FORMAT) == null) && srcDescriptors[j].getProperty(IArtifactDescriptor.FORMAT).equals(IArtifactDescriptor.FORMAT_PACKED)) { //if we have a packed artifact - IArtifactDescriptor newDescriptor = new ArtifactDescriptor(keys[i]); + IArtifactDescriptor newDescriptor = new ArtifactDescriptor(key); Map properties = new OrderedProperties(); properties.putAll(srcDescriptors[j].getProperties()); properties.remove(IArtifactDescriptor.FORMAT); @@ -960,7 +930,7 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { fail("27.2", e); } //corresponding key should now be in the destination - IArtifactDescriptor[] destDescriptors = destinationRepo.getArtifactDescriptors(keys[i]); + IArtifactDescriptor[] destDescriptors = destinationRepo.getArtifactDescriptors(key); boolean canonicalFound = false; for (int l = 0; !canonicalFound && (l < destDescriptors.length); l++) { //No processing steps mean item is canonical @@ -968,7 +938,7 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { canonicalFound = true; } if (!canonicalFound) - fail("27.3 no canonical found for " + keys[i].toString()); + fail("27.3 no canonical found for " + key.toString()); //ensure the canonical matches that in the expected assertFileSizes("27.3", (SimpleArtifactRepository) destinationRepo, (SimpleArtifactRepository) packedRepo); @@ -1102,7 +1072,7 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { assertContains("3", getArtifactRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("4", getArtifactRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("5", getArtifactRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).getArtifactKeys().length + getArtifactRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).getArtifactKeys().length, getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null).getArtifactKeys().length); + assertEquals("5", getArtifactKeyCount(sourceRepoLocation.toURI()) + getArtifactKeyCount(sourceRepo2Location.toURI()), getArtifactKeyCount(destRepoLocation.toURI())); } catch (ProvisionException e) { fail("Could not load destination", e); } @@ -1127,18 +1097,14 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { System.setErr(oldErr); newErr.close(); - try { - assertEquals("Verifying correct number of Keys", 1, getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null).getArtifactKeys().length); - //Because only 1 of the artifacts exists on disk, the number of artifacts in the destination should only be 1. - //Order in which mirror application mirrors artifacts is random. - } catch (ProvisionException e) { - fail("Error laoding destiantion repo", e); - } + assertEquals("Verifying correct number of Keys", 1, getArtifactKeyCount(destRepoLocation.toURI())); + //Because only 1 of the artifacts exists on disk, the number of artifacts in the destination should only be 1. + //Order in which mirror application mirrors artifacts is random. } public void testCompareUsingMD5Comparator() { //Setup create descriptors with different md5 values - IArtifactKey dupKey = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey dupKey = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); File artifact1 = getTestData("0.0", "/testData/mirror/mirrorSourceRepo1 with space/artifacts.xml"); File artifact2 = getTestData("0.0", "/testData/mirror/mirrorSourceRepo2/artifacts.xml"); IArtifactDescriptor descriptor1 = PublisherHelper.createArtifactDescriptor(dupKey, artifact1); @@ -1176,7 +1142,7 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { System.setOut(newOut); try { //Set compare flag. - String[] args = new String[] {"-source", repo1Location.toURL().toExternalForm(), "-destination", repo2Location.toURL().toExternalForm(), "-verbose", "-compare"}; + String[] args = new String[] {"-source", repo1Location.toURL().toExternalForm(), "-destination", repo2Location.toURL().toExternalForm(), "-verbose", "-compare", "-comparator", MD5ArtifactComparator.MD5_COMPARATOR_ID}; //run the mirror application runMirrorApplication("Running with duplicate descriptors with different md5 values", args); } catch (Exception e) { @@ -1200,7 +1166,7 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { public void testBaselineCompareUsingMD5Comparator() { //Setup create descriptors with different md5 values - IArtifactKey dupKey = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey dupKey = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); File artifact1 = getTestData("0.0", "/testData/mirror/mirrorSourceRepo1 with space/content.xml"); File artifact2 = getTestData("0.0", "/testData/mirror/mirrorSourceRepo2/content.xml"); @@ -1246,7 +1212,7 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { System.setOut(newOut); try { //Set compareAgaist - String[] args = new String[] {"-source", repoLocation.toURL().toExternalForm(), "-destination", destRepoLocation.toURL().toExternalForm(), "-compareAgainst", baselineLocation.toURL().toExternalForm(), "-verbose", "-compare"}; + String[] args = new String[] {"-source", repoLocation.toURL().toExternalForm(), "-destination", destRepoLocation.toURL().toExternalForm(), "-compareAgainst", baselineLocation.toURL().toExternalForm(), "-verbose", "-compare", "-comparator", MD5ArtifactComparator.MD5_COMPARATOR_ID}; //run the mirror application runMirrorApplication("Running with baseline compare", args); } catch (Exception e) { @@ -1294,10 +1260,6 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { manager.removeRepository(srcLocation); } - public synchronized IArtifactKey[] getArtifactKeys() { - return source.getArtifactKeys(); - } - public synchronized IArtifactDescriptor[] getArtifactDescriptors(IArtifactKey key) { return source.getArtifactDescriptors(key); } @@ -1314,6 +1276,10 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { public synchronized boolean contains(IArtifactDescriptor descriptor) { return source.contains(descriptor); } + + public synchronized IQueryResult query(IQuery query, IProgressMonitor monitor) { + return source.query(query, monitor); + } } //set up test repository @@ -1385,9 +1351,10 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { try { //Mirroring full duplicate, so any key will do. - IArtifactDescriptor[] descriptors = sourceRepository.getArtifactDescriptors(sourceRepository.getArtifactKeys()[0]); + IQueryResult descriptors = sourceRepository.descriptorQueryable().query(ArtifactDescriptorQuery.ALL_DESCRIPTORS, null); + IArtifactDescriptor descriptor = descriptors.iterator().next(); //Mirroring full duplicate, so any descriptor will do. - String message = NLS.bind(org.eclipse.equinox.internal.p2.artifact.repository.Messages.mirror_alreadyExists, descriptors[0], destRepoLocation.toURI()); + String message = NLS.bind(org.eclipse.equinox.internal.p2.artifact.repository.Messages.mirror_alreadyExists, descriptor, destRepoLocation.toURI()); assertLogDoesNotContainLine(log.getFile(), message); } catch (Exception e) { fail("Error verifying log", e); @@ -1456,9 +1423,10 @@ public class ArtifactMirrorApplicationTest extends AbstractProvisioningTest { try { //Mirroring full duplicate, so any key will do. - IArtifactDescriptor[] descriptors = sourceRepository.getArtifactDescriptors(sourceRepository.getArtifactKeys()[0]); + IQueryResult descriptors = sourceRepository.descriptorQueryable().query(ArtifactDescriptorQuery.ALL_DESCRIPTORS, null); + IArtifactDescriptor descriptor = descriptors.iterator().next(); //Mirroring full duplicate, so any descriptor will do. - String message = NLS.bind(org.eclipse.equinox.internal.p2.artifact.repository.Messages.mirror_alreadyExists, descriptors[0], destRepoLocation.toURI()); + String message = NLS.bind(org.eclipse.equinox.internal.p2.artifact.repository.Messages.mirror_alreadyExists, descriptor, destRepoLocation.toURI()); assertLogContainsLine(log.getFile(), message); } catch (Exception e) { fail("Error verifying log", e); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/ArtifactRepositoryCleanupTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/ArtifactRepositoryCleanupTest.java index eba8c9934..f95d562cf 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/ArtifactRepositoryCleanupTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/ArtifactRepositoryCleanupTest.java @@ -15,9 +15,9 @@ import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import org.eclipse.equinox.app.IApplicationContext; -import org.eclipse.equinox.internal.p2.artifact.mirror.MirrorApplication; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.internal.repository.tools.MirrorApplication; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.osgi.framework.Bundle; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/MetadataMirrorApplicationTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/MetadataMirrorApplicationTest.java index 0ff0987c7..7e46b7318 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/MetadataMirrorApplicationTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/MetadataMirrorApplicationTest.java @@ -14,18 +14,16 @@ import java.io.File; import java.net.*; import java.util.HashMap; import java.util.Map; -import org.eclipse.equinox.app.IApplicationContext; -import org.eclipse.equinox.internal.p2.metadata.mirror.MirrorApplication; import org.eclipse.equinox.internal.p2.metadata.repository.CompositeMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.internal.repository.tools.MirrorApplication; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; -import org.osgi.framework.Bundle; /** * Test API of the basic mirror application functionality's implementation. @@ -74,43 +72,11 @@ public class MetadataMirrorApplicationTest extends AbstractProvisioningTest { */ private void runMirrorApplication(String message, final String[] args) throws Exception { MirrorApplication application = new MirrorApplication(); - application.start(new IApplicationContext() { - - public void applicationRunning() { - } - - public Map getArguments() { - Map arguments = new HashMap(); - - arguments.put(IApplicationContext.APPLICATION_ARGS, args); - - return arguments; - } - - public String getBrandingApplication() { - return null; - } - - public Bundle getBrandingBundle() { - return null; - } - - public String getBrandingDescription() { - return null; - } - - public String getBrandingId() { - return null; - } - - public String getBrandingName() { - return null; - } - - public String getBrandingProperty(String key) { - return null; - } - }); + Map map = new HashMap(); + map.put("metadataOrArtifacts", "metadata"); + application.setInitializationData(null, null, map); + application.initializeFromArguments(args); + application.run(null); } /** @@ -139,14 +105,14 @@ public class MetadataMirrorApplicationTest extends AbstractProvisioningTest { } /** - * Takes 2 collectors, compares them, and returns the number of unique keys + * Takes 2 QueryResults, compares them, and returns the number of unique keys * Needed to verify that only the appropriate number of files have been transfered by the mirror application */ - private int getNumUnique(Collector c1, Collector c2) { - Object[] repo1 = c1.toCollection().toArray(); - Object[] repo2 = c2.toCollection().toArray(); + private int getNumUnique(IQueryResult c1, IQueryResult c2) { + Object[] repo1 = c1.toArray(IInstallableUnit.class); + Object[] repo2 = c2.toArray(IInstallableUnit.class); - //initialize to the size of both collectors + //initialize to the size of both query results int numKeys = repo1.length + repo2.length; for (int i = 0; i < repo1.length; i++) { @@ -396,7 +362,7 @@ public class MetadataMirrorApplicationTest extends AbstractProvisioningTest { assertContains("5.1", getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("5.2", getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("5.3", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null), getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null)), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals("5.3", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, null), getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).query(InstallableUnitQuery.ANY, null)), queryResultSize(getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, null))); } catch (ProvisionException e) { fail("5.4", e); } @@ -501,7 +467,7 @@ public class MetadataMirrorApplicationTest extends AbstractProvisioningTest { assertContains("11.1", getMetadataRepositoryManager().loadRepository(sourceRepo3Location.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("11.2", getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("11.3", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null), getMetadataRepositoryManager().loadRepository(sourceRepo3Location.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null)), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals("11.3", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).query(InstallableUnitQuery.ANY, null), getMetadataRepositoryManager().loadRepository(sourceRepo3Location.toURI(), null).query(InstallableUnitQuery.ANY, null)), queryResultSize(getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, null))); } catch (ProvisionException e) { fail("11.4", e); } @@ -686,7 +652,7 @@ public class MetadataMirrorApplicationTest extends AbstractProvisioningTest { assertContains("20.2", getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("20.3", getMetadataRepositoryManager().loadRepository(sourceRepo4Location.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("20.4", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null), getMetadataRepositoryManager().loadRepository(sourceRepo4Location.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null)), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals("20.4", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, null), getMetadataRepositoryManager().loadRepository(sourceRepo4Location.toURI(), null).query(InstallableUnitQuery.ANY, null)), queryResultSize(getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, null))); } catch (ProvisionException e) { fail("20.5", e); } @@ -704,7 +670,7 @@ public class MetadataMirrorApplicationTest extends AbstractProvisioningTest { runMirrorApplication("21.1", args); //We expect the IllegalStateException to be thrown fail("21.3 IllegalStateException not thrown"); - } catch (IllegalStateException e) { + } catch (IllegalArgumentException e) { return; //expected type of exception has been thrown } catch (Exception e) { fail("21.2", e); @@ -723,7 +689,7 @@ public class MetadataMirrorApplicationTest extends AbstractProvisioningTest { runMirrorApplication("22.1", args); //We expect the IllegalStateException to be thrown fail("22.3 IllegalStateException not thrown"); - } catch (IllegalStateException e) { + } catch (ProvisionException e) { return; //expected type of exception has been thrown } catch (Exception e) { fail("22.2", e); @@ -741,7 +707,7 @@ public class MetadataMirrorApplicationTest extends AbstractProvisioningTest { runMirrorApplication("23.0", args); //We expect the IllegalStateException to be thrown fail("23.2 IllegalStateException not thrown"); - } catch (IllegalStateException e) { + } catch (IllegalArgumentException e) { return; //expected type of exception has been thrown } catch (Exception e) { fail("23.1", e); @@ -972,7 +938,7 @@ public class MetadataMirrorApplicationTest extends AbstractProvisioningTest { assertContains("3", getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("4", getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("5", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null), getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null)), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals("5", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, null), getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).query(InstallableUnitQuery.ANY, null)), queryResultSize(getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, null))); } catch (ProvisionException e) { fail("Could not load destination", e); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/MetadataRepositoryCleanupTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/MetadataRepositoryCleanupTest.java index 7faef2d4f..41a7d73cb 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/MetadataRepositoryCleanupTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/MetadataRepositoryCleanupTest.java @@ -15,9 +15,9 @@ import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import org.eclipse.equinox.app.IApplicationContext; -import org.eclipse.equinox.internal.p2.artifact.mirror.MirrorApplication; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.internal.repository.tools.MirrorApplication; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.osgi.framework.Bundle; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/NewMirrorApplicationArtifactTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/NewMirrorApplicationArtifactTest.java index 867a05f44..e3a9f4bde 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/NewMirrorApplicationArtifactTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/NewMirrorApplicationArtifactTest.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.mirror; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.*; import java.net.MalformedURLException; @@ -22,12 +22,15 @@ import org.eclipse.equinox.internal.p2.artifact.repository.*; import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository; import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.ProvisionException; import org.eclipse.equinox.p2.internal.repository.tools.MirrorApplication; import org.eclipse.equinox.p2.internal.repository.tools.RepositoryDescriptor; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; @@ -311,15 +314,15 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { * Not Biconditional. */ private void assertFileSizes(String message, SimpleArtifactRepository expected, SimpleArtifactRepository actual) { - IArtifactKey[] expectedKeys = expected.getArtifactKeys(); - - for (int i = 0; i < expectedKeys.length; i++) { - IArtifactDescriptor[] expectedDescriptors = expected.getArtifactDescriptors(expectedKeys[i]); - IArtifactDescriptor[] actualDescriptors = actual.getArtifactDescriptors(expectedKeys[i]); + IQueryResult expectedKeys = expected.query(ArtifactKeyQuery.ALL_KEYS, null); + for (Iterator iterator = expectedKeys.iterator(); iterator.hasNext();) { + IArtifactKey key = (IArtifactKey) iterator.next(); + IArtifactDescriptor[] expectedDescriptors = expected.getArtifactDescriptors(key); + IArtifactDescriptor[] actualDescriptors = actual.getArtifactDescriptors(key); if (expectedDescriptors == null || actualDescriptors == null) if (!(expectedDescriptors == null && actualDescriptors == null)) - fail(message + " missing key " + expectedKeys[i]); + fail(message + " missing key " + key); top: for (int j = 0; j < expectedDescriptors.length; j++) { for (int k = 0; k < actualDescriptors.length; k++) { @@ -421,7 +424,7 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { assertContains("5.1", getArtifactRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("5.2", getArtifactRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("5.3", getArtifactRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).getArtifactKeys().length + getArtifactRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).getArtifactKeys().length, getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null).getArtifactKeys().length); + assertEquals("5.3", getArtifactKeyCount(sourceRepoLocation.toURI()) + getArtifactKeyCount(sourceRepo2Location.toURI()), getArtifactKeyCount(destRepoLocation.toURI())); } catch (ProvisionException e) { fail("5.4", e); } @@ -526,7 +529,7 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { assertContains("11.1", getArtifactRepositoryManager().loadRepository(sourceRepo3Location.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("11.2", getArtifactRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("11.3", getArtifactRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).getArtifactKeys().length + getArtifactRepositoryManager().loadRepository(sourceRepo3Location.toURI(), null).getArtifactKeys().length, getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null).getArtifactKeys().length); + assertEquals("11.3", getArtifactKeyCount(sourceRepo2Location.toURI()) + getArtifactKeyCount(sourceRepo3Location.toURI()), getArtifactKeyCount(destRepoLocation.toURI())); } catch (ProvisionException e) { fail("11.4", e); } @@ -719,7 +722,7 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { assertContains("20.2", getArtifactRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("20.3", getArtifactRepositoryManager().loadRepository(sourceRepo4Location.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("20.4", getArtifactRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).getArtifactKeys().length + getArtifactRepositoryManager().loadRepository(sourceRepo4Location.toURI(), null).getArtifactKeys().length, getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null).getArtifactKeys().length); + assertEquals("20.4", getArtifactKeyCount(sourceRepoLocation.toURI()) + getArtifactKeyCount(sourceRepo4Location.toURI()), getArtifactKeyCount(destRepoLocation.toURI())); } catch (ProvisionException e) { fail("20.5", e); } @@ -907,15 +910,15 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { fail(""); } - IArtifactKey[] keys = packedRepo.getArtifactKeys(); - - for (int i = 0; i < keys.length; i++) { - IArtifactDescriptor[] srcDescriptors = packedRepo.getArtifactDescriptors(keys[i]); + IQueryResult keys = packedRepo.query(ArtifactKeyQuery.ALL_KEYS, null); + for (Iterator iterator = keys.iterator(); iterator.hasNext();) { + IArtifactKey key = (IArtifactKey) iterator.next(); + IArtifactDescriptor[] srcDescriptors = packedRepo.getArtifactDescriptors(key); for (int j = 0; j < srcDescriptors.length; j++) { - if (!(srcDescriptors[j].getProperty(IArtifactDescriptor.FORMAT) == null) && srcDescriptors[j].getProperty(IArtifactDescriptor.FORMAT).equals("packed")) { + if (!(srcDescriptors[j].getProperty(IArtifactDescriptor.FORMAT) == null) && srcDescriptors[j].getProperty(IArtifactDescriptor.FORMAT).equals(IArtifactDescriptor.FORMAT_PACKED)) { //if we have a packed artifact - IArtifactDescriptor newDescriptor = new ArtifactDescriptor(keys[i]); + IArtifactDescriptor newDescriptor = new ArtifactDescriptor(key); Map properties = new OrderedProperties(); properties.putAll(srcDescriptors[j].getProperties()); properties.remove(IArtifactDescriptor.FORMAT); @@ -941,7 +944,7 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { fail("27.2", e); } //corresponding key should now be in the destination - IArtifactDescriptor[] destDescriptors = destinationRepo.getArtifactDescriptors(keys[i]); + IArtifactDescriptor[] destDescriptors = destinationRepo.getArtifactDescriptors(key); boolean canonicalFound = false; for (int l = 0; !canonicalFound && (l < destDescriptors.length); l++) { //No processing steps mean item is canonical @@ -949,7 +952,7 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { canonicalFound = true; } if (!canonicalFound) - fail("27.3 no canonical found for " + keys[i].toString()); + fail("27.3 no canonical found for " + key.toString()); //ensure the canonical matches that in the expected assertFileSizes("27.3", (SimpleArtifactRepository) destinationRepo, (SimpleArtifactRepository) packedRepo); @@ -1083,7 +1086,7 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { assertContains("3", getArtifactRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("4", getArtifactRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null), getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("5", getArtifactRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).getArtifactKeys().length + getArtifactRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).getArtifactKeys().length, getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null).getArtifactKeys().length); + assertEquals("5", getArtifactKeyCount(sourceRepoLocation.toURI()) + getArtifactKeyCount(sourceRepo2Location.toURI()), getArtifactKeyCount(destRepoLocation.toURI())); } catch (ProvisionException e) { fail("Could not load destination", e); } @@ -1111,19 +1114,15 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { if (newErr != null) newErr.close(); } - try { - assertEquals("Verifying correct number of Keys", 2, getArtifactRepositoryManager().loadRepository(destRepoLocation.toURI(), null).getArtifactKeys().length); - //Because only 2 of the artifacts exists on disk, the number of artifacts in the destination should only be 1. - //Order in which mirror application mirrors artifacts is random. - } catch (ProvisionException e) { - fail("Error laoding destiantion repo", e); - } + assertEquals("Verifying correct number of Keys", 2, getArtifactKeyCount(destRepoLocation.toURI())); + //Because only 2 of the artifacts exists on disk, the number of artifacts in the destination should only be 1. + //Order in which mirror application mirrors artifacts is random. } public void testCompareUsingMD5Comparator() { //Setup create descriptors with different md5 values - IArtifactKey dupKey = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey dupKey = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); File artifact1 = getTestData("0.0", "/testData/mirror/mirrorSourceRepo1 with space/artifacts.xml"); File artifact2 = getTestData("0.0", "/testData/mirror/mirrorSourceRepo2/artifacts.xml"); IArtifactDescriptor descriptor1 = PublisherHelper.createArtifactDescriptor(dupKey, artifact1); @@ -1195,7 +1194,7 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { public void testBaselineCompareUsingMD5Comparator() { //Setup create descriptors with different md5 values - IArtifactKey dupKey = PublisherHelper.createBinaryArtifactKey("testKeyId", new Version("1.2.3")); + IArtifactKey dupKey = PublisherHelper.createBinaryArtifactKey("testKeyId", Version.create("1.2.3")); File artifact1 = getTestData("0.0", "/testData/mirror/mirrorSourceRepo1 with space/content.xml"); File artifact2 = getTestData("0.0", "/testData/mirror/mirrorSourceRepo2/content.xml"); @@ -1301,10 +1300,6 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { manager.removeRepository(srcLocation); } - public synchronized IArtifactKey[] getArtifactKeys() { - return source.getArtifactKeys(); - } - public synchronized IArtifactDescriptor[] getArtifactDescriptors(IArtifactKey key) { return source.getArtifactDescriptors(key); } @@ -1321,6 +1316,10 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { public synchronized boolean contains(IArtifactDescriptor descriptor) { return source.contains(descriptor); } + + public synchronized IQueryResult query(IQuery query, IProgressMonitor monitor) { + return source.query(query, monitor); + } } //set up test repository @@ -1392,9 +1391,10 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { try { //Mirroring full duplicate, so any key will do. - IArtifactDescriptor[] descriptors = sourceRepository.getArtifactDescriptors(sourceRepository.getArtifactKeys()[0]); + IQueryResult descriptors = sourceRepository.descriptorQueryable().query(ArtifactDescriptorQuery.ALL_DESCRIPTORS, null); + IArtifactDescriptor descriptor = descriptors.iterator().next(); //Mirroring full duplicate, so any descriptor will do. - String message = NLS.bind(org.eclipse.equinox.internal.p2.artifact.repository.Messages.mirror_alreadyExists, descriptors[0], destRepoLocation.toURI()); + String message = NLS.bind(org.eclipse.equinox.internal.p2.artifact.repository.Messages.mirror_alreadyExists, descriptor, destRepoLocation.toURI()); assertLogDoesNotContainLine(log.getFile(), message); } catch (Exception e) { fail("Error verifying log", e); @@ -1469,9 +1469,10 @@ public class NewMirrorApplicationArtifactTest extends AbstractProvisioningTest { try { //Mirroring full duplicate, so any key will do. - IArtifactDescriptor[] descriptors = sourceRepository.getArtifactDescriptors(sourceRepository.getArtifactKeys()[0]); + IQueryResult descriptors = sourceRepository.descriptorQueryable().query(ArtifactDescriptorQuery.ALL_DESCRIPTORS, null); + IArtifactDescriptor descriptor = descriptors.iterator().next(); //Mirroring full duplicate, so any descriptor will do. - String message = NLS.bind(org.eclipse.equinox.internal.p2.artifact.repository.Messages.mirror_alreadyExists, descriptors[0], destRepoLocation.toURI()); + String message = NLS.bind(org.eclipse.equinox.internal.p2.artifact.repository.Messages.mirror_alreadyExists, descriptor, destRepoLocation.toURI()); assertLogContainsLine(log.getFile(), message); } catch (Exception e) { fail("Error verifying log", e); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/NewMirrorApplicationMetadataTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/NewMirrorApplicationMetadataTest.java index 69957d0cc..8baac04e3 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/NewMirrorApplicationMetadataTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/mirror/NewMirrorApplicationMetadataTest.java @@ -15,16 +15,16 @@ import java.net.*; import java.util.HashMap; import java.util.Map; import org.eclipse.equinox.internal.p2.metadata.repository.CompositeMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; import org.eclipse.equinox.internal.simpleconfigurator.utils.URIUtil; +import org.eclipse.equinox.p2.core.ProvisionException; import org.eclipse.equinox.p2.internal.repository.tools.MirrorApplication; import org.eclipse.equinox.p2.internal.repository.tools.RepositoryDescriptor; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.osgi.util.NLS; @@ -132,14 +132,14 @@ public class NewMirrorApplicationMetadataTest extends AbstractProvisioningTest { } /** - * Takes 2 collectors, compares them, and returns the number of unique keys + * Takes 2 QueryResults, compares them, and returns the number of unique keys * Needed to verify that only the appropriate number of files have been transfered by the mirror application */ - private int getNumUnique(Collector c1, Collector c2) { - Object[] repo1 = c1.toCollection().toArray(); - Object[] repo2 = c2.toCollection().toArray(); + private int getNumUnique(IQueryResult c1, IQueryResult c2) { + Object[] repo1 = c1.toArray(IInstallableUnit.class); + Object[] repo2 = c2.toArray(IInstallableUnit.class); - //initialize to the size of both collectors + //initialize to the size of both QueryResults int numKeys = repo1.length + repo2.length; for (int i = 0; i < repo1.length; i++) { @@ -394,7 +394,7 @@ public class NewMirrorApplicationMetadataTest extends AbstractProvisioningTest { assertContains("5.1", getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("5.2", getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("5.3", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null), getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null)), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals("5.3", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, null), getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).query(InstallableUnitQuery.ANY, null)), queryResultSize(getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, null))); } catch (ProvisionException e) { fail("5.4", e); } @@ -499,7 +499,7 @@ public class NewMirrorApplicationMetadataTest extends AbstractProvisioningTest { assertContains("11.1", getMetadataRepositoryManager().loadRepository(sourceRepo3Location.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("11.2", getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("11.3", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null), getMetadataRepositoryManager().loadRepository(sourceRepo3Location.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null)), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals("11.3", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).query(InstallableUnitQuery.ANY, null), getMetadataRepositoryManager().loadRepository(sourceRepo3Location.toURI(), null).query(InstallableUnitQuery.ANY, null)), queryResultSize(getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, null))); } catch (ProvisionException e) { fail("11.4", e); } @@ -704,7 +704,7 @@ public class NewMirrorApplicationMetadataTest extends AbstractProvisioningTest { assertContains("20.2", getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("20.3", getMetadataRepositoryManager().loadRepository(sourceRepo4Location.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("20.4", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null), getMetadataRepositoryManager().loadRepository(sourceRepo4Location.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null)), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals("20.4", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, null), getMetadataRepositoryManager().loadRepository(sourceRepo4Location.toURI(), null).query(InstallableUnitQuery.ANY, null)), queryResultSize(getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, null))); } catch (ProvisionException e) { fail("20.5", e); } @@ -959,7 +959,7 @@ public class NewMirrorApplicationMetadataTest extends AbstractProvisioningTest { assertContains("3", getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); assertContains("4", getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null)); //checks that the destination has the correct number of keys (no extras) - assertEquals("5", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null), getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null)), getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals("5", getNumUnique(getMetadataRepositoryManager().loadRepository(sourceRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, null), getMetadataRepositoryManager().loadRepository(sourceRepo2Location.toURI(), null).query(InstallableUnitQuery.ANY, null)), queryResultSize(getMetadataRepositoryManager().loadRepository(destRepoLocation.toURI(), null).query(InstallableUnitQuery.ANY, null))); } catch (ProvisionException e) { fail("Could not load destination", e); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/CommonPatternsTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/CommonPatternsTest.java index c3867942e..a824495f8 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/CommonPatternsTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/CommonPatternsTest.java @@ -11,7 +11,8 @@ package org.eclipse.equinox.p2.tests.omniVersion; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.IVersionFormat; +import org.eclipse.equinox.p2.metadata.Version; /** * Test common patterns: @@ -22,8 +23,9 @@ import org.eclipse.equinox.internal.provisional.p2.metadata.Version; * */ public class CommonPatternsTest extends VersionTesting { + public static String TRIPLET_FORMAT_STRING = "n=0;[.n=0;[.n=0;]][dS=m;]"; public static String MOZ_PREFIX = "format(((.)*)=p<0.m.0.m>;):"; - public static String TRIPLE_PREFIX = "format(n=0;[.n=0;[.n=0;]][dS=m;]):"; + public static String TRIPLE_PREFIX = "format(" + TRIPLET_FORMAT_STRING + "):"; public static String RPM_PREFIX = "format(<[n=0;:]a(d=[^a-zA-Z0-9@_-];?a)*>[-n[dS=!;]]):"; public static String JSR277_PREFIX = "format(n(.n=0;){0,3}[-S=m;]):"; @@ -142,6 +144,26 @@ public class CommonPatternsTest extends VersionTesting { assertEquals(TRIPLE_PREFIX, Version.parseVersion(test).getFormat().toString() + ':'); } + public void testTripletPatternToOSGi() throws Exception { + IVersionFormat triplet = Version.compile(TRIPLET_FORMAT_STRING); + assertEquals(Version.createOSGi(1, 0, 0), triplet.parse("1.0.0." + IVersionFormat.DEFAULT_MIN_STRING_TRANSLATION)); + assertEquals(Version.create("1.0.0." + IVersionFormat.DEFAULT_MAX_STRING_TRANSLATION), triplet.parse("1.0.0")); + assertEquals(Version.createOSGi(1, 0, 0, IVersionFormat.DEFAULT_MAX_STRING_TRANSLATION), Version.create("raw:1.0.0.m")); + assertEquals(triplet.parse("1.0"), Version.create("raw:1.0.0.m")); + assertEquals(triplet.parse("1.0." + IVersionFormat.DEFAULT_MIN_STRING_TRANSLATION), Version.create("raw:1.0.0.''")); + assertEquals(Version.createOSGi(1, 0, 0), Version.create("raw:1.0.0.''")); + } + + public void testMinTranslation() throws Exception { + IVersionFormat format = Version.compile("n=0;[.n=0;[.n=0;]][dS=m{!};]"); + assertEquals(Version.create("raw:1.0.0.''"), format.parse("1.0.0.!")); + } + + public void testMaxTranslation() throws Exception { + IVersionFormat format = Version.compile("n=0;[.n=0;[.n=0;]][dS=''{~,4};]"); + assertEquals(Version.create("raw:1.0.0.m"), format.parse("1.0.0.~~~~")); + } + // TODO: Not clear what a missing RPM EPOCH (i.e. first '.n:' should be interpreted as public void testRPMPattern() { Version v1 = Version.parseVersion(RPM_PREFIX + "33:1.2.3a-23/i386"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatATest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatATest.java index c439e9ecd..f7d4d0d74 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatATest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatATest.java @@ -11,8 +11,9 @@ package org.eclipse.equinox.p2.tests.omniVersion; +import org.eclipse.equinox.p2.metadata.Version; + import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; /** * Tests the format(a) rule. diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatArrayTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatArrayTest.java index 62be84716..5a2afa83b 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatArrayTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatArrayTest.java @@ -11,8 +11,9 @@ package org.eclipse.equinox.p2.tests.omniVersion; +import org.eclipse.equinox.p2.metadata.Version; + import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; /** * Tests format(<>) - arrays. diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatDTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatDTest.java index 66e9de920..566bf1b95 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatDTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatDTest.java @@ -11,8 +11,9 @@ package org.eclipse.equinox.p2.tests.omniVersion; +import org.eclipse.equinox.p2.metadata.Version; + import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; /** * Tests format(d) and explicit delimiter chars and strings. diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatNTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatNTest.java index 5065e0b19..9a67544e7 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatNTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatNTest.java @@ -11,8 +11,9 @@ package org.eclipse.equinox.p2.tests.omniVersion; +import org.eclipse.equinox.p2.metadata.Version; + import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; /** * Tests format(n) and format(N) diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatPTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatPTest.java index f163d8482..143f623b7 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatPTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatPTest.java @@ -11,8 +11,9 @@ package org.eclipse.equinox.p2.tests.omniVersion; +import org.eclipse.equinox.p2.metadata.Version; + import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; public class FormatPTest extends TestCase { public void testPad() { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatProcessingTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatProcessingTest.java index d7acc52a0..69baf16ca 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatProcessingTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatProcessingTest.java @@ -11,8 +11,9 @@ package org.eclipse.equinox.p2.tests.omniVersion; +import org.eclipse.equinox.p2.metadata.Version; + import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; /** * Tests processing rules not tested elsewhere, and combinations of processing rules. diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatQTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatQTest.java index 19c8a4430..dc771aae2 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatQTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatQTest.java @@ -11,8 +11,9 @@ package org.eclipse.equinox.p2.tests.omniVersion; +import org.eclipse.equinox.p2.metadata.Version; + import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; /** * Tests format(q) diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatRTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatRTest.java index 68397a716..38983b5a4 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatRTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatRTest.java @@ -11,8 +11,9 @@ package org.eclipse.equinox.p2.tests.omniVersion; +import org.eclipse.equinox.p2.metadata.Version; + import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; /** * Tests format(r) diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatRangeTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatRangeTest.java index 9ebc1ef75..d141dfd56 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatRangeTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatRangeTest.java @@ -11,8 +11,8 @@ package org.eclipse.equinox.p2.tests.omniVersion; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; /** * Tests ranges using format(xxx) version strings. @@ -66,7 +66,7 @@ public class FormatRangeTest extends VersionTesting { } public void testGreaterThanMinimum() { - // any version equal or greater than Version.MIN_VERSION is ok + // any version equal or greater than Version.emptyVersion is ok VersionRange lowerBound = new VersionRange("raw:-M"); assertIncludedInRange("0.1", lowerBound, "raw:-M"); assertIncludedInRange("1.0", lowerBound, OSGI_PREFIX + "0.9.0"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatSTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatSTest.java index 8bfaee947..5be32493a 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatSTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatSTest.java @@ -11,8 +11,9 @@ package org.eclipse.equinox.p2.tests.omniVersion; +import org.eclipse.equinox.p2.metadata.Version; + import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; /** * Tests format(s), and format(S) diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatTest.java index 888a147c6..fa5300f06 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/FormatTest.java @@ -11,8 +11,9 @@ package org.eclipse.equinox.p2.tests.omniVersion; +import org.eclipse.equinox.p2.metadata.Version; + import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; /** * Test of format() performing tests not covered by tests per rule. diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/IntersectionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/IntersectionTest.java index 1c456af77..04f8a987e 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/IntersectionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/IntersectionTest.java @@ -11,9 +11,10 @@ package org.eclipse.equinox.p2.tests.omniVersion; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; + import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; /** * Tests intersection of VersionRanges. diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/MultiplicityTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/MultiplicityTest.java index cb122ec44..34c9079a0 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/MultiplicityTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/MultiplicityTest.java @@ -11,8 +11,9 @@ package org.eclipse.equinox.p2.tests.omniVersion; +import org.eclipse.equinox.p2.metadata.Version; + import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; /** * Tests {n.m} in different combinations and the special +?* diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/OSGiRangeTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/OSGiRangeTest.java index f064b18f6..162818d7f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/OSGiRangeTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/OSGiRangeTest.java @@ -12,8 +12,8 @@ package org.eclipse.equinox.p2.tests.omniVersion; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; /** * Tests ranges of versions specified with osgi (default) version format. @@ -50,8 +50,8 @@ public class OSGiRangeTest extends VersionTesting { assertTrue("1.1", lowerBound.isIncluded(Version.parseVersion("1.0"))); assertTrue("1.2", lowerBound.isIncluded(Version.parseVersion("1.9.9.x"))); assertTrue("1.3", lowerBound.isIncluded(Version.parseVersion("999.999.999.foo"))); - assertTrue("2.0", !lowerBound.isIncluded(Version.parseVersion("raw:M"))); - assertTrue("2.1", !lowerBound.isIncluded(Version.parseVersion("raw:2147483647.2147483647.2147483647.0"))); + assertTrue("2.0", lowerBound.isIncluded(Version.parseVersion("raw:M"))); + assertTrue("2.1", lowerBound.isIncluded(Version.parseVersion("raw:2147483647.2147483647.2147483647.0"))); } @@ -94,16 +94,16 @@ public class OSGiRangeTest extends VersionTesting { /** * Tests that null values passed to the {@link VersionRange} constructor - * are interpreted as OSGi ranges. + * are not interpreted as MIN/MAX versions. */ public void testNullConstructor() { VersionRange range = new VersionRange(null); - assertEquals("1.0", range.getMinimum(), new Version(0, 0, 0)); - assertEquals("1.1", range.getMaximum(), new Version(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE)); + assertEquals("1.0", range.getMinimum(), Version.emptyVersion); + assertEquals("1.1", range.getMaximum(), Version.MAX_VERSION); range = new VersionRange(null, true, null, true); - assertEquals("2.0", range.getMinimum(), new Version(0, 0, 0)); - assertEquals("2.1", range.getMaximum(), new Version(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE)); + assertEquals("2.0", range.getMinimum(), Version.emptyVersion); + assertEquals("2.1", range.getMaximum(), Version.MAX_VERSION); } public void testSerialize() { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/OSGiVersionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/OSGiVersionTest.java index 608ae3885..d9ff27595 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/OSGiVersionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/OSGiVersionTest.java @@ -11,7 +11,7 @@ package org.eclipse.equinox.p2.tests.omniVersion; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; /** * Tests versions specified with default OSGi version strings and tests OSGi compatibility @@ -33,7 +33,7 @@ public class OSGiVersionTest extends VersionTesting { public void testOSGiStrings() { - Version v = new Version(""); + Version v = Version.parseVersion(null); assertEquals("0.0.0", v.toString()); assertNotNull(v = Version.parseVersion("")); assertEquals("0.0.0", v.toString()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/PerformanceTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/PerformanceTest.java index 605bfa70d..5f7061aa8 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/PerformanceTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/PerformanceTest.java @@ -11,8 +11,9 @@ package org.eclipse.equinox.p2.tests.omniVersion; +import org.eclipse.equinox.p2.metadata.Version; + import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; /** * Simple performance comparison between OSGi version implementation and Omni Version. @@ -30,7 +31,7 @@ public class PerformanceTest extends TestCase { public void testStringCreationPerformance() { // Ensure that classes are loaded etc. - Version.MAX_VERSION.compareTo(Version.MIN_VERSION); + Version.MAX_VERSION.compareTo(Version.emptyVersion); org.osgi.framework.Version.emptyVersion.compareTo(org.osgi.framework.Version.emptyVersion); // Create all versions in string format @@ -51,7 +52,7 @@ public class PerformanceTest extends TestCase { public void testCreationPerformance() { // Ensure that classes are loaded etc. - Version.MAX_VERSION.compareTo(Version.MIN_VERSION); + Version.MAX_VERSION.compareTo(Version.emptyVersion); org.osgi.framework.Version.emptyVersion.compareTo(org.osgi.framework.Version.emptyVersion); long start = System.currentTimeMillis(); @@ -137,7 +138,7 @@ public class PerformanceTest extends TestCase { for (int i = 0; i < MUL; i++) for (int j = 0; j < MUL; j++) for (int k = 0; k < MUL; k++) - new Version(i, j, k, qualifierTemplate); + Version.createOSGi(i, j, k, qualifierTemplate); } public static void omniVersionCompare(Version versions[]) { @@ -159,7 +160,7 @@ public class PerformanceTest extends TestCase { for (int i = 0; i < MUL; i++) for (int j = 0; j < MUL; j++) for (int k = 0; k < MUL; k++) - Version.parseVersion(strings[x++]); + Version.create(strings[x++]); } public static void osgiVersionCompare(org.osgi.framework.Version versions[]) { @@ -201,7 +202,7 @@ public class PerformanceTest extends TestCase { for (int i = 0; i < MUL; i++) for (int j = 0; j < MUL; j++) for (int k = 0; k < MUL; k++) - versions[x++] = new Version(i, j, k, qualifierTemplate.substring(0, k + 1)); + versions[x++] = Version.createOSGi(i, j, k, qualifierTemplate.substring(0, k + 1)); return versions; } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawRangeTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawRangeTest.java index 3b637d812..eae2a6146 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawRangeTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawRangeTest.java @@ -11,8 +11,8 @@ package org.eclipse.equinox.p2.tests.omniVersion; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; /** * Tests version ranges specified using raw. diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawRangeWithOriginalTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawRangeWithOriginalTest.java index ab3034425..b2315f6d9 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawRangeWithOriginalTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawRangeWithOriginalTest.java @@ -11,8 +11,10 @@ package org.eclipse.equinox.p2.tests.omniVersion; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; + +import org.eclipse.equinox.internal.p2.metadata.VersionFormat; /** * Tests inclusion of original version range string in raw format. @@ -46,6 +48,11 @@ public class RawRangeWithOriginalTest extends VersionTesting { assertEquals("raw:[1.0,2.0]/format(n.n):1.0,2.0", new VersionRange("raw:[1.0,2.0]/format(n.n):[1.0,2.0]").toString()); } + public void testSimpleFormatToString() { + // range brackets are normalized in toString - not needed in original + assertEquals("raw:[1.0,2.0]/format(n.n):1.0,2.0", new VersionRange("format(n.n):[1.0,2.0]").toString()); + } + public void testRawWithSimpleFormatSerialized() { assertSerialized(new VersionRange("raw:[1.0,2.0]/format(n.n):[1.0,2.0]")); // range brackets are normalized in toString - not needed in original @@ -163,7 +170,7 @@ public class RawRangeWithOriginalTest extends VersionTesting { } public void testOSGiMinBoundary() { - String rangeString = "raw:[-M,2.1.0]/format(n[.n=0;[.n=0;[.S=[A-Za-z0-9_-];]]]):-M,2.1.0"; + String rangeString = "raw:[-M,2.1.0.'']/format(" + VersionFormat.OSGI_FORMAT_STRING + "):-M,2.1.0"; VersionRange range = new VersionRange(rangeString); VersionRange range1 = new VersionRange("[0.0.0,2.1.0]"); @@ -188,7 +195,7 @@ public class RawRangeWithOriginalTest extends VersionTesting { } public void testRecreateUsingMaxUpper() { - Version v = new Version("format(n[.n=0;[.n=0;]][d?S=M;]):2.1"); + Version v = Version.create("format(n[.n=0;[.n=0;]][d?S=M;]):2.1"); VersionRange range = new VersionRange(v, true, null, true); Version min = range.getMinimum(); Version max = range.getMaximum(); @@ -197,7 +204,7 @@ public class RawRangeWithOriginalTest extends VersionTesting { } public void testRecreateUsingMinLower() { - Version v = new Version("format(n[.n=0;[.n=0;]][d?S=M;]):2.1"); + Version v = Version.create("format(n[.n=0;[.n=0;]][d?S=M;]):2.1"); VersionRange range = new VersionRange(null, true, v, true); Version min = range.getMinimum(); Version max = range.getMaximum(); @@ -206,7 +213,7 @@ public class RawRangeWithOriginalTest extends VersionTesting { } public void testOSGiMaxBoundary() { - String rangeString = "raw:[2.1.0,MpM]/format(n[.n=0;[.n=0;[.S=[A-Za-z0-9_-];]]]):2.1.0,MpM"; + String rangeString = "raw:[2.1.0.'',MpM]/format(" + VersionFormat.OSGI_FORMAT_STRING + "):2.1.0,MpM"; VersionRange range = new VersionRange(rangeString); VersionRange range1 = new VersionRange("2.1.0"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawVersionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawVersionTest.java index ec5b5cc86..e1c80bb03 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawVersionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawVersionTest.java @@ -11,8 +11,9 @@ package org.eclipse.equinox.p2.tests.omniVersion; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionVector; +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.internal.p2.metadata.VersionVector; /** * Tests the OmniVersion raw version format. @@ -23,84 +24,84 @@ public class RawVersionTest extends VersionTesting { public void testBasicParsing() { // should parse without exception - assertNotNull(Version.parseVersion("raw:1")); - assertNotNull(Version.parseVersion("raw:1.0")); - assertNotNull(Version.parseVersion("raw:1.0.0")); - assertNotNull(Version.parseVersion("raw:1.0.0.9")); - assertNotNull(Version.parseVersion("raw:1.0.0.'r12345'")); - assertNotNull(Version.parseVersion("raw:1.0.0.'r12345.hello'")); + assertNotNull(Version.create("raw:1")); + assertNotNull(Version.create("raw:1.0")); + assertNotNull(Version.create("raw:1.0.0")); + assertNotNull(Version.create("raw:1.0.0.9")); + assertNotNull(Version.create("raw:1.0.0.'r12345'")); + assertNotNull(Version.create("raw:1.0.0.'r12345.hello'")); - assertNotNull(Version.parseVersion("raw:1.0.m")); - assertNotNull(Version.parseVersion("raw:1.0.M")); + assertNotNull(Version.create("raw:1.0.m")); + assertNotNull(Version.create("raw:1.0.M")); - assertNotNull(Version.parseVersion("raw:1.0.M")); - assertNotNull(Version.parseVersion("raw:1.0.-M")); + assertNotNull(Version.create("raw:1.0.M")); + assertNotNull(Version.create("raw:1.0.-M")); } public void testSerialize() { Version v = null; // should parse without exception - assertNotNull(v = Version.parseVersion("raw:1")); + assertNotNull(v = Version.create("raw:1")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0")); + assertNotNull(v = Version.create("raw:1.0")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0.0")); + assertNotNull(v = Version.create("raw:1.0.0")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0.0.9")); + assertNotNull(v = Version.create("raw:1.0.0.9")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0.0.'r12345'")); + assertNotNull(v = Version.create("raw:1.0.0.'r12345'")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0.0.'r12345.hello'")); + assertNotNull(v = Version.create("raw:1.0.0.'r12345.hello'")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0.m")); + assertNotNull(v = Version.create("raw:1.0.m")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0.M")); + assertNotNull(v = Version.create("raw:1.0.M")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0.M")); + assertNotNull(v = Version.create("raw:1.0.M")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0.-M")); + assertNotNull(v = Version.create("raw:1.0.-M")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:0")); + assertNotNull(v = Version.create("raw:0")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:0.1.2.3.4.5.6.7.8.9")); + assertNotNull(v = Version.create("raw:0.1.2.3.4.5.6.7.8.9")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:0.-1.-2.-3.-4.-5.-6.-7.-8.-9")); + assertNotNull(v = Version.create("raw:0.-1.-2.-3.-4.-5.-6.-7.-8.-9")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:123456789.-1234567890")); + assertNotNull(v = Version.create("raw:123456789.-1234567890")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:123456789.-1234567890")); + assertNotNull(v = Version.create("raw:123456789.-1234567890")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:m")); + assertNotNull(v = Version.create("raw:m")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:M")); + assertNotNull(v = Version.create("raw:M")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:-M")); + assertNotNull(v = Version.create("raw:-M")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.m")); + assertNotNull(v = Version.create("raw:1.m")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.M")); + assertNotNull(v = Version.create("raw:1.M")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.-M")); + assertNotNull(v = Version.create("raw:1.-M")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:'a'")); + assertNotNull(v = Version.create("raw:'a'")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:\"a\"")); + assertNotNull(v = Version.create("raw:\"a\"")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:'ab'")); + assertNotNull(v = Version.create("raw:'ab'")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:'abcdefghijklmnopqrstuvwxyz0123456789'")); + assertNotNull(v = Version.create("raw:'abcdefghijklmnopqrstuvwxyz0123456789'")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'")); + assertNotNull(v = Version.create("raw:'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:'-_!\"#$%&/()=?+*;,:.'")); + assertNotNull(v = Version.create("raw:'-_!\"#$%&/()=?+*;,:.'")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:\"'\"")); + assertNotNull(v = Version.create("raw:\"'\"")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:'\"'")); + assertNotNull(v = Version.create("raw:'\"'")); assertSerialized(v); } @@ -109,73 +110,73 @@ public class RawVersionTest extends VersionTesting { Version v = null; String s = null; // should parse without exception - assertNotNull(v = Version.parseVersion(s = "raw:1")); + assertNotNull(v = Version.create(s = "raw:1")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0")); + assertNotNull(v = Version.create(s = "raw:1.0")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0.0")); + assertNotNull(v = Version.create(s = "raw:1.0.0")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0.0.9")); + assertNotNull(v = Version.create(s = "raw:1.0.0.9")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0.0.'r12345'")); + assertNotNull(v = Version.create(s = "raw:1.0.0.'r12345'")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0.0.'r12345.hello'")); + assertNotNull(v = Version.create(s = "raw:1.0.0.'r12345.hello'")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0.m")); + assertNotNull(v = Version.create(s = "raw:1.0.m")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0.M")); + assertNotNull(v = Version.create(s = "raw:1.0.M")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0.M")); + assertNotNull(v = Version.create(s = "raw:1.0.M")); assertEquals(s, v.toString()); // -M is normalized - assertNotNull(v = Version.parseVersion("raw:1.0.-M")); + assertNotNull(v = Version.create("raw:1.0.-M")); s = "raw:1.0"; assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:0")); - assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:0.1.2.3.4.5.6.7.8.9")); + assertNotNull(v = Version.create(s = "raw:0")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:0.-1.-2.-3.-4.-5.-6.-7.-8.-9")); + assertNotNull(v = Version.create(s = "raw:0.1.2.3.4.5.6.7.8.9")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:123456789.-1234567890")); + assertNotNull(v = Version.create(s = "raw:0.-1.-2.-3.-4.-5.-6.-7.-8.-9")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:123456789.-1234567890")); + assertNotNull(v = Version.create(s = "raw:123456789.-1234567890")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:m")); + assertNotNull(v = Version.create(s = "raw:123456789.-1234567890")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:M")); + assertNotNull(v = Version.create(s = "raw:m")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:-M")); + assertNotNull(v = Version.create(s = "raw:M")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.m")); + assertNotNull(v = Version.create(s = "raw:-M")); + assertEquals("0.0.0", v.toString()); + assertNotNull(v = Version.create(s = "raw:1.m")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.M")); + assertNotNull(v = Version.create(s = "raw:1.M")); assertEquals(s, v.toString()); // -M is normalized - assertNotNull(v = Version.parseVersion("raw:1.-M")); + assertNotNull(v = Version.create("raw:1.-M")); s = "raw:1"; assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:'a'")); + assertNotNull(v = Version.create(s = "raw:'a'")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:\"a\"")); + assertNotNull(v = Version.create(s = "raw:\"a\"")); // " is normalized to ' s = "raw:'a'"; assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:'ab'")); + assertNotNull(v = Version.create(s = "raw:'ab'")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:'abcdefghijklmnopqrstuvwxyz0123456789'")); + assertNotNull(v = Version.create(s = "raw:'abcdefghijklmnopqrstuvwxyz0123456789'")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'")); + assertNotNull(v = Version.create(s = "raw:'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:'-_!\"#$%&/()=?+*;,:.'")); + assertNotNull(v = Version.create(s = "raw:'-_!\"#$%&/()=?+*;,:.'")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:\"'\"")); + assertNotNull(v = Version.create(s = "raw:\"'\"")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:'\"'")); + assertNotNull(v = Version.create(s = "raw:'\"'")); assertEquals(s, v.toString()); } @@ -183,24 +184,24 @@ public class RawVersionTest extends VersionTesting { public void testIntegerParsing() { // should parse without exception - Version v = Version.parseVersion("raw:0"); + Version v = Version.create("raw:0"); assertNotNull(v); assertEquals(v.getSegment(0), Integer.valueOf(0)); // single digits - v = Version.parseVersion("raw:0.1.2.3.4.5.6.7.8.9"); + v = Version.create("raw:0.1.2.3.4.5.6.7.8.9"); assertNotNull(v); for (int i = 0; i < 10; i++) assertEquals(v.getSegment(i), Integer.valueOf(i)); // negative single digits - v = Version.parseVersion("raw:0.-1.-2.-3.-4.-5.-6.-7.-8.-9"); + v = Version.create("raw:0.-1.-2.-3.-4.-5.-6.-7.-8.-9"); assertNotNull(v); for (int i = 0; i < 10; i++) assertEquals(v.getSegment(i), Integer.valueOf(-i)); // some larger numbers - v = Version.parseVersion("raw:123456789.-1234567890"); + v = Version.create("raw:123456789.-1234567890"); assertNotNull(v); assertEquals(v.getSegment(0), Integer.valueOf(123456789)); assertEquals(v.getSegment(1), Integer.valueOf(-1234567890)); @@ -209,33 +210,33 @@ public class RawVersionTest extends VersionTesting { public void testWhiteSpaceExceptions() { try { - Version.parseVersion("raw: 0 "); + Version.create("raw: 0 "); fail("space not allowed 1"); } catch (IllegalArgumentException e) { assertTrue(true); } try { - Version.parseVersion("raw:0 .1 . 'a'. 'b c d'. 4. 5. 6. 7. 8 . 9"); + Version.create("raw:0 .1 . 'a'. 'b c d'. 4. 5. 6. 7. 8 . 9"); fail("space not allowed 2"); } catch (IllegalArgumentException e) { assertTrue(true); } try { - Version.parseVersion("raw:< 1.2.3>"); + Version.create("raw:< 1.2.3>"); fail("space not allowed in array 1"); } catch (IllegalArgumentException e) { assertTrue(true); } try { - Version.parseVersion("raw:<1.2.3 >"); + Version.create("raw:<1.2.3 >"); fail("space not allowed in array 2"); } catch (IllegalArgumentException e) { assertTrue(true); } try { - Version.parseVersion("raw:1.- 1"); + Version.create("raw:1.- 1"); fail("Uncaught error: space between minus and number in negative"); } catch (IllegalArgumentException e) { assertTrue(true); @@ -244,140 +245,140 @@ public class RawVersionTest extends VersionTesting { public void testMaxParsing() { - assertNotNull(Version.parseVersion("raw:m")); - assertNotNull(Version.parseVersion("raw:M")); - assertNotNull(Version.parseVersion("raw:-M")); + assertNotNull(Version.create("raw:m")); + assertNotNull(Version.create("raw:M")); + assertNotNull(Version.create("raw:-M")); - assertNotNull(Version.parseVersion("raw:1.m")); - assertNotNull(Version.parseVersion("raw:1.M")); - assertNotNull(Version.parseVersion("raw:1.-M")); + assertNotNull(Version.create("raw:1.m")); + assertNotNull(Version.create("raw:1.M")); + assertNotNull(Version.create("raw:1.-M")); } public void testStringParsing() { - Version v = Version.parseVersion("raw:'a'"); + Version v = Version.create("raw:'a'"); assertNotNull(v); assertEquals(v.getSegment(0), "a"); - assertNotNull(v = Version.parseVersion("raw:\"a\"")); + assertNotNull(v = Version.create("raw:\"a\"")); assertEquals(v.getSegment(0), "a"); - assertNotNull(v = Version.parseVersion("raw:'ab'")); + assertNotNull(v = Version.create("raw:'ab'")); assertEquals(v.getSegment(0), "ab"); - assertNotNull(v = Version.parseVersion("raw:'abcdefghijklmnopqrstuvwxyz0123456789'")); + assertNotNull(v = Version.create("raw:'abcdefghijklmnopqrstuvwxyz0123456789'")); assertEquals(v.getSegment(0), "abcdefghijklmnopqrstuvwxyz0123456789"); - assertNotNull(v = Version.parseVersion("raw:'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'")); + assertNotNull(v = Version.create("raw:'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'")); assertEquals(v.getSegment(0), "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); - assertNotNull(v = Version.parseVersion("raw:'-_!\"#$%&/()=?+*;,:.'")); + assertNotNull(v = Version.create("raw:'-_!\"#$%&/()=?+*;,:.'")); assertEquals(v.getSegment(0), "-_!\"#$%&/()=?+*;,:."); - assertNotNull(v = Version.parseVersion("raw:\"'\"")); + assertNotNull(v = Version.create("raw:\"'\"")); assertEquals(v.getSegment(0), "'"); - assertNotNull(v = Version.parseVersion("raw:'\"'")); + assertNotNull(v = Version.create("raw:'\"'")); assertEquals(v.getSegment(0), "\""); } public void testEmptyStringParsing() { - Version v = Version.parseVersion("raw:''"); + Version v = Version.create("raw:''"); assertNotNull(v); assertEquals(v.getSegment(0), ""); - v = Version.parseVersion("raw:\"\""); + v = Version.create("raw:\"\""); assertNotNull(v); assertEquals(v.getSegment(0), ""); } public void testStringConcatenation() { - Version v = Version.parseVersion("raw:'ab''cd'"); + Version v = Version.create("raw:'ab''cd'"); assertNotNull(v); assertEquals(v.getSegment(0), "abcd"); - v = Version.parseVersion("raw:'ab'\"cd\""); + v = Version.create("raw:'ab'\"cd\""); assertNotNull(v); assertEquals(v.getSegment(0), "abcd"); - v = Version.parseVersion("raw:\"ab\"\"cd\""); + v = Version.create("raw:\"ab\"\"cd\""); assertNotNull(v); assertEquals(v.getSegment(0), "abcd"); } public void testStringToString() { // string is normalized - assertEquals("raw:'abcd'", Version.parseVersion("raw:'ab''cd'").toString()); + assertEquals("raw:'abcd'", Version.create("raw:'ab''cd'").toString()); // string is normalized - assertEquals("raw:'abcd'", Version.parseVersion("raw:'ab'\"cd\"").toString()); + assertEquals("raw:'abcd'", Version.create("raw:'ab'\"cd\"").toString()); // string is normalized - assertEquals("raw:'abcd'", Version.parseVersion("raw:\"ab\"\"cd\"").toString()); + assertEquals("raw:'abcd'", Version.create("raw:\"ab\"\"cd\"").toString()); - assertEquals("raw:\"'\"", Version.parseVersion("raw:\"'\"").toString()); + assertEquals("raw:\"'\"", Version.create("raw:\"'\"").toString()); - assertEquals("raw:'\"'", Version.parseVersion("raw:'\"'").toString()); + assertEquals("raw:'\"'", Version.create("raw:'\"'").toString()); // quotes are normalized - default ' should be used until " is needed and vice versa. - assertEquals("raw:'abc\"xxx\"and '\"'yyy'\"", Version.parseVersion("raw:'abc\"xxx\"'\"and 'yyy'\"").toString()); + assertEquals("raw:'abc\"xxx\"and '\"'yyy'\"", Version.create("raw:'abc\"xxx\"'\"and 'yyy'\"").toString()); } public void testArrayParsing() { Version v = null; - assertNotNull(v = Version.parseVersion("raw:<1>")); - assertEquals(v.getSegment(0), Version.parseVersion("raw:1")); + assertNotNull(v = Version.create("raw:<1>")); + assertEquals(v.getSegment(0), new VersionVector(new Comparable[] {new Integer(1)}, null)); - assertNotNull(v = Version.parseVersion("raw:<1.0>")); - assertEquals(v.getSegment(0), Version.parseVersion("raw:1.0")); + assertNotNull(v = Version.create("raw:<1.0>")); + assertEquals(v.getSegment(0), new VersionVector(new Comparable[] {new Integer(1), new Integer(0)}, null)); - assertNotNull(v = Version.parseVersion("raw:<'a'>")); - assertEquals(v.getSegment(0), Version.parseVersion("raw:'a'")); + assertNotNull(v = Version.create("raw:<'a'>")); + assertEquals(v.getSegment(0), new VersionVector(new Comparable[] {"a"}, null)); - assertNotNull(v = Version.parseVersion("raw:<'a'.'b'>")); - assertEquals(v.getSegment(0), Version.parseVersion("raw:'a'.'b'")); + assertNotNull(v = Version.create("raw:<'a'.'b'>")); + assertEquals(v.getSegment(0), new VersionVector(new Comparable[] {"a", "b"}, null)); - assertNotNull(v = Version.parseVersion("raw:<'a'.'b''c'>")); - assertEquals(v.getSegment(0), Version.parseVersion("raw:'a'.'bc'")); // with concatenation + assertNotNull(v = Version.create("raw:<'a'.'b''c'>")); + assertEquals(v.getSegment(0), new VersionVector(new Comparable[] {"a", "bc"}, null)); - assertNotNull(v = Version.parseVersion("raw:<1.2.-M>")); - assertEquals(v.getSegment(0), Version.parseVersion("raw:1.2.-M")); + assertNotNull(v = Version.create("raw:<1.2.-M>")); + assertEquals(v.getSegment(0), new VersionVector(new Comparable[] {new Integer(1), new Integer(2)}, null)); - assertNotNull(v = Version.parseVersion("raw:<1.2.m>")); - assertEquals(v.getSegment(0), Version.parseVersion("raw:1.2.m")); + assertNotNull(v = Version.create("raw:<1.2.m>")); + assertEquals(v.getSegment(0), new VersionVector(new Comparable[] {new Integer(1), new Integer(2), VersionVector.MAXS_VALUE}, null)); - assertNotNull(v = Version.parseVersion("raw:<1.2.M>")); - assertEquals(v.getSegment(0), Version.parseVersion("raw:1.2.M")); + assertNotNull(v = Version.create("raw:<1.2.M>")); + assertEquals(v.getSegment(0), new VersionVector(new Comparable[] {new Integer(1), new Integer(2), VersionVector.MAX_VALUE}, null)); - assertNotNull(v = Version.parseVersion("raw:<<1>>")); - assertEquals(v.getSegment(0), Version.parseVersion("raw:<1>")); + assertNotNull(v = Version.create("raw:<<1>>")); + assertEquals(v.getSegment(0), new VersionVector(new Comparable[] {new VersionVector(new Comparable[] {new Integer(1)}, null)}, null)); - assertNotNull(v = Version.parseVersion("raw:<<1.<2>>>")); - assertEquals(v.getSegment(0), Version.parseVersion("raw:<1.<2>>")); + assertNotNull(v = Version.create("raw:<<1.<2>>>")); + assertEquals(v.getSegment(0), new VersionVector(new Comparable[] {new VersionVector(new Comparable[] {new Integer(1), new VersionVector(new Comparable[] {new Integer(2)}, null)}, null)}, null)); } public void testArraySerialize() { Version v = null; - assertNotNull(v = Version.parseVersion("raw:<1>")); + assertNotNull(v = Version.create("raw:<1>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:<1.0>")); + assertNotNull(v = Version.create("raw:<1.0>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:<'a'>")); + assertNotNull(v = Version.create("raw:<'a'>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:<'a'.'b'>")); + assertNotNull(v = Version.create("raw:<'a'.'b'>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:<'a'.'b''c'>")); + assertNotNull(v = Version.create("raw:<'a'.'b''c'>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:<1.2.-M>")); + assertNotNull(v = Version.create("raw:<1.2.-M>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:<1.2.m>")); + assertNotNull(v = Version.create("raw:<1.2.m>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:<1.2.M>")); + assertNotNull(v = Version.create("raw:<1.2.M>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:<<1>>")); + assertNotNull(v = Version.create("raw:<<1>>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:<<1.<2>>>")); + assertNotNull(v = Version.create("raw:<<1.<2>>>")); assertSerialized(v); } @@ -385,37 +386,37 @@ public class RawVersionTest extends VersionTesting { public void testArraytoString() { Version v = null; String s = null; - assertNotNull(v = Version.parseVersion(s = "raw:<1>")); + assertNotNull(v = Version.create(s = "raw:<1>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:<1.0>")); + assertNotNull(v = Version.create(s = "raw:<1.0>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:<'a'>")); + assertNotNull(v = Version.create(s = "raw:<'a'>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:<'a'.'b'>")); + assertNotNull(v = Version.create(s = "raw:<'a'.'b'>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:<'a'.'bc'>")); + assertNotNull(v = Version.create(s = "raw:<'a'.'bc'>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion("raw:<1.2.-M>")); + assertNotNull(v = Version.create("raw:<1.2.-M>")); s = "raw:<1.2>"; // is normalized assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:<1.2.m>")); + assertNotNull(v = Version.create(s = "raw:<1.2.m>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:<1.2.M>")); + assertNotNull(v = Version.create(s = "raw:<1.2.M>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:<<1>>")); + assertNotNull(v = Version.create(s = "raw:<<1>>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:<<1.<2>>>")); + assertNotNull(v = Version.create(s = "raw:<<1.<2>>>")); assertEquals(s, v.toString()); } public void testArrayOrder() { - Version v1 = Version.parseVersion("raw:<1.0.0>"); - Version v2 = Version.parseVersion("raw:<1.1.0>"); + Version v1 = Version.create("raw:<1.0.0>"); + Version v2 = Version.create("raw:<1.1.0>"); - Version v3 = Version.parseVersion("raw:<1.0.0>.<1.0.0>"); - Version v4 = Version.parseVersion("raw:<1.0.0>.<1.0.0>.'a'"); - Version v5 = Version.parseVersion("raw:<1.0.0>.<1.0.1>"); - Version v6 = Version.parseVersion("raw:<2.0.0>"); + Version v3 = Version.create("raw:<1.0.0>.<1.0.0>"); + Version v4 = Version.create("raw:<1.0.0>.<1.0.0>.'a'"); + Version v5 = Version.create("raw:<1.0.0>.<1.0.1>"); + Version v6 = Version.create("raw:<2.0.0>"); assertOrder(v1, v2); assertOrder(v3, v4); @@ -425,82 +426,82 @@ public class RawVersionTest extends VersionTesting { public void testPadParsing1() { Version v = null; - assertNotNull(v = Version.parseVersion("raw:1.0p0")); + assertNotNull(v = Version.create("raw:1.0p0")); assertPad(v, "raw:0"); - assertNotNull(v = Version.parseVersion("raw:1.0p'foo'")); + assertNotNull(v = Version.create("raw:1.0p'foo'")); assertPad(v, "raw:'foo'"); - assertNotNull(v = Version.parseVersion("raw:1.0p<0>")); + assertNotNull(v = Version.create("raw:1.0p<0>")); assertPad(v, "raw:<0>"); - assertNotNull(v = Version.parseVersion("raw:1.0p<'foo'>")); + assertNotNull(v = Version.create("raw:1.0p<'foo'>")); assertPad(v, "raw:<'foo'>"); - assertNotNull(v = Version.parseVersion("raw:1.0pm")); + assertNotNull(v = Version.create("raw:1.0pm")); assertPad(v, "raw:m"); - assertNotNull(v = Version.parseVersion("raw:1.0pM")); + assertNotNull(v = Version.create("raw:1.0pM")); assertPad(v, "raw:M"); - assertNotNull(v = Version.parseVersion("raw:1.0p-M")); + assertNotNull(v = Version.create("raw:1.0p-M")); assertEquals(v.getPad(), null); - assertNotNull(v = Version.parseVersion("raw:1.0p")); + assertNotNull(v = Version.create("raw:1.0p")); assertPad(v, "raw:"); - assertNotNull(v = Version.parseVersion("raw:1.0p")); + assertNotNull(v = Version.create("raw:1.0p")); assertPad(v, "raw:"); - assertNotNull(v = Version.parseVersion("raw:1.0p<-M>")); + assertNotNull(v = Version.create("raw:1.0p<-M>")); assertPad(v, "raw:<-M>"); - assertNotNull(v = Version.parseVersion("raw:1.0p<1.0.0.'r12345'.m>")); + assertNotNull(v = Version.create("raw:1.0p<1.0.0.'r12345'.m>")); assertPad(v, "raw:<1.0.0.'r12345'.m>"); } public void testPadSerialize() { Version v = null; - assertNotNull(v = Version.parseVersion("raw:1.0p0")); + assertNotNull(v = Version.create("raw:1.0p0")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p'foo'")); + assertNotNull(v = Version.create("raw:1.0p'foo'")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p<0>")); + assertNotNull(v = Version.create("raw:1.0p<0>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p<'foo'>")); + assertNotNull(v = Version.create("raw:1.0p<'foo'>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0pm")); + assertNotNull(v = Version.create("raw:1.0pm")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0pM")); + assertNotNull(v = Version.create("raw:1.0pM")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p-M")); + assertNotNull(v = Version.create("raw:1.0p-M")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p")); + assertNotNull(v = Version.create("raw:1.0p")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p")); + assertNotNull(v = Version.create("raw:1.0p")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p<-M>")); + assertNotNull(v = Version.create("raw:1.0p<-M>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p<1.0.0.'r12345'.m>")); + assertNotNull(v = Version.create("raw:1.0p<1.0.0.'r12345'.m>")); assertSerialized(v); } public void testPadtoString() { Version v = null; String s = null; - assertNotNull(v = Version.parseVersion("raw:1.0p0")); + assertNotNull(v = Version.create("raw:1.0p0")); s = "raw:1p0"; // normalized assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0p'foo'")); + assertNotNull(v = Version.create(s = "raw:1.0p'foo'")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0p<0>")); + assertNotNull(v = Version.create(s = "raw:1.0p<0>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0p<'foo'>")); + assertNotNull(v = Version.create(s = "raw:1.0p<'foo'>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0pm")); + assertNotNull(v = Version.create(s = "raw:1.0pm")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0pM")); + assertNotNull(v = Version.create(s = "raw:1.0pM")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion("raw:1.0p-M")); + assertNotNull(v = Version.create("raw:1.0p-M")); s = "raw:1.0"; // normalized assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0p")); + assertNotNull(v = Version.create(s = "raw:1.0p")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0p")); + assertNotNull(v = Version.create(s = "raw:1.0p")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0p<-M>")); + assertNotNull(v = Version.create(s = "raw:1.0p<-M>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0p<1.0.0.'r12345'.m>")); + assertNotNull(v = Version.create(s = "raw:1.0p<1.0.0.'r12345'.m>")); assertEquals(s, v.toString()); } @@ -509,91 +510,92 @@ public class RawVersionTest extends VersionTesting { */ public void testNestedPadParsing() { Version v = null; - assertNotNull(v = Version.parseVersion("raw:1.0p<0p0>")); + assertNotNull(v = Version.create("raw:1.0p<0p0>")); assertPad(v, "raw:<0p0>"); - assertPad(v.getPad(), "raw:0"); - assertNotNull(v = Version.parseVersion("raw:1.0p<0p'foo'>")); + assertPadPad(v, "raw:0"); + assertNotNull(v = Version.create("raw:1.0p<0p'foo'>")); assertPad(v, "raw:<0p'foo'>"); - assertPad(v.getPad(), "raw:'foo'"); - assertNotNull(v = Version.parseVersion("raw:1.0p<0p<0>>")); + assertPadPad(v, "raw:'foo'"); + assertNotNull(v = Version.create("raw:1.0p<0p<0>>")); assertPad(v, "raw:<0p<0>>"); - assertPad(v.getPad(), "raw:<0>"); - assertNotNull(v = Version.parseVersion("raw:1.0p<0p<'foo'>>")); + assertPadPad(v, "raw:<0>"); + assertNotNull(v = Version.create("raw:1.0p<0p<'foo'>>")); assertPad(v, "raw:<0p<'foo'>>"); - assertPad(v.getPad(), "raw:<'foo'>"); + assertPadPad(v, "raw:<'foo'>"); - assertNotNull(v = Version.parseVersion("raw:1.0p<0pm>")); + assertNotNull(v = Version.create("raw:1.0p<0pm>")); assertPad(v, "raw:<0pm>"); - assertPad(v.getPad(), "raw:m"); + assertPadPad(v, "raw:m"); - assertNotNull(v = Version.parseVersion("raw:1.0p<0pM>")); + assertNotNull(v = Version.create("raw:1.0p<0pM>")); assertPad(v, "raw:<0pM>"); - assertPad(v.getPad(), "raw:M"); + assertPadPad(v, "raw:M"); - assertNotNull(v = Version.parseVersion("raw:1.0p<0p-M>")); + assertNotNull(v = Version.create("raw:1.0p<0p-M>")); assertPad(v, "raw:<0p-M>"); + assertPadPad(v, null); assertEquals(((VersionVector) v.getPad()).getPad(), null); - assertNotNull(v = Version.parseVersion("raw:1.0p<0p>")); + assertNotNull(v = Version.create("raw:1.0p<0p>")); assertPad(v, "raw:<0p>"); - assertPad(v.getPad(), "raw:"); + assertPadPad(v, "raw:"); - assertNotNull(v = Version.parseVersion("raw:1.0p<0pM>")); + assertNotNull(v = Version.create("raw:1.0p<0pM>")); assertPad(v, "raw:<0pM>"); - assertPad(v.getPad(), "raw:M"); + assertPadPad(v, "raw:M"); - assertNotNull(v = Version.parseVersion("raw:1.0p<0p-M>")); + assertNotNull(v = Version.create("raw:1.0p<0p-M>")); assertPad(v, "raw:<0p-M>"); - assertEquals(((VersionVector) v.getPad()).getPad(), null); + assertPadPad(v, null); } public void testNestedPadSerialize() { Version v = null; - assertNotNull(v = Version.parseVersion("raw:1.0p<0p0>")); + assertNotNull(v = Version.create("raw:1.0p<0p0>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p<0p'foo'>")); + assertNotNull(v = Version.create("raw:1.0p<0p'foo'>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p<0p<0>>")); + assertNotNull(v = Version.create("raw:1.0p<0p<0>>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p<0p<'foo'>>")); + assertNotNull(v = Version.create("raw:1.0p<0p<'foo'>>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p<0pm>")); + assertNotNull(v = Version.create("raw:1.0p<0pm>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p<0pM>")); + assertNotNull(v = Version.create("raw:1.0p<0pM>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p<0p-M>")); + assertNotNull(v = Version.create("raw:1.0p<0p-M>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p<0p>")); + assertNotNull(v = Version.create("raw:1.0p<0p>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p<0pM>")); + assertNotNull(v = Version.create("raw:1.0p<0pM>")); assertSerialized(v); - assertNotNull(v = Version.parseVersion("raw:1.0p<0p-M>")); + assertNotNull(v = Version.create("raw:1.0p<0p-M>")); assertSerialized(v); } public void testNestedPadtoString() { Version v = null; String s = null; - assertNotNull(v = Version.parseVersion(s = "raw:1.0p<0p0>")); + assertNotNull(v = Version.create(s = "raw:1.0p<0p0>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0p<0p'foo'>")); + assertNotNull(v = Version.create(s = "raw:1.0p<0p'foo'>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0p<0p<0>>")); + assertNotNull(v = Version.create(s = "raw:1.0p<0p<0>>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0p<0p<'foo'>>")); + assertNotNull(v = Version.create(s = "raw:1.0p<0p<'foo'>>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0p<0pm>")); + assertNotNull(v = Version.create(s = "raw:1.0p<0pm>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0p<0pM>")); + assertNotNull(v = Version.create(s = "raw:1.0p<0pM>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion("raw:1.0p<0p-M>")); + assertNotNull(v = Version.create("raw:1.0p<0p-M>")); s = "raw:1.0p<0>"; // normalized assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0p<0p>")); + assertNotNull(v = Version.create(s = "raw:1.0p<0p>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion(s = "raw:1.0p<0pM>")); + assertNotNull(v = Version.create(s = "raw:1.0p<0pM>")); assertEquals(s, v.toString()); - assertNotNull(v = Version.parseVersion("raw:1.0p<0p-M>")); + assertNotNull(v = Version.create("raw:1.0p<0p-M>")); s = "raw:1.0p<0>"; // normalized assertEquals(s, v.toString()); } @@ -603,15 +605,15 @@ public class RawVersionTest extends VersionTesting { * 1p-M < 1.0.0 < 1.0.0p0 == 1p0 < 1.1 < 1.1.1 < 1p1 == 1.1p1 < 1pM */ public void testPadOrder() { - Version v1 = Version.parseVersion("raw:1p-M"); - Version v2 = Version.parseVersion("raw:1.0.0"); - Version v3 = Version.parseVersion("raw:1.0.0p0"); - Version v4 = Version.parseVersion("raw:1p0"); - Version v5 = Version.parseVersion("raw:1.1"); - Version v6 = Version.parseVersion("raw:1.1.1"); - Version v7 = Version.parseVersion("raw:1p1"); - Version v8 = Version.parseVersion("raw:1.1p1"); - Version v9 = Version.parseVersion("raw:1pM"); + Version v1 = Version.create("raw:1p-M"); + Version v2 = Version.create("raw:1.0.0"); + Version v3 = Version.create("raw:1.0.0p0"); + Version v4 = Version.create("raw:1p0"); + Version v5 = Version.create("raw:1.1"); + Version v6 = Version.create("raw:1.1.1"); + Version v7 = Version.create("raw:1p1"); + Version v8 = Version.create("raw:1.1p1"); + Version v9 = Version.create("raw:1pM"); assertOrder(v1, v2); assertOrder(v2, v3); @@ -624,13 +626,13 @@ public class RawVersionTest extends VersionTesting { } public void testPadTypeOrder() { - Version v0 = Version.parseVersion("raw:1p-M"); - Version v1 = Version.parseVersion("raw:1p'a'"); - Version v2 = Version.parseVersion("raw:1p<0>"); - Version v3 = Version.parseVersion("raw:1.0.0"); - Version v4 = Version.parseVersion("raw:1p0"); - Version v5 = Version.parseVersion("raw:1p1"); - Version v6 = Version.parseVersion("raw:1pM"); + Version v0 = Version.create("raw:1p-M"); + Version v1 = Version.create("raw:1p'a'"); + Version v2 = Version.create("raw:1p<0>"); + Version v3 = Version.create("raw:1.0.0"); + Version v4 = Version.create("raw:1p0"); + Version v5 = Version.create("raw:1p1"); + Version v6 = Version.create("raw:1pM"); assertOrder(v0, v1); assertOrder(v1, v2); assertOrder(v2, v3); @@ -643,11 +645,11 @@ public class RawVersionTest extends VersionTesting { * Test that a / is not prematurely taken as the separator between raw and original when in a string */ public void testOriginalTerminator() { - Version v = Version.parseVersion("raw:'/'"); + Version v = Version.create("raw:'/'"); assertNotNull(v); assertEquals(v.getSegment(0), "/"); - v = Version.parseVersion("raw:\"/\""); + v = Version.create("raw:\"/\""); assertNotNull(v); assertEquals(v.getSegment(0), "/"); } @@ -655,7 +657,7 @@ public class RawVersionTest extends VersionTesting { public void testEmptyInput() { // should parse with exception try { - Version.parseVersion("raw:"); + Version.create("raw:"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -665,7 +667,7 @@ public class RawVersionTest extends VersionTesting { public void testNewLine() { // should parse with exception try { - Version.parseVersion("raw:1.'\n'.2"); + Version.create("raw:1.'\n'.2"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -675,7 +677,7 @@ public class RawVersionTest extends VersionTesting { public void testSpaceInInt() { // should parse with exception try { - Version.parseVersion("raw:1 2.2"); + Version.create("raw:1 2.2"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -685,7 +687,7 @@ public class RawVersionTest extends VersionTesting { public void testFloatingPointl() { // should parse with exception try { - Version.parseVersion("raw:1,2.2"); + Version.create("raw:1,2.2"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -695,7 +697,7 @@ public class RawVersionTest extends VersionTesting { public void testScientific() { // should parse with exception try { - Version.parseVersion("raw:1E3"); + Version.create("raw:1E3"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -705,7 +707,7 @@ public class RawVersionTest extends VersionTesting { public void testHex() { // should parse with exception try { - Version.parseVersion("raw:0xABCD"); + Version.create("raw:0xABCD"); fail("Uncaught error: hexadecimal not allowed"); } catch (IllegalArgumentException e) { assertTrue(true); @@ -714,7 +716,7 @@ public class RawVersionTest extends VersionTesting { public void testUnbalancedSingleQuoteRight() { try { - Version.parseVersion("raw:'unbalanced"); + Version.create("raw:'unbalanced"); fail("Uncaught error: unbalanced sngle quote"); } catch (IllegalArgumentException e) { assertTrue(true); @@ -723,7 +725,7 @@ public class RawVersionTest extends VersionTesting { public void testMixedQuotes1() { try { - Version.parseVersion("raw:1.\"unbalanced'.10"); + Version.create("raw:1.\"unbalanced'.10"); fail("Uncaught error: mixed quotes"); } catch (IllegalArgumentException e) { assertTrue(true); @@ -732,7 +734,7 @@ public class RawVersionTest extends VersionTesting { public void testMixedQuotes2() { try { - Version.parseVersion("raw:1.'unbalanced\".10"); + Version.create("raw:1.'unbalanced\".10"); fail("Uncaught error: mixed quotes"); } catch (IllegalArgumentException e) { assertTrue(true); @@ -741,7 +743,7 @@ public class RawVersionTest extends VersionTesting { public void testUnbalancedDoubleQuoteRight() { try { - Version.parseVersion("raw:\"unbalanced"); + Version.create("raw:\"unbalanced"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -750,7 +752,7 @@ public class RawVersionTest extends VersionTesting { public void testUnbalancedArrayRight() { try { - Version.parseVersion("raw:<1.2.3"); + Version.create("raw:<1.2.3"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -759,7 +761,7 @@ public class RawVersionTest extends VersionTesting { public void testUnbalancedArrayLeft() { try { - Version.parseVersion("raw:1.2.3>"); + Version.create("raw:1.2.3>"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -768,7 +770,7 @@ public class RawVersionTest extends VersionTesting { public void testBadDecimalInteger() { try { - Version.parseVersion("raw:12af"); + Version.create("raw:12af"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -777,7 +779,7 @@ public class RawVersionTest extends VersionTesting { public void testUnquotedStringFirstValue() { try { - Version.parseVersion("raw:a"); + Version.create("raw:a"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -786,7 +788,7 @@ public class RawVersionTest extends VersionTesting { public void testUnquotedStringSecondValue() { try { - Version.parseVersion("raw:1.a"); + Version.create("raw:1.a"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -795,7 +797,7 @@ public class RawVersionTest extends VersionTesting { public void testSinglePeriod() { try { - Version.parseVersion("raw:."); + Version.create("raw:."); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -804,7 +806,7 @@ public class RawVersionTest extends VersionTesting { public void testTwoPeriods() { try { - Version.parseVersion("raw:.."); + Version.create("raw:.."); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -813,7 +815,7 @@ public class RawVersionTest extends VersionTesting { public void testThreePeriods() { try { - Version.parseVersion("raw:..."); + Version.create("raw:..."); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -823,7 +825,7 @@ public class RawVersionTest extends VersionTesting { public void testPadNotLast() { try { - Version.parseVersion("raw:p10.10"); + Version.create("raw:p10.10"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -833,7 +835,7 @@ public class RawVersionTest extends VersionTesting { public void testEmptyPad() { try { - Version.parseVersion("raw:10p"); + Version.create("raw:10p"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -842,7 +844,7 @@ public class RawVersionTest extends VersionTesting { public void testPadWithNull() { try { - Version.parseVersion("raw:10p."); + Version.create("raw:10p."); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -851,7 +853,7 @@ public class RawVersionTest extends VersionTesting { public void testWrongPadSeparator() { try { - Version.parseVersion("raw:10.p0"); + Version.create("raw:10.p0"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -860,7 +862,7 @@ public class RawVersionTest extends VersionTesting { public void testMultiplePadElements() { try { - Version.parseVersion("raw:10p1.2"); + Version.create("raw:10p1.2"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -869,7 +871,7 @@ public class RawVersionTest extends VersionTesting { public void testUnbalancedPadElementsSQ() { try { - Version.parseVersion("raw:10p'abc"); + Version.create("raw:10p'abc"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -878,7 +880,7 @@ public class RawVersionTest extends VersionTesting { public void testUnbalancedPadElementsDQ() { try { - Version.parseVersion("raw:10p\"abc"); + Version.create("raw:10p\"abc"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -887,7 +889,7 @@ public class RawVersionTest extends VersionTesting { public void testUnbalancedPadArrayElementsRight() { try { - Version.parseVersion("raw:10p<10"); + Version.create("raw:10p<10"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -896,7 +898,7 @@ public class RawVersionTest extends VersionTesting { public void testUnbalancedPadArrayElementsLeft() { try { - Version.parseVersion("raw:10p10>"); + Version.create("raw:10p10>"); fail(); } catch (IllegalArgumentException e) { assertTrue(true); @@ -904,11 +906,11 @@ public class RawVersionTest extends VersionTesting { } public void testOrder() { - Version v1 = Version.parseVersion("raw:1"); - Version v2 = Version.parseVersion("raw:1.0"); - Version v3 = Version.parseVersion("raw:1.0.0"); - Version v4 = Version.parseVersion("raw:1.0.0.'9'"); - Version v5 = Version.parseVersion("raw:1.0.0.'r12345'"); + Version v1 = Version.create("raw:1"); + Version v2 = Version.create("raw:1.0"); + Version v3 = Version.create("raw:1.0.0"); + Version v4 = Version.create("raw:1.0.0.'9'"); + Version v5 = Version.create("raw:1.0.0.'r12345'"); assertOrder(v1, v2); assertOrder(v2, v3); @@ -918,14 +920,14 @@ public class RawVersionTest extends VersionTesting { public void testTypeOrder() { // '' < 'z' < m < [0} < [M] < 0 < M - Version v0 = Version.parseVersion("raw:-M"); - Version v1 = Version.parseVersion("raw:''"); - Version v2 = Version.parseVersion("raw:'z'"); - Version v3 = Version.parseVersion("raw:m"); - Version v4 = Version.parseVersion("raw:<0>"); - Version v5 = Version.parseVersion("raw:"); - Version v6 = Version.parseVersion("raw:0"); - Version v7 = Version.parseVersion("raw:M"); + Version v0 = Version.create("raw:-M"); + Version v1 = Version.create("raw:''"); + Version v2 = Version.create("raw:'z'"); + Version v3 = Version.create("raw:m"); + Version v4 = Version.create("raw:<0>"); + Version v5 = Version.create("raw:"); + Version v6 = Version.create("raw:0"); + Version v7 = Version.create("raw:M"); assertOrder(v0, v1); assertOrder(v1, v2); @@ -938,14 +940,14 @@ public class RawVersionTest extends VersionTesting { public void testTypeOrder2() { // '' < 'z' < m < [0] < [M] < 0 < M - Version v0 = Version.parseVersion("raw:0.-M"); - Version v1 = Version.parseVersion("raw:0.''"); - Version v2 = Version.parseVersion("raw:0.'z'"); - Version v3 = Version.parseVersion("raw:0.m"); - Version v4 = Version.parseVersion("raw:0.<0>"); - Version v5 = Version.parseVersion("raw:0."); - Version v6 = Version.parseVersion("raw:0.0"); - Version v7 = Version.parseVersion("raw:0.M"); + Version v0 = Version.create("raw:0.-M"); + Version v1 = Version.create("raw:0.''"); + Version v2 = Version.create("raw:0.'z'"); + Version v3 = Version.create("raw:0.m"); + Version v4 = Version.create("raw:0.<0>"); + Version v5 = Version.create("raw:0."); + Version v6 = Version.create("raw:0.0"); + Version v7 = Version.create("raw:0.M"); assertOrder(v0, v1); assertOrder(v1, v2); @@ -957,17 +959,17 @@ public class RawVersionTest extends VersionTesting { } public void testShorterIsOlder() { - Version v1 = Version.parseVersion("raw:1.0"); - Version v2 = Version.parseVersion("raw:1.0.0"); - Version v3 = Version.parseVersion("raw:1.0.0.0"); + Version v1 = Version.create("raw:1.0"); + Version v2 = Version.create("raw:1.0.0"); + Version v3 = Version.create("raw:1.0.0.0"); - Version v4 = Version.parseVersion("raw:'a'"); - Version v5 = Version.parseVersion("raw:'a'.'b'.'b'"); - Version v6 = Version.parseVersion("raw:'a'.'b'.'b'.'b'"); + Version v4 = Version.create("raw:'a'"); + Version v5 = Version.create("raw:'a'.'b'.'b'"); + Version v6 = Version.create("raw:'a'.'b'.'b'.'b'"); - Version v7 = Version.parseVersion("raw:<1>"); - Version v8 = Version.parseVersion("raw:<1>.<0>.<0>"); - Version v9 = Version.parseVersion("raw:<1>.<0>.<0>.<0>"); + Version v7 = Version.create("raw:<1>"); + Version v8 = Version.create("raw:<1>.<0>.<0>"); + Version v9 = Version.create("raw:<1>.<0>.<0>.<0>"); assertOrder(v1, v2); assertOrder(v2, v3); @@ -980,14 +982,14 @@ public class RawVersionTest extends VersionTesting { } public void testNumericVersionOrder() { - Version v1 = Version.parseVersion("1"); - Version v2 = Version.parseVersion("1.0.1"); - Version v3 = Version.parseVersion("1.1"); - Version v4 = Version.parseVersion("1.1.1"); - Version v5 = Version.parseVersion("1.1.1.-"); - Version v6 = Version.parseVersion("1.2"); - Version v7 = Version.parseVersion("2"); - Version v8 = Version.parseVersion("10.0"); + Version v1 = Version.create("1"); + Version v2 = Version.create("1.0.1"); + Version v3 = Version.create("1.1"); + Version v4 = Version.create("1.1.1"); + Version v5 = Version.create("1.1.1.-"); + Version v6 = Version.create("1.2"); + Version v7 = Version.create("2"); + Version v8 = Version.create("10.0"); assertOrder(v1, v2); assertOrder(v2, v3); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawWithOriginalTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawWithOriginalTest.java index 32617bac3..55af3b42d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawWithOriginalTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/RawWithOriginalTest.java @@ -11,7 +11,7 @@ package org.eclipse.equinox.p2.tests.omniVersion; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; /** * Tests inclusion of original version string in the raw format. @@ -33,7 +33,7 @@ public class RawWithOriginalTest extends VersionTesting { public void testRawWithUnknownFormatSerialized() { assertSerialized(Version.parseVersion("raw:1.0/:silver.moon")); - assertEquals("raw:1.0/:silver.moon", getSerialized(new Version("raw:1.0/:silver.moon")).toString()); + assertEquals("raw:1.0/:silver.moon", getSerialized(Version.create("raw:1.0/:silver.moon")).toString()); } @@ -49,7 +49,7 @@ public class RawWithOriginalTest extends VersionTesting { public void testRawWithSimpleFormatSerialized() { assertSerialized(Version.parseVersion("raw:1.0/format(n.n):1.0")); - assertEquals("raw:1.0/format(n.n):1.0", getSerialized(new Version("raw:1.0/format(n.n):1.0")).toString()); + assertEquals("raw:1.0/format(n.n):1.0", getSerialized(Version.create("raw:1.0/format(n.n):1.0")).toString()); } public void testOriginalStatedButMissing() { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/VersionTesting.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/VersionTesting.java index 2886f0c6f..79e76d090 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/VersionTesting.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/omniVersion/VersionTesting.java @@ -11,9 +11,12 @@ package org.eclipse.equinox.p2.tests.omniVersion; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; + import java.io.*; import junit.framework.TestCase; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.p2.metadata.VersionVector; /** * Base class for version testing. Adds useful assert methods. @@ -62,32 +65,31 @@ public class VersionTesting extends TestCase { assertTrue(true); } - // /** - // * Assert that pad of v is the same as the single element raw version string - // * @param v - // * @param rawVersionString - // */ - // public static void assertPad(VersionVector v, String rawVersionString) { - // assertNotNull(v); - // assertNotNull(rawVersionString); - // Version v2 = Version.parseVersion(rawVersionString); - // assertNotNull(v2); - // - // assertEquals(v.getPad(), v2); - // } - - /** - * Assert that pad of v is the same as the single element raw version string - * @param v - * @param rawVersionString - */ - public static void assertPad(Comparable v, String rawVersionString) { - assertTrue(v instanceof VersionVector); - assertNotNull(rawVersionString); - Version v2 = Version.parseVersion(rawVersionString); - assertNotNull(v2); + public static void assertPad(Version v, String rawVersionString) { + assertNotNull(v); + Comparable cmp = null; + if (rawVersionString != null) { + Version v2 = Version.create(rawVersionString); + assertNotNull(v2); + assertTrue(v2.getSegmentCount() == 1); + cmp = v2.getSegment(0); + } + assertEquals(v.getPad(), cmp); + } - assertEquals(((VersionVector) v).getPad(), v2.getSegment(0)); + public void assertPadPad(Version v, String rawVersionString) { + // TODO Auto-generated method stub + assertNotNull(v); + Comparable pad = v.getPad(); + assertTrue(pad instanceof VersionVector); + Comparable cmp = null; + if (rawVersionString != null) { + Version v2 = Version.create(rawVersionString); + assertNotNull(v2); + assertTrue(v2.getSegmentCount() == 1); + cmp = v2.getSegment(0); + } + assertEquals(((VersionVector) pad).getPad(), cmp); } /** diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/perf/MetadataRepositoryPerformanceTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/perf/MetadataRepositoryPerformanceTest.java new file mode 100644 index 000000000..fcda75acc --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/perf/MetadataRepositoryPerformanceTest.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.tests.perf; + +import java.io.File; +import org.eclipse.core.tests.harness.PerformanceTestRunner; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; + +/** + * Performance tests for metadata repositories + */ +public class MetadataRepositoryPerformanceTest extends ProvisioningPerformanceTest { + private static final int REPEATS = 5; + protected File repoLocation; + IMetadataRepository repository; + + protected void setUp() throws Exception { + super.setUp(); + String tempDir = System.getProperty("java.io.tmpdir"); + repoLocation = new File(tempDir, "MetadataRepositoryPerformanceTest"); + delete(repoLocation); + repoLocation.mkdir(); + IMetadataRepositoryManager manager = getMetadataRepositoryManager(); + repository = manager.createRepository(repoLocation.toURI(), "TestRepo", IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, null); + } + + protected void tearDown() throws Exception { + getMetadataRepositoryManager().removeRepository(repoLocation.toURI()); + delete(repoLocation); + super.tearDown(); + } + + public void testQueryLocalRepository() { + final int IU_COUNT = 3000; + new PerformanceTestRunner() { + IQuery[] queries = new IQuery[IU_COUNT]; + + protected void setUp() { + IInstallableUnit[] ius = new IInstallableUnit[IU_COUNT]; + for (int i = 0; i < ius.length; i++) { + ius[i] = generateIU(i); + queries[i] = new InstallableUnitQuery(ius[i].getId(), ius[i].getVersion()); + } + repository.addInstallableUnits(ius); + } + + protected void tearDown() { + } + + protected void test() { + for (int i = 0; i < queries.length; i++) { + repository.query(queries[i], null); + } + } + }.run(this, "Test query local metadata repo for " + IU_COUNT + " ius", REPEATS, 10); + } +} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/perf/ProvisioningPerformanceTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/perf/ProvisioningPerformanceTest.java new file mode 100644 index 000000000..cec1ec4e8 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/perf/ProvisioningPerformanceTest.java @@ -0,0 +1,31 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.tests.perf; + +import org.eclipse.equinox.p2.metadata.Version; + +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; + +/** + * + */ +public class ProvisioningPerformanceTest extends AbstractProvisioningTest { + + protected IInstallableUnit generateIU(int i) { + MetadataFactory.InstallableUnitDescription desc = new MetadataFactory.InstallableUnitDescription(); + desc.setId("org.eclipse.someiu" + i); + desc.setVersion(Version.createOSGi(1, 1, i)); + return MetadataFactory.createInstallableUnit(desc); + } + +} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/perf/PublisherPerformanceTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/perf/PublisherPerformanceTest.java new file mode 100644 index 000000000..a1a1c5eac --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/perf/PublisherPerformanceTest.java @@ -0,0 +1,53 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.tests.perf; + +import org.eclipse.core.tests.harness.PerformanceTestRunner; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.publisher.IPublisherResult; +import org.eclipse.equinox.p2.publisher.PublisherResult; +import org.eclipse.equinox.p2.query.IQuery; + +/** + * Performance tests for the p2 publisher + */ +public class PublisherPerformanceTest extends ProvisioningPerformanceTest { + private static final int REPEATS = 5; + + public void testQueryPublisherResult() { + final int IU_COUNT = 3000; + new PerformanceTestRunner() { + IQuery[] queries = new IQuery[IU_COUNT]; + PublisherResult result; + + protected void setUp() { + IInstallableUnit[] ius = new IInstallableUnit[IU_COUNT]; + result = new PublisherResult(); + for (int i = 0; i < ius.length; i++) { + ius[i] = generateIU(i); + result.addIU(ius[i], IPublisherResult.ROOT); + queries[i] = new InstallableUnitQuery(ius[i].getId(), ius[i].getVersion()); + } + } + + protected void tearDown() { + } + + protected void test() { + for (int i = 0; i < queries.length; i++) { + result.query(queries[i], null); + } + } + }.run(this, "Test query PublisherResult for " + IU_COUNT + " ius", REPEATS, 10); + + } +} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AbsolutePlanTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AbsolutePlanTest.java new file mode 100644 index 000000000..40b53d3e0 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AbsolutePlanTest.java @@ -0,0 +1,80 @@ +package org.eclipse.equinox.p2.tests.planner; + +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; + +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +public class AbsolutePlanTest extends AbstractProvisioningTest { + public void testAddAndRemoveIU() { + IProfile profile = createProfile(getName()); + ProfileChangeRequest pcr = new ProfileChangeRequest(profile); + pcr.setAbsoluteMode(true); + IInstallableUnit iuA = createEclipseIU("A"); + pcr.addInstallableUnits(new IInstallableUnit[] {iuA, createEclipseIU("B"), createEclipseIU("C")}); + IPlanner planner = createPlanner(); + IProvisioningPlan plan = planner.getProvisioningPlan(pcr, new ProvisioningContext(), null); + assertEquals(3, countPlanElements(plan)); + createEngine().perform(plan, null); + + ProfileChangeRequest removeRequest = new ProfileChangeRequest(profile); + removeRequest.setAbsoluteMode(true); + removeRequest.removeInstallableUnits(new IInstallableUnit[] {iuA}); + assertEquals(1, countPlanElements(planner.getProvisioningPlan(removeRequest, new ProvisioningContext(), null))); + } + + public void testAddAndRemoveProperty() { + IInstallableUnit iuA = createEclipseIU("A"); + IProfile profile = createProfile(getName()); + + ProfileChangeRequest pcr = new ProfileChangeRequest(profile); + pcr.setAbsoluteMode(true); + pcr.addInstallableUnits(new IInstallableUnit[] {iuA}); + pcr.setInstallableUnitProfileProperty(iuA, "key", "value"); + + IPlanner planner = createPlanner(); + IProvisioningPlan plan = planner.getProvisioningPlan(pcr, new ProvisioningContext(), null); + assertEquals(1, countPlanElements(plan)); + createEngine().perform(plan, null); + + Operand[] ops = plan.getOperands(); + boolean found = false; + for (int i = 0; i < ops.length; i++) { + if (ops[i] instanceof InstallableUnitPropertyOperand) + found = true; + } + assertTrue(found); + + ProfileChangeRequest removeRequest = new ProfileChangeRequest(profile); + removeRequest.setAbsoluteMode(true); + removeRequest.removeInstallableUnits(new IInstallableUnit[] {iuA}); + removeRequest.removeInstallableUnitProfileProperty(iuA, "key"); + + assertEquals(1, countPlanElements(planner.getProvisioningPlan(removeRequest, new ProvisioningContext(), null))); + } + + public void testAddProperty() { + IProfile profile = createProfile(getName()); + + ProfileChangeRequest pcr = new ProfileChangeRequest(profile); + pcr.setAbsoluteMode(true); + pcr.setProfileProperty("foo", "bar"); + + IPlanner planner = createPlanner(); + IProvisioningPlan plan = planner.getProvisioningPlan(pcr, new ProvisioningContext(), null); + createEngine().perform(plan, null); + + assertEquals("bar", getProfileRegistry().getProfile(getName()).getProperty("foo")); + } +} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ActualChangeRequestTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ActualChangeRequestTest.java index f24ed4994..868c7de50 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ActualChangeRequestTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ActualChangeRequestTest.java @@ -10,16 +10,17 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.Map; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class ActualChangeRequestTest extends AbstractProvisioningTest { @@ -32,9 +33,9 @@ public class ActualChangeRequestTest extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}, NO_PROPERTIES, true); + a = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {(IRequiredCapability) MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}, NO_PROPERTIES, true); - b = createIU("B", new Version("1.0.0"), true); + b = createIU("B", Version.create("1.0.0"), true); createTestMetdataRepository(new IInstallableUnit[] {a, b}); @@ -49,33 +50,33 @@ public class ActualChangeRequestTest extends AbstractProvisioningTest { req.addInstallableUnits(new IInstallableUnit[] {b}); req.setInstallableUnitInclusionRules(b, PlannerHelper.createStrictInclusionRule(b)); req.setInstallableUnitProfileProperty(b, "foo", "bar"); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getRequestStatus(b).getSeverity()); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); - engine.perform(profile1, new DefaultPhaseSet(), plan.getOperands(), null, null); + engine.perform(plan, null); assertProfileContainsAll("B is missing", profile1, new IInstallableUnit[] {b}); - assertEquals(1, profile1.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(1, queryResultSize(profile1.query(InstallableUnitQuery.ANY, null))); //Install A ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {a}); req2.setInstallableUnitInclusionRules(a, PlannerHelper.createStrictInclusionRule(a)); req2.setInstallableUnitProfileProperty(a, "foo", "bar"); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); assertNull(plan2.getRequestStatus(b)); Map m = plan2.getSideEffectChanges(); m.toString(); assertEquals(IStatus.OK, plan2.getRequestStatus(a).getSeverity()); - engine.perform(profile1, new DefaultPhaseSet(), plan2.getOperands(), null, null); + engine.perform(plan2, null); assertProfileContainsAll("A is missing", profile1, new IInstallableUnit[] {a, b}); - assertEquals(2, profile1.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(2, queryResultSize(profile1.query(InstallableUnitQuery.ANY, null))); //Uninstall B ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.removeInstallableUnits(new IInstallableUnit[] {b}); req3.removeInstallableUnitProfileProperty(b, "foo"); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.OK, plan3.getStatus().getSeverity()); assertEquals(IStatus.ERROR, plan3.getRequestStatus(b).getSeverity()); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ActualChangeRequestTest2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ActualChangeRequestTest2.java index c5b62d116..a74fa8f02 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ActualChangeRequestTest2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ActualChangeRequestTest2.java @@ -10,16 +10,17 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.Map; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class ActualChangeRequestTest2 extends AbstractProvisioningTest { @@ -33,10 +34,10 @@ public class ActualChangeRequestTest2 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}, NO_PROPERTIES, true); + a = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {(IRequiredCapability) MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}, NO_PROPERTIES, true); - b = createIU("B", new Version("1.0.0"), true); - b2 = createIU("B", new Version("2.0.0"), true); + b = createIU("B", Version.create("1.0.0"), true); + b2 = createIU("B", Version.create("2.0.0"), true); createTestMetdataRepository(new IInstallableUnit[] {a, b2, b}); @@ -53,19 +54,19 @@ public class ActualChangeRequestTest2 extends AbstractProvisioningTest { req.addInstallableUnits(new IInstallableUnit[] {a}); req.setInstallableUnitInclusionRules(a, PlannerHelper.createOptionalInclusionRule(a)); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getRequestStatus(b).getSeverity()); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); - engine.perform(profile1, new DefaultPhaseSet(), plan.getOperands(), null, null); + engine.perform(plan, null); assertProfileContainsAll("B is missing", profile1, new IInstallableUnit[] {a, b}); - assertEquals(2, profile1.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(2, queryResultSize(profile1.query(InstallableUnitQuery.ANY, null))); //Install B2 ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {b2}); req2.setInstallableUnitInclusionRules(b2, PlannerHelper.createStrictInclusionRule(b2)); req2.removeInstallableUnits(new IInstallableUnit[] {b}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); assertNotNull(plan2.getRequestStatus(b)); assertNotNull(plan2.getRequestStatus(b2)); @@ -74,26 +75,26 @@ public class ActualChangeRequestTest2 extends AbstractProvisioningTest { assertNotNull(m.get(a)); assertEquals(IStatus.INFO, ((RequestStatus) m.get(a)).getSeverity()); assertEquals(RequestStatus.REMOVED, ((RequestStatus) m.get(a)).getInitialRequestType()); - engine.perform(profile1, new DefaultPhaseSet(), plan2.getOperands(), null, null); + engine.perform(plan2, null); assertProfileContainsAll("A is missing", profile1, new IInstallableUnit[] {b2}); - assertEquals(1, profile1.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(1, queryResultSize(profile1.query(InstallableUnitQuery.ANY, null))); //Try to Install A ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.addInstallableUnits(new IInstallableUnit[] {a}); req3.setInstallableUnitInclusionRules(a, PlannerHelper.createOptionalInclusionRule(a)); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertNotNull(plan3.getRequestStatus(a)); assertEquals(IStatus.ERROR, plan3.getRequestStatus(a).getSeverity()); - assertEquals(RequestStatus.ADDED, plan3.getRequestStatus(a).getInitialRequestType()); + assertEquals(RequestStatus.ADDED, ((RequestStatus) plan3.getRequestStatus(a)).getInitialRequestType()); //Try to Install A ProfileChangeRequest req4 = new ProfileChangeRequest(profile1); req4.addInstallableUnits(new IInstallableUnit[] {a}); req4.setInstallableUnitInclusionRules(a, PlannerHelper.createStrictInclusionRule(a)); - ProvisioningPlan plan4 = planner.getProvisioningPlan(req4, null, null); + IProvisioningPlan plan4 = planner.getProvisioningPlan(req4, null, null); assertNotNull(plan4.getRequestStatus(a)); assertEquals(IStatus.ERROR, plan4.getRequestStatus(a).getSeverity()); - assertEquals(RequestStatus.ADDED, plan4.getRequestStatus(a).getInitialRequestType()); + assertEquals(RequestStatus.ADDED, ((RequestStatus) plan4.getRequestStatus(a)).getInitialRequestType()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AddIUProperty.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AddIUProperty.java index 1575d9049..d0cc00e13 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AddIUProperty.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AddIUProperty.java @@ -8,15 +8,16 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.director.SimplePlanner; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.query.IUProfilePropertyQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class AddIUProperty extends AbstractProvisioningTest { @@ -28,9 +29,9 @@ public class AddIUProperty extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), true); + a1 = createIU("A", Version.create("1.0.0"), true); - a2 = createIU("A", new Version("2.0.0"), true); + a2 = createIU("A", Version.create("2.0.0"), true); createTestMetdataRepository(new IInstallableUnit[] {a1, a2}); @@ -42,7 +43,7 @@ public class AddIUProperty extends AbstractProvisioningTest { public void testWithoutIUProperty() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, a1); } @@ -51,7 +52,7 @@ public class AddIUProperty extends AbstractProvisioningTest { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1}); req.setInstallableUnitInclusionRules(a1, PlannerHelper.createOptionalInclusionRule(a1)); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, a1); } @@ -60,43 +61,44 @@ public class AddIUProperty extends AbstractProvisioningTest { //Add a1, strictly ; ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); - engine.perform(profile, new DefaultPhaseSet(), plan.getOperands(), null, null); + engine.perform(plan, null); assertProfileContainsAll("A1 is missing", profile, new IInstallableUnit[] {a1}); - Collector allProfileIUs = profile.query(InstallableUnitQuery.ANY, new Collector(), null); - assertEquals(allProfileIUs.size(), 1); + IQueryResult allProfileIUs = profile.query(InstallableUnitQuery.ANY, null); + assertEquals(queryResultSize(allProfileIUs), 1); //Add a2 with a1. This is an error ProfileChangeRequest req4 = ProfileChangeRequest.createByProfileId(profile.getProfileId()); req4.addInstallableUnits(new IInstallableUnit[] {a2}); - ProvisioningPlan plan4 = planner.getProvisioningPlan(req4, null, null); + IProvisioningPlan plan4 = planner.getProvisioningPlan(req4, null, null); assertEquals(IStatus.ERROR, plan4.getStatus().getSeverity()); //Add a2, making a1 optional; ProfileChangeRequest req2 = ProfileChangeRequest.createByProfileId(profile.getProfileId()); req2.setInstallableUnitInclusionRules(a1, PlannerHelper.createOptionalInclusionRule(a1)); req2.addInstallableUnits(new IInstallableUnit[] {a2}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan2, a2); - engine.perform(profile, new DefaultPhaseSet(), plan2.getOperands(), null, null); + engine.perform(plan2, null); + profile = getProfile(profile.getProfileId()); assertProfileContainsAll("A2 is missing", profile, new IInstallableUnit[] {a2}); - allProfileIUs = profile.query(InstallableUnitQuery.ANY, new Collector(), null); - assertEquals(allProfileIUs.size(), 1); + allProfileIUs = profile.query(InstallableUnitQuery.ANY, null); + assertEquals(queryResultSize(allProfileIUs), 1); - Collector iuProfileProperties = profile.query(new IUProfilePropertyQuery(SimplePlanner.INCLUSION_RULES, null), new Collector(), null); - assertEquals(iuProfileProperties.size(), 1); + IQueryResult iuProfileProperties = profile.query(new IUProfilePropertyQuery(SimplePlanner.INCLUSION_RULES, null), null); + assertEquals(queryResultSize(iuProfileProperties), 1); //Remove a1 optionality - should be a no-op ProfileChangeRequest req3 = ProfileChangeRequest.createByProfileId(profile.getProfileId()); req3.removeInstallableUnitInclusionRules(a1); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); - engine.perform(profile, new DefaultPhaseSet(), plan3.getOperands(), null, null); - allProfileIUs = profile.query(InstallableUnitQuery.ANY, new Collector(), null); + engine.perform(plan3, null); + allProfileIUs = profile.query(InstallableUnitQuery.ANY, null); assertProfileContainsAll("A2 is missing", profile, new IInstallableUnit[] {a2}); - assertEquals(allProfileIUs.size(), 1); + assertEquals(queryResultSize(allProfileIUs), 1); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AdditionalConstraints.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AdditionalConstraints.java index 92ae7647c..848b6bc8d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AdditionalConstraints.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AdditionalConstraints.java @@ -10,15 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.Arrays; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class AdditionalConstraints extends AbstractProvisioningTest { @@ -33,15 +34,15 @@ public class AdditionalConstraints extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 4.0.0)"), null)); + a1 = createIU("A", Version.create("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 4.0.0)"))); - b1 = createIU("B", new Version("1.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); - b2 = createIU("B", new Version("2.0.0"), true); + b2 = createIU("B", Version.create("2.0.0"), true); - b3 = createIU("B", new Version("3.0.0"), true); + b3 = createIU("B", Version.create("3.0.0"), true); - x1 = createIU("X", new Version(2, 0, 0), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[2.0.0, 2.0.0]"), null)); + x1 = createIU("X", Version.createOSGi(2, 0, 0), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[2.0.0, 2.0.0]"))); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, b2, b3, x1}); @@ -54,8 +55,8 @@ public class AdditionalConstraints extends AbstractProvisioningTest { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1}); ProvisioningContext ctx = new ProvisioningContext(); - ctx.setAdditionalRequirements(Arrays.asList(createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[2.0.0, 2.0.0]"), null)[0])); - ProvisioningPlan plan = planner.getProvisioningPlan(req, ctx, null); + ctx.setAdditionalRequirements(Arrays. asList(createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[2.0.0, 2.0.0]"))[0])); + IProvisioningPlan plan = planner.getProvisioningPlan(req, ctx, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, a1); assertInstallOperand(plan, b2); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AgentPlanTestInExternalInstance.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AgentPlanTestInExternalInstance.java index 4d2337c84..bc8a9681c 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AgentPlanTestInExternalInstance.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AgentPlanTestInExternalInstance.java @@ -8,30 +8,25 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.lang.reflect.Field; import java.net.URI; import java.util.Properties; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; -import org.eclipse.equinox.p2.tests.TestActivator; public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { - Object previousSelfValue; - public void setUp() throws Exception { super.setUp(); - SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) getProfileRegistry(); try { Field selfField = SimpleProfileRegistry.class.getDeclaredField("self"); //$NON-NLS-1$ selfField.setAccessible(true); @@ -44,11 +39,11 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { createProfile("agent"); Properties p = new Properties(); p.setProperty("org.eclipse.equinox.p2.planner.resolveMetaRequirements", "false"); - createProfile("installation", null, p); + createProfile("installation", p); } public void tearDown() throws Exception { - SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) getProfileRegistry(); try { Field selfField = SimpleProfileRegistry.class.getDeclaredField("self"); //$NON-NLS-1$ selfField.setAccessible(true); @@ -63,7 +58,7 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { } public void testGetAgentPlanActionNeededButUnavailable() { - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); IProfile profile = getProfile("installation"); @@ -73,7 +68,7 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { request.addInstallableUnits(new IInstallableUnit[] {a}); ProvisioningContext context = new ProvisioningContext(new URI[0]); - ProvisioningPlan plan = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); assertNotOK(plan.getStatus()); } @@ -81,7 +76,7 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); createTestMetdataRepository(new IInstallableUnit[] {a, act1}); @@ -91,7 +86,7 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); assertTrue(plan.getStatus().isOK()); assertNotNull(plan.getInstallerPlan()); } @@ -100,10 +95,10 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { //This tests the case where the action is in conflict with the thing being installed //The action needs another version of A which is singleton IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); - IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 2.0.0]"), null), new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 2.0.0]")), new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); - IInstallableUnit a2 = createIU("A", new Version(2, 0, 0)); + IInstallableUnit a2 = createIU("A", Version.createOSGi(2, 0, 0)); createTestMetdataRepository(new IInstallableUnit[] {a, a2, act1}); @@ -113,7 +108,7 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); assertOK("Provisioning plan", plan.getStatus()); } @@ -121,7 +116,7 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); IInstallableUnit b = createEclipseIU("B"); @@ -133,19 +128,19 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { ProfileChangeRequest request = new ProfileChangeRequest(getProfile("installation")); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); //Check that the actions are installed properly - assertOK("install actions", engine.perform(getProfile("agent"), new DefaultPhaseSet(), plan.getInstallerPlan().getOperands(), null, null)); + assertOK("install actions", engine.perform(plan.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act1}); //Check that the IUs are installed in the profile - assertOK("install A", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan.getOperands(), null, null)); + assertOK("install A", engine.perform(plan, null)); assertProfileContainsAll("Checking profile after initial install", getProfile("installation"), new IInstallableUnit[] {a}); ProfileChangeRequest request2 = new ProfileChangeRequest(getProfile("installation")); request2.addInstallableUnits(new IInstallableUnit[] {b}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); + IProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); assertNull(plan2.getInstallerPlan()); - assertOK("install b", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan2.getOperands(), null, null)); + assertOK("install b", engine.perform(plan2, null)); assertProfileContainsAll("Checking profile after initial install", getProfile("installation"), new IInstallableUnit[] {a, b}); assertProfileContainsAll("Checking actions are still installed", getProfile("agent"), new IInstallableUnit[] {act1}); } @@ -153,10 +148,10 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { public void testWithOveralInDependency() { IInstallableUnit common = createEclipseIU("Common"); IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); - IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "Common", null), new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); + IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "Common"), new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); - IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "Common", null), metaReq); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); + IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "Common"), metaReq); createTestMetdataRepository(new IInstallableUnit[] {a, act1, common}); @@ -167,10 +162,10 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); - assertOK("install actions", engine.perform(getProfile("agent"), new DefaultPhaseSet(), plan.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + assertOK("install actions", engine.perform(plan.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act1, common}); - assertOK("install A", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan.getOperands(), null, null)); + assertOK("install A", engine.perform(plan, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("installation"), new IInstallableUnit[] {a, common}); } @@ -178,13 +173,13 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); IProvidedCapability act2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", DEFAULT_VERSION); IInstallableUnit act2 = createIU("Action2", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq2 = createRequiredCapabilities("p2.action", "action2", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq2 = createRequiredCapabilities("p2.action", "action2", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit b = createIUWithMetaRequirement("B", DEFAULT_VERSION, true, NO_REQUIRES, metaReq2); createTestMetdataRepository(new IInstallableUnit[] {a, b, act1, act2,}); @@ -196,19 +191,19 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { //install A which will install Action1 ProfileChangeRequest request = new ProfileChangeRequest(getProfile("installation")); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); - assertOK("install actions", engine.perform(getProfile("agent"), new DefaultPhaseSet(), plan.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + assertOK("install actions", engine.perform(plan.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act1}); - assertOK("install A", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan.getOperands(), null, null)); + assertOK("install A", engine.perform(plan, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("installation"), new IInstallableUnit[] {a}); //install B which will install Action2 ProfileChangeRequest request2 = new ProfileChangeRequest(getProfile("installation")); request2.addInstallableUnits(new IInstallableUnit[] {b}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); - assertOK("install actions", engine.perform(getProfile("agent"), new DefaultPhaseSet(), plan2.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); + assertOK("install actions", engine.perform(plan2.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act2, act1}); - assertOK("install A", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan2.getOperands(), null, null)); + assertOK("install A", engine.perform(plan2, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("installation"), new IInstallableUnit[] {b, a}); } @@ -216,25 +211,25 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); IProvidedCapability act1bCap = MetadataFactory.createProvidedCapability("p2.action", "action1b", DEFAULT_VERSION); IInstallableUnit act1b = createIU("Action1b", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1bCap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReqb = createRequiredCapabilities("p2.action", "action1b", new VersionRange("[0.0.0, 1.0.0]"), null); - IInstallableUnit a111 = createIUWithMetaRequirement("A", new Version(1, 1, 1), true, NO_REQUIRES, metaReqb); + IRequiredCapability[] metaReqb = createRequiredCapabilities("p2.action", "action1b", new VersionRange("[0.0.0, 1.0.0]")); + IInstallableUnit a111 = createIUWithMetaRequirement("A", Version.createOSGi(1, 1, 1), true, NO_REQUIRES, metaReqb); IProvidedCapability act2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", DEFAULT_VERSION); IInstallableUnit act2 = createIU("Action2", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IProvidedCapability act1v2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", new Version(2, 0, 0)); - IInstallableUnit act1v2 = createIU("Action1", new Version("2.0.0"), null, NO_REQUIRES, new IProvidedCapability[] {act1v2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); + IProvidedCapability act1v2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", Version.createOSGi(2, 0, 0)); + IInstallableUnit act1v2 = createIU("Action1", Version.create("2.0.0"), null, NO_REQUIRES, new IProvidedCapability[] {act1v2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReqd = createRequiredCapabilities("p2.action", "action2", new VersionRange("[2.0.0, 2.0.0]"), null); + IRequiredCapability[] metaReqd = createRequiredCapabilities("p2.action", "action2", new VersionRange("[2.0.0, 2.0.0]")); IInstallableUnit d = createIUWithMetaRequirement("D", DEFAULT_VERSION, true, NO_REQUIRES, metaReqd); - IRequiredCapability[] metaReq2 = createRequiredCapabilities("p2.action", "action2", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq2 = createRequiredCapabilities("p2.action", "action2", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit b = createIUWithMetaRequirement("B", DEFAULT_VERSION, true, NO_REQUIRES, metaReq2); IInstallableUnit c = createEclipseIU("C"); @@ -247,27 +242,27 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { //install A which will install Action1 ProfileChangeRequest request = new ProfileChangeRequest(getProfile("installation")); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); - assertOK("install actions for A", engine.perform(getProfile("agent"), new DefaultPhaseSet(), plan.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + assertOK("install actions for A", engine.perform(plan.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act1}); - assertOK("install A", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan.getOperands(), null, null)); + assertOK("install A", engine.perform(plan, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("installation"), new IInstallableUnit[] {a}); //install B which will install Action2 ProfileChangeRequest request2 = new ProfileChangeRequest(getProfile("installation")); request2.addInstallableUnits(new IInstallableUnit[] {b}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); - assertOK("install actions for B", engine.perform(getProfile("agent"), new DefaultPhaseSet(), plan2.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); + assertOK("install actions for B", engine.perform(plan2.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act2}); - assertOK("install B", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan2.getOperands(), null, null)); + assertOK("install B", engine.perform(plan2, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("installation"), new IInstallableUnit[] {b, a}); //install C ProfileChangeRequest requestForC = new ProfileChangeRequest(getProfile("installation")); requestForC.addInstallableUnits(new IInstallableUnit[] {c}); - ProvisioningPlan planForC = planner.getProvisioningPlan(requestForC, ctx, new NullProgressMonitor()); + IProvisioningPlan planForC = planner.getProvisioningPlan(requestForC, ctx, new NullProgressMonitor()); assertNull(planForC.getInstallerPlan()); - assertOK("install C", engine.perform(getProfile("installation"), new DefaultPhaseSet(), planForC.getOperands(), null, null)); + assertOK("install C", engine.perform(planForC, null)); assertProfileContainsAll("Checking profile after C", getProfile("installation"), new IInstallableUnit[] {a, b, c}); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act2, act1}); @@ -275,42 +270,41 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { ProfileChangeRequest requestUpdateA = new ProfileChangeRequest(getProfile("installation")); requestUpdateA.removeInstallableUnits(new IInstallableUnit[] {a}); requestUpdateA.addInstallableUnits(new IInstallableUnit[] {a111}); - ProvisioningPlan planUpdateA = planner.getProvisioningPlan(requestUpdateA, ctx, new NullProgressMonitor()); - assertOK("install actions for A 1.1.1", engine.perform(getProfile("agent"), new DefaultPhaseSet(), planUpdateA.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan planUpdateA = planner.getProvisioningPlan(requestUpdateA, ctx, new NullProgressMonitor()); + assertOK("install actions for A 1.1.1", engine.perform(planUpdateA.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act1, act1b, act2}); - assertOK("install A", engine.perform(getProfile("installation"), new DefaultPhaseSet(), planUpdateA.getOperands(), null, null)); + assertOK("install A", engine.perform(planUpdateA, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("installation"), new IInstallableUnit[] {a111, b, c}); - assertEquals(0, getProfile("installation").query(new InstallableUnitQuery("Action1", DEFAULT_VERSION), new Collector(), null).size()); - assertEquals(requestUpdateA, planUpdateA.getProfileChangeRequest()); - assertEquals(getProfile("agent").getProfileId(), plan.getInstallerPlan().getProfileChangeRequest().getProfile().getProfileId()); + assertTrue(getProfile("installation").query(new InstallableUnitQuery("Action1", DEFAULT_VERSION), null).isEmpty()); + assertEquals(getProfile("agent").getProfileId(), plan.getInstallerPlan().getProfile().getProfileId()); //uninstall A ProfileChangeRequest request3 = new ProfileChangeRequest(getProfile("installation")); request3.removeInstallableUnits(new IInstallableUnit[] {a111}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(request3, ctx, new NullProgressMonitor()); + IProvisioningPlan plan3 = planner.getProvisioningPlan(request3, ctx, new NullProgressMonitor()); // assertOK("install actions", engine.perform(getProfile("agent"), new DefaultPhaseSet(), plan3.getInstallerPlan().getOperands(), null, null)); // assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act1b}); //At this point there is not - assertOK("install A", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan3.getOperands(), null, null)); + assertOK("install A", engine.perform(plan3, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("installation"), new IInstallableUnit[] {c, b}); //uninstall C ProfileChangeRequest request4 = new ProfileChangeRequest(getProfile("installation")); request4.removeInstallableUnits(new IInstallableUnit[] {c}); - ProvisioningPlan uninstallC = planner.getProvisioningPlan(request4, ctx, new NullProgressMonitor()); + IProvisioningPlan uninstallC = planner.getProvisioningPlan(request4, ctx, new NullProgressMonitor()); assertNull(uninstallC.getInstallerPlan()); - assertOK("install C", engine.perform(getProfile("installation"), new DefaultPhaseSet(), uninstallC.getOperands(), null, null)); + assertOK("install C", engine.perform(uninstallC, null)); assertProfileContainsAll("Checking profile after C", getProfile("installation"), new IInstallableUnit[] {b}); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act2, act1b}); //install D, This will cause the removal of act1 and cause the addition of act1v2 from the installer ProfileChangeRequest requestForD = new ProfileChangeRequest(getProfile("installation")); requestForD.addInstallableUnits(new IInstallableUnit[] {d}); - ProvisioningPlan planForD = planner.getProvisioningPlan(requestForD, ctx, new NullProgressMonitor()); + IProvisioningPlan planForD = planner.getProvisioningPlan(requestForD, ctx, new NullProgressMonitor()); assertNotNull(planForD.getInstallerPlan()); - assertEquals(1, planForD.getInstallerPlan().getRemovals().query(new InstallableUnitQuery(act1b.getId()), new Collector(), null).size()); - assertOK("install actions", engine.perform(getProfile("agent"), new DefaultPhaseSet(), planForD.getInstallerPlan().getOperands(), null, null)); + assertEquals(1, queryResultSize(planForD.getInstallerPlan().getRemovals().query(new InstallableUnitQuery(act1b.getId()), null))); + assertOK("install actions", engine.perform(planForD.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act1v2}); - assertOK("install D", engine.perform(getProfile("installation"), new DefaultPhaseSet(), planForD.getOperands(), null, null)); + assertOK("install D", engine.perform(planForD, null)); assertProfileContainsAll("Checking profile after D", getProfile("installation"), new IInstallableUnit[] {b, d}); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act2, act1v2}); } @@ -319,13 +313,13 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); - IProvidedCapability act1v2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", new Version(2, 0, 0)); - IInstallableUnit act1v2 = createIU("Action1", new Version("2.0.0"), null, NO_REQUIRES, new IProvidedCapability[] {act1v2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); + IProvidedCapability act1v2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", Version.createOSGi(2, 0, 0)); + IInstallableUnit act1v2 = createIU("Action1", Version.create("2.0.0"), null, NO_REQUIRES, new IProvidedCapability[] {act1v2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReqd = createRequiredCapabilities("p2.action", "action2", new VersionRange("[2.0.0, 2.0.0]"), null); + IRequiredCapability[] metaReqd = createRequiredCapabilities("p2.action", "action2", new VersionRange("[2.0.0, 2.0.0]")); IInstallableUnit d = createIUWithMetaRequirement("D", DEFAULT_VERSION, true, NO_REQUIRES, metaReqd); createTestMetdataRepository(new IInstallableUnit[] {a, act1, d, act1v2}); @@ -336,9 +330,8 @@ public class AgentPlanTestInExternalInstance extends AbstractProvisioningTest { ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {a, d}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); assertNotOK(plan.getStatus()); - assertEquals(request, plan.getProfileChangeRequest()); - assertEquals(getProfile("agent").getProfileId(), plan.getInstallerPlan().getProfileChangeRequest().getProfile().getProfileId()); + assertEquals(getProfile("agent").getProfileId(), plan.getInstallerPlan().getProfile().getProfileId()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AgentPlanTestInExternalInstanceForCohostedMode.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AgentPlanTestInExternalInstanceForCohostedMode.java index cefff2e34..0b100dc04 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AgentPlanTestInExternalInstanceForCohostedMode.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AgentPlanTestInExternalInstanceForCohostedMode.java @@ -8,30 +8,25 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.lang.reflect.Field; import java.net.URI; import java.util.Properties; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; -import org.eclipse.equinox.p2.tests.TestActivator; public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProvisioningTest { - Object previousSelfValue = null; - public void setUp() throws Exception { super.setUp(); - SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) getProfileRegistry(); try { Field selfField = SimpleProfileRegistry.class.getDeclaredField("self"); //$NON-NLS-1$ selfField.setAccessible(true); @@ -44,11 +39,11 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv createProfile("agent"); Properties p = new Properties(); p.setProperty("org.eclipse.equinox.p2.planner.resolveMetaRequirements", "true"); - createProfile("installation", null, p); + createProfile("installation", p); } public void tearDown() throws Exception { - SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) getProfileRegistry(); try { Field selfField = SimpleProfileRegistry.class.getDeclaredField("self"); //$NON-NLS-1$ selfField.setAccessible(true); @@ -63,7 +58,7 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv } public void testGetAgentPlanActionNeededButUnavailable() { - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); IProfile profile = getProfile("installation"); @@ -73,7 +68,7 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv request.addInstallableUnits(new IInstallableUnit[] {a}); ProvisioningContext context = new ProvisioningContext(new URI[0]); - ProvisioningPlan plan = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); assertNotOK(plan.getStatus()); } @@ -81,7 +76,7 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); createTestMetdataRepository(new IInstallableUnit[] {a, act1}); @@ -91,7 +86,7 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); assertTrue(plan.getStatus().isOK()); assertNotNull(plan.getInstallerPlan()); } @@ -100,10 +95,10 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv //This tests the case where the action is in conflict with the thing being installed //The action needs another version of A which is singleton IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); - IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 2.0.0]"), null), new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 2.0.0]")), new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); - IInstallableUnit a2 = createIU("A", new Version(2, 0, 0)); + IInstallableUnit a2 = createIU("A", Version.createOSGi(2, 0, 0)); createTestMetdataRepository(new IInstallableUnit[] {a, a2, act1}); @@ -113,7 +108,7 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); assertNotOK(plan.getStatus()); } @@ -121,7 +116,7 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); IInstallableUnit b = createEclipseIU("B"); @@ -133,19 +128,19 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv ProfileChangeRequest request = new ProfileChangeRequest(getProfile("installation")); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); //Check that the actions are installed properly - assertOK("install actions", engine.perform(getProfile("agent"), new DefaultPhaseSet(), plan.getInstallerPlan().getOperands(), null, null)); + assertOK("install actions", engine.perform(plan.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act1}); //Check that the IUs are installed in the profile - assertOK("install A", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan.getOperands(), null, null)); + assertOK("install A", engine.perform(plan, null)); assertProfileContainsAll("Checking profile after initial install", getProfile("installation"), new IInstallableUnit[] {a, act1}); ProfileChangeRequest request2 = new ProfileChangeRequest(getProfile("installation")); request2.addInstallableUnits(new IInstallableUnit[] {b}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); + IProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); assertNull(plan2.getInstallerPlan()); - assertOK("install b", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan2.getOperands(), null, null)); + assertOK("install b", engine.perform(plan2, null)); assertProfileContainsAll("Checking profile after initial install", getProfile("installation"), new IInstallableUnit[] {a, b, act1}); assertProfileContainsAll("Checking actions are still installed", getProfile("agent"), new IInstallableUnit[] {act1}); } @@ -153,10 +148,10 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv public void testWithOveralInDependency() { IInstallableUnit common = createEclipseIU("Common"); IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); - IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "Common", null), new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); + IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "Common"), new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); - IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "Common", null), metaReq); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); + IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "Common"), metaReq); createTestMetdataRepository(new IInstallableUnit[] {a, act1, common}); @@ -167,10 +162,10 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); - assertOK("install actions", engine.perform(getProfile("agent"), new DefaultPhaseSet(), plan.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + assertOK("install actions", engine.perform(plan.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act1, common}); - assertOK("install A", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan.getOperands(), null, null)); + assertOK("install A", engine.perform(plan, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("installation"), new IInstallableUnit[] {a, common, act1}); } @@ -178,13 +173,13 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); IProvidedCapability act2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", DEFAULT_VERSION); IInstallableUnit act2 = createIU("Action2", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq2 = createRequiredCapabilities("p2.action", "action2", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq2 = createRequiredCapabilities("p2.action", "action2", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit b = createIUWithMetaRequirement("B", DEFAULT_VERSION, true, NO_REQUIRES, metaReq2); createTestMetdataRepository(new IInstallableUnit[] {a, b, act1, act2,}); @@ -196,19 +191,19 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv //install A which will install Action1 ProfileChangeRequest request = new ProfileChangeRequest(getProfile("installation")); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); - assertOK("install actions", engine.perform(getProfile("agent"), new DefaultPhaseSet(), plan.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + assertOK("install actions", engine.perform(plan.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act1}); - assertOK("install A", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan.getOperands(), null, null)); + assertOK("install A", engine.perform(plan, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("installation"), new IInstallableUnit[] {a, act1}); //install B which will install Action2 ProfileChangeRequest request2 = new ProfileChangeRequest(getProfile("installation")); request2.addInstallableUnits(new IInstallableUnit[] {b}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); - assertOK("install actions", engine.perform(getProfile("agent"), new DefaultPhaseSet(), plan2.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); + assertOK("install actions", engine.perform(plan2.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act2, act1}); - assertOK("install A", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan2.getOperands(), null, null)); + assertOK("install A", engine.perform(plan2, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("installation"), new IInstallableUnit[] {b, a, act1, act2}); } @@ -216,25 +211,25 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); IProvidedCapability act1bCap = MetadataFactory.createProvidedCapability("p2.action", "action1b", DEFAULT_VERSION); IInstallableUnit act1b = createIU("Action1b", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1bCap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReqb = createRequiredCapabilities("p2.action", "action1b", new VersionRange("[0.0.0, 1.0.0]"), null); - IInstallableUnit a111 = createIUWithMetaRequirement("A", new Version(1, 1, 1), true, NO_REQUIRES, metaReqb); + IRequiredCapability[] metaReqb = createRequiredCapabilities("p2.action", "action1b", new VersionRange("[0.0.0, 1.0.0]")); + IInstallableUnit a111 = createIUWithMetaRequirement("A", Version.createOSGi(1, 1, 1), true, NO_REQUIRES, metaReqb); IProvidedCapability act2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", DEFAULT_VERSION); IInstallableUnit act2 = createIU("Action2", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IProvidedCapability act1v2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", new Version(2, 0, 0)); - IInstallableUnit act1v2 = createIU("Action1", new Version("2.0.0"), null, NO_REQUIRES, new IProvidedCapability[] {act1v2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); + IProvidedCapability act1v2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", Version.createOSGi(2, 0, 0)); + IInstallableUnit act1v2 = createIU("Action1", Version.create("2.0.0"), null, NO_REQUIRES, new IProvidedCapability[] {act1v2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReqd = createRequiredCapabilities("p2.action", "action2", new VersionRange("[2.0.0, 2.0.0]"), null); + IRequiredCapability[] metaReqd = createRequiredCapabilities("p2.action", "action2", new VersionRange("[2.0.0, 2.0.0]")); IInstallableUnit d = createIUWithMetaRequirement("D", DEFAULT_VERSION, true, NO_REQUIRES, metaReqd); - IRequiredCapability[] metaReq2 = createRequiredCapabilities("p2.action", "action2", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq2 = createRequiredCapabilities("p2.action", "action2", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit b = createIUWithMetaRequirement("B", DEFAULT_VERSION, true, NO_REQUIRES, metaReq2); IInstallableUnit c = createEclipseIU("C"); @@ -247,27 +242,27 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv //install A which will install Action1 ProfileChangeRequest request = new ProfileChangeRequest(getProfile("installation")); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); - assertOK("install actions for A", engine.perform(getProfile("agent"), new DefaultPhaseSet(), plan.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + assertOK("install actions for A", engine.perform(plan.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act1}); - assertOK("install A", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan.getOperands(), null, null)); + assertOK("install A", engine.perform(plan, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("installation"), new IInstallableUnit[] {a, act1}); //install B which will install Action2 ProfileChangeRequest request2 = new ProfileChangeRequest(getProfile("installation")); request2.addInstallableUnits(new IInstallableUnit[] {b}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); - assertOK("install actions for B", engine.perform(getProfile("agent"), new DefaultPhaseSet(), plan2.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); + assertOK("install actions for B", engine.perform(plan2.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act2}); - assertOK("install B", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan2.getOperands(), null, null)); + assertOK("install B", engine.perform(plan2, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("installation"), new IInstallableUnit[] {b, a, act2}); //install C ProfileChangeRequest requestForC = new ProfileChangeRequest(getProfile("installation")); requestForC.addInstallableUnits(new IInstallableUnit[] {c}); - ProvisioningPlan planForC = planner.getProvisioningPlan(requestForC, ctx, new NullProgressMonitor()); + IProvisioningPlan planForC = planner.getProvisioningPlan(requestForC, ctx, new NullProgressMonitor()); assertNull(planForC.getInstallerPlan()); - assertOK("install C", engine.perform(getProfile("installation"), new DefaultPhaseSet(), planForC.getOperands(), null, null)); + assertOK("install C", engine.perform(planForC, null)); assertProfileContainsAll("Checking profile after C", getProfile("installation"), new IInstallableUnit[] {a, b, c, act2, act1}); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act2, act1}); @@ -275,42 +270,41 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv ProfileChangeRequest requestUpdateA = new ProfileChangeRequest(getProfile("installation")); requestUpdateA.removeInstallableUnits(new IInstallableUnit[] {a}); requestUpdateA.addInstallableUnits(new IInstallableUnit[] {a111}); - ProvisioningPlan planUpdateA = planner.getProvisioningPlan(requestUpdateA, ctx, new NullProgressMonitor()); - assertOK("install actions for A 1.1.1", engine.perform(getProfile("agent"), new DefaultPhaseSet(), planUpdateA.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan planUpdateA = planner.getProvisioningPlan(requestUpdateA, ctx, new NullProgressMonitor()); + assertOK("install actions for A 1.1.1", engine.perform(planUpdateA.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act1, act1b, act2}); - assertOK("install A", engine.perform(getProfile("installation"), new DefaultPhaseSet(), planUpdateA.getOperands(), null, null)); + assertOK("install A", engine.perform(planUpdateA, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("installation"), new IInstallableUnit[] {act2, act1b, a111, b, c}); - assertEquals(0, getProfile("installation").query(new InstallableUnitQuery("Action1", DEFAULT_VERSION), new Collector(), null).size()); - assertEquals(requestUpdateA, planUpdateA.getProfileChangeRequest()); - assertEquals(getProfile("agent").getProfileId(), plan.getInstallerPlan().getProfileChangeRequest().getProfile().getProfileId()); + assertTrue(getProfile("installation").query(new InstallableUnitQuery("Action1", DEFAULT_VERSION), null).isEmpty()); + assertEquals(getProfile("agent").getProfileId(), plan.getInstallerPlan().getProfile().getProfileId()); //uninstall A ProfileChangeRequest request3 = new ProfileChangeRequest(getProfile("installation")); request3.removeInstallableUnits(new IInstallableUnit[] {a111}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(request3, ctx, new NullProgressMonitor()); + IProvisioningPlan plan3 = planner.getProvisioningPlan(request3, ctx, new NullProgressMonitor()); // assertOK("install actions", engine.perform(getProfile("agent"), new DefaultPhaseSet(), plan3.getInstallerPlan().getOperands(), null, null)); // assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act1b}); //At this point there is not - assertOK("install A", engine.perform(getProfile("installation"), new DefaultPhaseSet(), plan3.getOperands(), null, null)); + assertOK("install A", engine.perform(plan3, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("installation"), new IInstallableUnit[] {c, b, act2}); //uninstall C ProfileChangeRequest request4 = new ProfileChangeRequest(getProfile("installation")); request4.removeInstallableUnits(new IInstallableUnit[] {c}); - ProvisioningPlan uninstallC = planner.getProvisioningPlan(request4, ctx, new NullProgressMonitor()); + IProvisioningPlan uninstallC = planner.getProvisioningPlan(request4, ctx, new NullProgressMonitor()); assertNull(uninstallC.getInstallerPlan()); - assertOK("install C", engine.perform(getProfile("installation"), new DefaultPhaseSet(), uninstallC.getOperands(), null, null)); + assertOK("install C", engine.perform(uninstallC, null)); assertProfileContainsAll("Checking profile after C", getProfile("installation"), new IInstallableUnit[] {b, act2}); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act2}); //install D, This will cause the removal of act1 and cause the addition of act1v2 from the installer ProfileChangeRequest requestForD = new ProfileChangeRequest(getProfile("installation")); requestForD.addInstallableUnits(new IInstallableUnit[] {d}); - ProvisioningPlan planForD = planner.getProvisioningPlan(requestForD, ctx, new NullProgressMonitor()); + IProvisioningPlan planForD = planner.getProvisioningPlan(requestForD, ctx, new NullProgressMonitor()); assertNotNull(planForD.getInstallerPlan()); - assertEquals(1, planForD.getInstallerPlan().getRemovals().query(new InstallableUnitQuery(act1b.getId()), new Collector(), null).size()); - assertOK("install actions", engine.perform(getProfile("agent"), new DefaultPhaseSet(), planForD.getInstallerPlan().getOperands(), null, null)); + assertEquals(1, queryResultSize(planForD.getInstallerPlan().getRemovals().query(new InstallableUnitQuery(act1b.getId()), null))); + assertOK("install actions", engine.perform(planForD.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act1v2}); - assertOK("install D", engine.perform(getProfile("installation"), new DefaultPhaseSet(), planForD.getOperands(), null, null)); + assertOK("install D", engine.perform(planForD, null)); assertProfileContainsAll("Checking profile after D", getProfile("installation"), new IInstallableUnit[] {b, d}); assertProfileContainsAll("Checking profile after install of actions", getProfile("agent"), new IInstallableUnit[] {act2, act1v2}); } @@ -319,13 +313,13 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); - IProvidedCapability act1v2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", new Version(2, 0, 0)); - IInstallableUnit act1v2 = createIU("Action1", new Version("2.0.0"), null, NO_REQUIRES, new IProvidedCapability[] {act1v2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); + IProvidedCapability act1v2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", Version.createOSGi(2, 0, 0)); + IInstallableUnit act1v2 = createIU("Action1", Version.create("2.0.0"), null, NO_REQUIRES, new IProvidedCapability[] {act1v2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReqd = createRequiredCapabilities("p2.action", "action2", new VersionRange("[2.0.0, 2.0.0]"), null); + IRequiredCapability[] metaReqd = createRequiredCapabilities("p2.action", "action2", new VersionRange("[2.0.0, 2.0.0]")); IInstallableUnit d = createIUWithMetaRequirement("D", DEFAULT_VERSION, true, NO_REQUIRES, metaReqd); createTestMetdataRepository(new IInstallableUnit[] {a, act1, d, act1v2}); @@ -336,8 +330,8 @@ public class AgentPlanTestInExternalInstanceForCohostedMode extends AbstractProv ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {a, d}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); assertNotOK(plan.getStatus()); - assertEquals(request, plan.getProfileChangeRequest()); + assertEquals(request.getProfile(), plan.getProfile()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AgentPlanTestInRunningInstance.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AgentPlanTestInRunningInstance.java index 4e7b9d9c5..61af3ee7a 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AgentPlanTestInRunningInstance.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AgentPlanTestInRunningInstance.java @@ -8,25 +8,18 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - -import java.lang.reflect.Field; import java.net.URI; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; -import org.eclipse.equinox.p2.tests.TestActivator; public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { private IProfile initialProfile = null; - private Object previousSelfValue = null; public void setUp() throws Exception { super.setUp(); @@ -35,39 +28,16 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { if (initialProfile != null) return; - if (System.getProperty("eclipse.p2.profile") == null) { - SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); - try { - Field selfField = SimpleProfileRegistry.class.getDeclaredField("self"); //$NON-NLS-1$ - selfField.setAccessible(true); - previousSelfValue = selfField.get(profileRegistry); - if (previousSelfValue == null) - selfField.set(profileRegistry, "agent"); - } catch (Throwable t) { - fail(); - } - } - createProfile("agent"); + setUpSelfProfile(); } public void tearDown() throws Exception { if (initialProfile == null) { - if (System.getProperty("eclipse.p2.profile") == null) { - SimpleProfileRegistry profileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); - try { - Field selfField = SimpleProfileRegistry.class.getDeclaredField("self"); //$NON-NLS-1$ - selfField.setAccessible(true); - Object self = selfField.get(profileRegistry); - if (self.equals("agent")) - selfField.set(profileRegistry, previousSelfValue); - } catch (Throwable t) { - // ignore as we still want to continue tidying up - } - } + tearDownSelfProfile(); } else { //After the test we clean up the profile IProfile profileAfterTestRun = getProfile(IProfileRegistry.SELF); - ProvisioningPlan rollbackPlan = createPlanner().getDiffPlan(profileAfterTestRun, initialProfile, new NullProgressMonitor()); + IProvisioningPlan rollbackPlan = createPlanner().getDiffPlan(profileAfterTestRun, initialProfile, new NullProgressMonitor()); assertOK("rollback plan", rollbackPlan.getStatus()); assertOK("rollback execution", PlanExecutionHelper.executePlan(rollbackPlan, createEngine(), new ProvisioningContext(), new NullProgressMonitor())); } @@ -75,7 +45,7 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { } public void testGetAgentPlanActionNeededButUnavailable() { - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); IProfile profile = getProfile(IProfileRegistry.SELF); @@ -85,7 +55,7 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { request.addInstallableUnits(new IInstallableUnit[] {a}); ProvisioningContext context = new ProvisioningContext(new URI[0]); - ProvisioningPlan plan = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); assertNotOK(plan.getStatus()); } @@ -93,7 +63,7 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); createTestMetdataRepository(new IInstallableUnit[] {a, act1}); @@ -103,7 +73,7 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); assertTrue(plan.getStatus().isOK()); assertNotNull(plan.getInstallerPlan()); } @@ -112,11 +82,11 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { //This tests the case where the action is in conflict with the thing being installed //The action needs another version of A which is singleton IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); - IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 2.0.0]"), null), new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); + IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 2.0.0]")), new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); - IInstallableUnit a2 = createIU("A", new Version(2, 0, 0)); + IInstallableUnit a2 = createIU("A", Version.createOSGi(2, 0, 0)); createTestMetdataRepository(new IInstallableUnit[] {a, a2, act1}); IProfile profile = getProfile(IProfileRegistry.SELF); @@ -125,7 +95,7 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); assertNotOK(plan.getStatus()); } @@ -133,7 +103,7 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); IInstallableUnit b = createEclipseIU("B"); @@ -145,19 +115,18 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { ProfileChangeRequest request = new ProfileChangeRequest(getProfile(IProfileRegistry.SELF)); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); - assertOK("install actions", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), plan.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + assertOK("install actions", engine.perform(plan.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {act1}); - assertOK("install A", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), plan.getOperands(), null, null)); + assertOK("install A", engine.perform(plan, null)); assertProfileContainsAll("Checking profile after initial install", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {a, act1}); - assertEquals(request, plan.getProfileChangeRequest()); - assertEquals(getProfile(IProfileRegistry.SELF).getProfileId(), plan.getInstallerPlan().getProfileChangeRequest().getProfile().getProfileId()); + assertEquals(getProfile(IProfileRegistry.SELF).getProfileId(), plan.getInstallerPlan().getProfile().getProfileId()); ProfileChangeRequest request2 = new ProfileChangeRequest(getProfile(IProfileRegistry.SELF)); request2.addInstallableUnits(new IInstallableUnit[] {b}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); + IProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); assertNull(plan2.getInstallerPlan()); - assertOK("install b", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), plan2.getOperands(), null, null)); + assertOK("install b", engine.perform(plan2, null)); assertProfileContainsAll("Checking profile after initial install", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {a, act1, b}); } @@ -165,10 +134,10 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { public void testWithOveralInDependency() { IInstallableUnit common = createEclipseIU("Common"); IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); - IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "Common", null), new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); + IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "Common"), new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); - IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "Common", null), metaReq); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); + IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "Common"), metaReq); createTestMetdataRepository(new IInstallableUnit[] {a, act1, common}); @@ -179,10 +148,10 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); - assertOK("install actions", engine.perform(profile, new DefaultPhaseSet(), plan.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + assertOK("install actions", engine.perform(plan.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {act1, common}); - assertOK("install A", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), plan.getOperands(), null, null)); + assertOK("install A", engine.perform(plan, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {a, common, act1}); } @@ -190,13 +159,13 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); IProvidedCapability act2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", DEFAULT_VERSION); IInstallableUnit act2 = createIU("Action2", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq2 = createRequiredCapabilities("p2.action", "action2", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq2 = createRequiredCapabilities("p2.action", "action2", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit b = createIUWithMetaRequirement("B", DEFAULT_VERSION, true, NO_REQUIRES, metaReq2); createTestMetdataRepository(new IInstallableUnit[] {a, b, act1, act2,}); @@ -209,19 +178,19 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { //install A which will install Action1 ProfileChangeRequest request = new ProfileChangeRequest(getProfile(IProfileRegistry.SELF)); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); - assertOK("install actions", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), plan.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + assertOK("install actions", engine.perform(plan.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {act1}); - assertOK("install A", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), plan.getOperands(), null, null)); + assertOK("install A", engine.perform(plan, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {a, act1}); //install B which will install Action2 ProfileChangeRequest request2 = new ProfileChangeRequest(getProfile(IProfileRegistry.SELF)); request2.addInstallableUnits(new IInstallableUnit[] {b}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); - assertOK("install actions", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), plan2.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); + assertOK("install actions", engine.perform(plan2.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {act2, act1, a}); - assertOK("install A", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), plan2.getOperands(), null, null)); + assertOK("install A", engine.perform(plan2, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {act2, act1, b, a}); } @@ -229,19 +198,19 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); IProvidedCapability act1bCap = MetadataFactory.createProvidedCapability("p2.action", "action1b", DEFAULT_VERSION); IInstallableUnit act1b = createIU("Action1b", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1bCap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReqb = createRequiredCapabilities("p2.action", "action1b", new VersionRange("[0.0.0, 1.0.0]"), null); - IInstallableUnit a111 = createIUWithMetaRequirement("A", new Version(1, 1, 1), true, NO_REQUIRES, metaReqb); + IRequiredCapability[] metaReqb = createRequiredCapabilities("p2.action", "action1b", new VersionRange("[0.0.0, 1.0.0]")); + IInstallableUnit a111 = createIUWithMetaRequirement("A", Version.createOSGi(1, 1, 1), true, NO_REQUIRES, metaReqb); IProvidedCapability act2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", DEFAULT_VERSION); IInstallableUnit act2 = createIU("Action2", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq2 = createRequiredCapabilities("p2.action", "action2", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq2 = createRequiredCapabilities("p2.action", "action2", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit b = createIUWithMetaRequirement("B", DEFAULT_VERSION, true, NO_REQUIRES, metaReq2); IInstallableUnit c = createEclipseIU("C"); @@ -254,27 +223,27 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { //install A which will install Action1 ProfileChangeRequest request = new ProfileChangeRequest(getProfile(IProfileRegistry.SELF)); request.addInstallableUnits(new IInstallableUnit[] {a}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); - assertOK("install actions for A", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), plan.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + assertOK("install actions for A", engine.perform(plan.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {act1}); - assertOK("install A", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), plan.getOperands(), null, null)); + assertOK("install A", engine.perform(plan, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {a, act1}); //install B which will install Action2 ProfileChangeRequest request2 = new ProfileChangeRequest(getProfile(IProfileRegistry.SELF)); request2.addInstallableUnits(new IInstallableUnit[] {b}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); - assertOK("install actions for B", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), plan2.getInstallerPlan().getOperands(), null, null)); + IProvisioningPlan plan2 = planner.getProvisioningPlan(request2, ctx, new NullProgressMonitor()); + assertOK("install actions for B", engine.perform(plan2.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {act2, act1, a}); - assertOK("install B", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), plan2.getOperands(), null, null)); + assertOK("install B", engine.perform(plan2, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {act2, act1, b, a}); //install C ProfileChangeRequest requestForC = new ProfileChangeRequest(getProfile(IProfileRegistry.SELF)); requestForC.addInstallableUnits(new IInstallableUnit[] {c}); - ProvisioningPlan planForC = planner.getProvisioningPlan(requestForC, ctx, new NullProgressMonitor()); + IProvisioningPlan planForC = planner.getProvisioningPlan(requestForC, ctx, new NullProgressMonitor()); assertNull(planForC.getInstallerPlan()); - assertOK("install C", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), planForC.getOperands(), null, null)); + assertOK("install C", engine.perform(planForC, null)); assertProfileContainsAll("Checking profile after C", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {act1, act2, a, b, c}); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {act2, act1, b, a}); @@ -282,22 +251,22 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { ProfileChangeRequest requestUpdateA = new ProfileChangeRequest(getProfile(IProfileRegistry.SELF)); requestUpdateA.removeInstallableUnits(new IInstallableUnit[] {a}); requestUpdateA.addInstallableUnits(new IInstallableUnit[] {a111}); - ProvisioningPlan planUpdateA = planner.getProvisioningPlan(requestUpdateA, ctx, new NullProgressMonitor()); + IProvisioningPlan planUpdateA = planner.getProvisioningPlan(requestUpdateA, ctx, new NullProgressMonitor()); assertOK("Checking planUpdateA", planUpdateA.getStatus()); - assertOK("install actions for A 1.1.1", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), planUpdateA.getInstallerPlan().getOperands(), null, null)); + assertOK("install actions for A 1.1.1", engine.perform(planUpdateA.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {act1, act1b}); - assertOK("install A", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), planUpdateA.getOperands(), null, null)); + assertOK("install A", engine.perform(planUpdateA, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {act1b, a111, b, c}); - assertEquals(0, getProfile(IProfileRegistry.SELF).query(new InstallableUnitQuery("Action1", DEFAULT_VERSION), new Collector(), null).size()); + assertTrue(getProfile(IProfileRegistry.SELF).query(new InstallableUnitQuery("Action1", DEFAULT_VERSION), null).isEmpty()); //uninstall A ProfileChangeRequest request3 = new ProfileChangeRequest(getProfile(IProfileRegistry.SELF)); request3.removeInstallableUnits(new IInstallableUnit[] {a111}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(request3, ctx, new NullProgressMonitor()); + IProvisioningPlan plan3 = planner.getProvisioningPlan(request3, ctx, new NullProgressMonitor()); // assertNull(plan3.getInstallerPlan()); //TODO - assertOK("install actions", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), plan3.getInstallerPlan().getOperands(), null, null)); + assertOK("install actions", engine.perform(plan3.getInstallerPlan(), null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {act1b}); //At this point there is not - assertOK("install A", engine.perform(getProfile(IProfileRegistry.SELF), new DefaultPhaseSet(), plan3.getOperands(), null, null)); + assertOK("install A", engine.perform(plan3, null)); assertProfileContainsAll("Checking profile after install of actions", getProfile(IProfileRegistry.SELF), new IInstallableUnit[] {c, b, act2}); } @@ -305,13 +274,13 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); - IProvidedCapability act1v2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", new Version(2, 0, 0)); - IInstallableUnit act1v2 = createIU("Action1", new Version("2.0.0"), null, NO_REQUIRES, new IProvidedCapability[] {act1v2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); + IProvidedCapability act1v2Cap = MetadataFactory.createProvidedCapability("p2.action", "action2", Version.createOSGi(2, 0, 0)); + IInstallableUnit act1v2 = createIU("Action1", Version.create("2.0.0"), null, NO_REQUIRES, new IProvidedCapability[] {act1v2Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReqd = createRequiredCapabilities("p2.action", "action2", new VersionRange("[2.0.0, 2.0.0]"), null); + IRequiredCapability[] metaReqd = createRequiredCapabilities("p2.action", "action2", new VersionRange("[2.0.0, 2.0.0]")); IInstallableUnit d = createIUWithMetaRequirement("D", DEFAULT_VERSION, true, NO_REQUIRES, metaReqd); createTestMetdataRepository(new IInstallableUnit[] {a, act1, d, act1v2}); @@ -322,7 +291,7 @@ public class AgentPlanTestInRunningInstance extends AbstractProvisioningTest { ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {a, d}); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); assertNotOK(plan.getStatus()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllOptional.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllOptional.java index 7f5bb5e44..61ab19151 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllOptional.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllOptional.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class AllOptional extends AbstractProvisioningTest { @@ -28,16 +32,16 @@ public class AllOptional extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - IRequiredCapability[] reqA = new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, true)}; - a1 = createIU("A", new Version("1.0.0"), reqA); - b1 = createIU("B", new Version("1.0.0"), true); + IRequiredCapability[] reqA = new IRequiredCapability[] {(IRequiredCapability) MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, true)}; + a1 = createIU("A", Version.create("1.0.0"), reqA); + b1 = createIU("B", Version.create("1.0.0"), true); IRequiredCapability[] reqC = new IRequiredCapability[2]; - reqC[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", VersionRange.emptyRange, null, true, false, true); - reqC[1] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "E", VersionRange.emptyRange, null, true, false, true); - c1 = createIU("C", new Version("1.0.0"), reqC); - d1 = createIU("D", new Version("1.0.0"), true); - e1 = createIU("E", new Version("1.0.0"), true); + reqC[0] = (IRequiredCapability) MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", VersionRange.emptyRange, null, true, false, true); + reqC[1] = (IRequiredCapability) MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "E", VersionRange.emptyRange, null, true, false, true); + c1 = createIU("C", Version.create("1.0.0"), reqC); + d1 = createIU("D", Version.create("1.0.0"), true); + e1 = createIU("E", Version.create("1.0.0"), true); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, c1, d1, e1}); @@ -48,7 +52,7 @@ public class AllOptional extends AbstractProvisioningTest { public void testInstallation() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1, c1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, a1); assertInstallOperand(plan, b1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllOrbit.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllOrbit.java index 68e86b52d..ad24ab23e 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllOrbit.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllOrbit.java @@ -15,12 +15,12 @@ import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; @@ -32,7 +32,7 @@ public class AllOrbit extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - IMetadataRepositoryManager repoMan = (MetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager repoMan = (MetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); repo = repoMan.loadRepository(getTestData("repository for wsdl test", "testData/orbitRepo/").toURI(), new NullProgressMonitor()); profile1 = createProfile("TestProfile." + getName()); @@ -42,29 +42,22 @@ public class AllOrbit extends AbstractProvisioningTest { public void testInstallTwoVersionsOptionaly() { ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); - Collector allIUs = repo.query(InstallableUnitQuery.ANY, new Collector(), null); + IQueryResult allIUs = repo.query(InstallableUnitQuery.ANY, null); req1.addInstallableUnits((IInstallableUnit[]) allIUs.toArray(IInstallableUnit.class)); for (Iterator iterator = allIUs.iterator(); iterator.hasNext();) { IInstallableUnit iu = (IInstallableUnit) iterator.next(); if (!iu.getId().equals("javax.wsdl")) req1.setInstallableUnitInclusionRules(iu, PlannerHelper.createOptionalInclusionRule(iu)); } - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); - Operand[] ops = plan1.getOperands(); - int count = 0; - for (int i = 0; i < ops.length; i++) { - if (ops[i] instanceof InstallableUnitOperand) { - count++; - } - } + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.OK, plan1.getStatus().getSeverity()); } public void test2() { //Install everything except com.ibm.icu ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); - Collector allIUs = repo.query(InstallableUnitQuery.ANY, new Collector(), null); - ArrayList toInstall = new ArrayList(allIUs.size()); + IQueryResult allIUs = repo.query(InstallableUnitQuery.ANY, null); + ArrayList toInstall = new ArrayList(); int removed = 0; for (Iterator iterator = allIUs.iterator(); iterator.hasNext();) { IInstallableUnit toAdd = (IInstallableUnit) iterator.next(); @@ -75,23 +68,16 @@ public class AllOrbit extends AbstractProvisioningTest { } req1.addInstallableUnits((IInstallableUnit[]) toInstall.toArray(new IInstallableUnit[toInstall.size()])); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); - Operand[] ops = plan1.getOperands(); - int count = 0; - for (int i = 0; i < ops.length; i++) { - if (ops[i] instanceof InstallableUnitOperand) { - count++; - } - } - assertEquals(178, count); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + assertEquals(178, countPlanElements(plan1)); assertEquals(IStatus.OK, plan1.getStatus().getSeverity()); } public void test3() { //Install everything optionaly (except com.ibm.icu that we don't install at all) ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); - Collector allIUs = repo.query(InstallableUnitQuery.ANY, new Collector(), null); - ArrayList toInstall = new ArrayList(allIUs.size()); + IQueryResult allIUs = repo.query(InstallableUnitQuery.ANY, null); + ArrayList toInstall = new ArrayList(); int removed = 0; for (Iterator iterator = allIUs.iterator(); iterator.hasNext();) { IInstallableUnit toAdd = (IInstallableUnit) iterator.next(); @@ -103,15 +89,8 @@ public class AllOrbit extends AbstractProvisioningTest { } req1.addInstallableUnits((IInstallableUnit[]) toInstall.toArray(new IInstallableUnit[toInstall.size()])); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); - Operand[] ops = plan1.getOperands(); - int count = 0; - for (int i = 0; i < ops.length; i++) { - if (ops[i] instanceof InstallableUnitOperand) { - count++; - } - } - assertEquals(178, count); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + assertEquals(178, countPlanElements(plan1)); assertEquals(IStatus.OK, plan1.getStatus().getSeverity()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllTests.java index 8da13e016..c2555de8d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllTests.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllTests.java @@ -19,6 +19,7 @@ public class AllTests extends TestCase { public static Test suite() { TestSuite suite = new TestSuite(AllTests.class.getName()); + suite.addTestSuite(AbsolutePlanTest.class); suite.addTestSuite(ActualChangeRequestTest.class); suite.addTestSuite(ActualChangeRequestTest2.class); suite.addTestSuite(AdditionalConstraints.class); @@ -93,6 +94,8 @@ public class AllTests extends TestCase { suite.addTestSuite(PatchTest8.class); suite.addTestSuite(PatchTest9.class); suite.addTestSuite(PatchTestMultiplePatch.class); + suite.addTestSuite(PatchTestMultiplePatch2.class); + suite.addTestSuite(PatchTestMultiplePatch3.class); suite.addTestSuite(PatchTestOptional.class); suite.addTestSuite(PatchTestOptional2.class); suite.addTestSuite(PatchTestOptional3.class); @@ -121,6 +124,7 @@ public class AllTests extends TestCase { suite.addTestSuite(SWTFragment.class); suite.addTestSuite(TwoVersionsOfWSDL.class); suite.addTestSuite(UninstallEverything.class); + suite.addTestSuite(UpdateQueryTest.class); return suite; } } \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AnotherSingleton.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AnotherSingleton.java index cf294e904..cb6ecc3cb 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AnotherSingleton.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AnotherSingleton.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class AnotherSingleton extends AbstractProvisioningTest { @@ -32,15 +34,15 @@ public class AnotherSingleton extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), true); + a1 = createIU("A", Version.create("1.0.0"), true); - a2 = createIU("A", new Version("2.0.0"), true); + a2 = createIU("A", Version.create("2.0.0"), true); - IRequiredCapability c1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"), null, false, false); - x = createIU("X", new Version(2, 0, 0), new IRequiredCapability[] {c1}); + IRequiredCapability c1 = (IRequiredCapability) MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"), null, false, false); + x = createIU("X", Version.createOSGi(2, 0, 0), new IRequiredCapability[] {c1}); - IRequiredCapability c2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 2.0.0]"), null, false, false); - y = createIU("Y", new Version(2, 0, 0), new IRequiredCapability[] {c2}); + IRequiredCapability c2 = (IRequiredCapability) MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 2.0.0]"), null, false, false); + y = createIU("Y", Version.createOSGi(2, 0, 0), new IRequiredCapability[] {c2}); createTestMetdataRepository(new IInstallableUnit[] {a1, a2, x, y}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug207319.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug207319.java index 29ed90869..6e24f9294 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug207319.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug207319.java @@ -8,16 +8,13 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.provisional.p2.director.IDirector; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class Bug207319 extends AbstractProvisioningTest { @@ -28,9 +25,9 @@ public class Bug207319 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a = createIU("A", new Version("1.0.0")); - b = createIU("B", new Version("1.0.0"), new IProvidedCapability[] {MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new Version("1.0.0"))}); - c = createIU("C", new Version("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"), null)); + a = createIU("A", Version.create("1.0.0")); + b = createIU("B", Version.create("1.0.0"), new IProvidedCapability[] {MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", Version.create("1.0.0"))}); + c = createIU("C", Version.create("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"))); createTestMetdataRepository(new IInstallableUnit[] {a, b, c}); profile = createProfile(Bug207319.class.getName()); director = createDirector(); @@ -42,13 +39,13 @@ public class Bug207319 extends AbstractProvisioningTest { req.addInstallableUnits(new IInstallableUnit[] {b}); assertEquals(IStatus.OK, director.provision(req, null, null).getSeverity()); assertProfileContainsAll("B is missing", profile, new IInstallableUnit[] {b}); - assertNotIUs(new IInstallableUnit[] {a}, profile.query(InstallableUnitQuery.ANY, new Collector(), null).iterator()); + assertNotIUs(new IInstallableUnit[] {a}, profile.query(InstallableUnitQuery.ANY, null).iterator()); ProfileChangeRequest req2 = new ProfileChangeRequest(profile); req2.addInstallableUnits(new IInstallableUnit[] {c}); assertEquals(IStatus.OK, director.provision(req2, null, null).getSeverity()); assertProfileContainsAll("B and C are missing", profile, new IInstallableUnit[] {b, c}); - assertNotIUs(new IInstallableUnit[] {a}, profile.query(InstallableUnitQuery.ANY, new Collector(), null).iterator()); + assertNotIUs(new IInstallableUnit[] {a}, profile.query(InstallableUnitQuery.ANY, null).iterator()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug249605.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug249605.java index 976aca1a9..5738f1770 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug249605.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug249605.java @@ -10,15 +10,19 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.HashMap; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.query.UserVisibleRootQuery; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class Bug249605 extends AbstractProvisioningTest { @@ -32,19 +36,19 @@ public class Bug249605 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - b1 = createIU("B", new Version(1, 1, 0), true); - b2 = createIU("B", new Version(1, 2, 0), true); - b3 = createIU("B", new Version(1, 3, 0), true); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + b1 = createIU("B", Version.createOSGi(1, 1, 0), true); + b2 = createIU("B", Version.createOSGi(1, 2, 0), true); + b3 = createIU("B", Version.createOSGi(1, 3, 0), true); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.2.0)"), null, false, false, true)); - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); IRequirementChange change2 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.2.0, 1.3.0)"), null, false, false, true)); - p2 = createIUPatch("P", new Version("1.2.0"), null, new IRequiredCapability[0], new IProvidedCapability[0], new HashMap(), null, null, true, MetadataFactory.createUpdateDescriptor("P", new VersionRange("[1.0.0, 1.2.0)"), 0, null), new IRequirementChange[] {change2}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null, new IRequiredCapability[0]); + p2 = createIUPatch("P", Version.create("1.2.0"), null, new IRequiredCapability[0], new IProvidedCapability[0], new HashMap(), null, null, true, MetadataFactory.createUpdateDescriptor("P", new VersionRange("[1.0.0, 1.2.0)"), 0, null), new IRequirementChange[] {change2}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null, new IRequiredCapability[0]); IRequirementChange change3 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.3.0, 1.4.0)"), null, false, false, true)); - p3 = createIUPatch("P", new Version("1.3.0"), null, new IRequiredCapability[0], new IProvidedCapability[0], new HashMap(), null, null, true, MetadataFactory.createUpdateDescriptor("P", new VersionRange("[1.0.0, 1.3.0)"), 0, null), new IRequirementChange[] {change3}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null, new IRequiredCapability[0]); + p3 = createIUPatch("P", Version.create("1.3.0"), null, new IRequiredCapability[0], new IProvidedCapability[0], new HashMap(), null, null, true, MetadataFactory.createUpdateDescriptor("P", new VersionRange("[1.0.0, 1.3.0)"), 0, null), new IRequirementChange[] {change3}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null, new IRequiredCapability[0]); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, b2, b3, p1, p2, p3}); @@ -57,28 +61,28 @@ public class Bug249605 extends AbstractProvisioningTest { // The requirement from A to B is broken because there is no B satisfying. Therefore A can only install if the P is installed as well ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {a1, p1}); - req1.setInstallableUnitProfileProperty(p1, IInstallableUnit.PROP_PROFILE_ROOT_IU, Boolean.toString(true)); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + req1.setInstallableUnitProfileProperty(p1, IProfile.PROP_PROFILE_ROOT_IU, Boolean.toString(true)); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.OK, plan1.getStatus().getSeverity()); - assertOK("1.1", engine.perform(profile1, DefaultPhaseSet.createDefaultPhaseSet(0), plan1.getOperands(), null, new NullProgressMonitor())); + assertOK("1.1", engine.perform(plan1, new NullProgressMonitor())); assertProfileContains("1.2", profile1, new IInstallableUnit[] {a1, p1, b1}); ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {p2}); req2.removeInstallableUnits(new IInstallableUnit[] {p1}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, new NullProgressMonitor()); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, new NullProgressMonitor()); assertOK("2.0", plan2.getStatus()); - assertOK("2.1", engine.perform(profile1, DefaultPhaseSet.createDefaultPhaseSet(0), plan2.getOperands(), null, new NullProgressMonitor())); + assertOK("2.1", engine.perform(plan2, new NullProgressMonitor())); assertProfileContains("2.2", profile1, new IInstallableUnit[] {a1, p2, b2}); - assertEquals("true", profile1.getInstallableUnitProperty(p2, IInstallableUnit.PROP_PROFILE_ROOT_IU)); + assertTrue(UserVisibleRootQuery.isUserVisible(p2, profile1)); ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.addInstallableUnits(new IInstallableUnit[] {p3}); req3.removeInstallableUnits(new IInstallableUnit[] {p2}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, new NullProgressMonitor()); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, new NullProgressMonitor()); assertOK("3.0", plan3.getStatus()); - assertOK("3.1", engine.perform(profile1, DefaultPhaseSet.createDefaultPhaseSet(0), plan3.getOperands(), null, new NullProgressMonitor())); + assertOK("3.1", engine.perform(plan3, new NullProgressMonitor())); assertProfileContains("3.2", profile1, new IInstallableUnit[] {a1, p3, b3}); - assertEquals("true", profile1.getInstallableUnitProperty(p3, IInstallableUnit.PROP_PROFILE_ROOT_IU)); + assertTrue(UserVisibleRootQuery.isUserVisible(p3, profile1)); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug252638.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug252638.java index 82556a6aa..895768481 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug252638.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug252638.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; //Failing to install something optionally should indicate the failure in the request status for the IU being installed. @@ -30,10 +32,10 @@ public class Bug252638 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), true); + a1 = createIU("A", Version.create("1.0.0"), true); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequiredCapability lifeCycle = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 3.0.0)"), null, false, false, false); - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle); createTestMetdataRepository(new IInstallableUnit[] {a1, p1}); @@ -45,15 +47,15 @@ public class Bug252638 extends AbstractProvisioningTest { public void testInstall() { ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); - engine.perform(profile1, new DefaultPhaseSet(), plan1.getOperands(), null, null); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + engine.perform(plan1, null); assertProfileContainsAll("1.0", profile1, new IInstallableUnit[] {a1}); assertEquals(IStatus.OK, plan1.getStatus().getSeverity()); ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {p1}); req2.setInstallableUnitInclusionRules(p1, PlannerHelper.createOptionalInclusionRule(p1)); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getCode()); assertEquals(IStatus.ERROR, plan2.getRequestStatus(p1).getSeverity()); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug252682.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug252682.java index 84a7f78c1..5b76c9a89 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug252682.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug252682.java @@ -10,18 +10,18 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import java.util.ArrayList; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class Bug252682 extends AbstractProvisioningTest { @@ -39,22 +39,22 @@ public class Bug252682 extends AbstractProvisioningTest { newIUs.add(createEclipseIU("org.eclipse.equinox.p2.core", Version.createOSGi(1, 0, 100, "v20081024"))); ProfileChangeRequest req = new ProfileChangeRequest(profile); - ProvisioningPlan plan = createPlanner().getProvisioningPlan(req, null, null); + IProvisioningPlan plan = createPlanner().getProvisioningPlan(req, null, null); assertOK("validate profile", plan.getStatus()); } public void testInstallFeaturePatch() { - IInstallableUnit p2Feature = (IInstallableUnit) profile.query(new InstallableUnitQuery("org.eclipse.equinox.p2.user.ui.feature.group"), new Collector(), new NullProgressMonitor()).iterator().next(); + IInstallableUnit p2Feature = (IInstallableUnit) profile.query(new InstallableUnitQuery("org.eclipse.equinox.p2.user.ui.feature.group"), new NullProgressMonitor()).iterator().next(); System.out.println(p2Feature); - Collector c = profile.query(new InstallableUnitQuery("org.eclipse.equinox.p2.core.patch"), new Collector(), new NullProgressMonitor()); - assertEquals(1, c.size()); + IQueryResult c = profile.query(new InstallableUnitQuery("org.eclipse.equinox.p2.core.patch"), new NullProgressMonitor()); + assertEquals(1, queryResultSize(c)); ProvisioningContext ctx = new ProvisioningContext(); ctx.setExtraIUs(newIUs); IInstallableUnit patch = (IInstallableUnit) c.iterator().next(); ProfileChangeRequest request = new ProfileChangeRequest(profile); request.removeInstallableUnits(new IInstallableUnit[] {patch}); IPlanner planner = createPlanner(); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); assertOK("Installation plan", plan.getStatus()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug254481dataSet1.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug254481dataSet1.java index c555c5cd5..70880af3d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug254481dataSet1.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug254481dataSet1.java @@ -14,11 +14,12 @@ import java.io.File; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class Bug254481dataSet1 extends AbstractProvisioningTest { @@ -43,20 +44,20 @@ public class Bug254481dataSet1 extends AbstractProvisioningTest { } public void testInstallFeaturePatch() { - Collector c = repo.query(new InstallableUnitQuery("RPT_ARM_TEST.feature.group"), new Collector(), new NullProgressMonitor()); - assertEquals(1, c.size()); + IQueryResult c = repo.query(new InstallableUnitQuery("RPT_ARM_TEST.feature.group"), new NullProgressMonitor()); + assertEquals(1, queryResultSize(c)); IInstallableUnit patch = (IInstallableUnit) c.iterator().next(); ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {patch}); request.setInstallableUnitInclusionRules(patch, PlannerHelper.createOptionalInclusionRule(patch)); IPlanner planner = createPlanner(); - ProvisioningPlan plan = planner.getProvisioningPlan(request, null, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, null, new NullProgressMonitor()); assertInstallOperand(plan, patch); //[[R]com.ibm.rational.test.lt.arm 7.0.250.v200810021504 --> [R]com.ibm.rational.test.lt.arm 7.0.300.200811041300, - assertEquals(1, plan.getAdditions().query(new InstallableUnitQuery("com.ibm.rational.test.lt.arm"), new Collector(), null).size()); + assertEquals(1, queryResultSize(plan.getAdditions().query(new InstallableUnitQuery("com.ibm.rational.test.lt.arm"), null))); //[R]com.ibm.rational.test.lt.armbroker 7.0.250.v200810021504 --> [R]com.ibm.rational.test.lt.armbroker 7.0.300.200811041300, - assertEquals(1, plan.getAdditions().query(new InstallableUnitQuery("com.ibm.rational.test.lt.armbroker"), new Collector(), null).size()); + assertEquals(1, queryResultSize(plan.getAdditions().query(new InstallableUnitQuery("com.ibm.rational.test.lt.armbroker"), null))); //[R]com.ibm.rational.test.lt.kernel 7.2.151.v200810021605 --> [R]com.ibm.rational.test.lt.kernel 7.2.200.200811041300, - assertEquals(1, plan.getAdditions().query(new InstallableUnitQuery("com.ibm.rational.test.lt.kernel"), new Collector(), null).size()); + assertEquals(1, queryResultSize(plan.getAdditions().query(new InstallableUnitQuery("com.ibm.rational.test.lt.kernel"), null))); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug254481dataSet2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug254481dataSet2.java index 54a71d235..3bcc05187 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug254481dataSet2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug254481dataSet2.java @@ -14,11 +14,12 @@ import java.io.File; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class Bug254481dataSet2 extends AbstractProvisioningTest { @@ -43,16 +44,16 @@ public class Bug254481dataSet2 extends AbstractProvisioningTest { } public void testInstallFeaturePatch() { - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.jdt.feature.patch.feature.group"), new Collector(), new NullProgressMonitor()); - assertEquals(1, c.size()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.jdt.feature.patch.feature.group"), new NullProgressMonitor()); + assertEquals(1, queryResultSize(c)); IInstallableUnit patch = (IInstallableUnit) c.iterator().next(); ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {patch}); request.setInstallableUnitInclusionRules(patch, PlannerHelper.createOptionalInclusionRule(patch)); IPlanner planner = createPlanner(); - ProvisioningPlan plan = planner.getProvisioningPlan(request, null, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, null, new NullProgressMonitor()); assertInstallOperand(plan, patch); - assertEquals(1, plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.jdt.core"), new Collector(), null).size()); - assertEquals(1, plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.jdt.core.manipulation"), new Collector(), null).size()); + assertEquals(1, queryResultSize(plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.jdt.core"), null))); + assertEquals(1, queryResultSize(plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.jdt.core.manipulation"), null))); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug255984.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug255984.java index cbe2b94ca..ab3247e31 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug255984.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug255984.java @@ -10,16 +10,18 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.query.IUProfilePropertyQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class Bug255984 extends AbstractProvisioningTest { @@ -32,9 +34,9 @@ public class Bug255984 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}, NO_PROPERTIES, true); + a = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}, NO_PROPERTIES, true); - b = createIU("B", new Version("1.0.0"), true); + b = createIU("B", Version.create("1.0.0"), true); createTestMetdataRepository(new IInstallableUnit[] {a, b}); @@ -49,32 +51,32 @@ public class Bug255984 extends AbstractProvisioningTest { req.addInstallableUnits(new IInstallableUnit[] {b}); req.setInstallableUnitInclusionRules(b, PlannerHelper.createStrictInclusionRule(b)); req.setInstallableUnitProfileProperty(b, "foo", "bar"); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); - engine.perform(profile1, new DefaultPhaseSet(), plan.getOperands(), null, null); + engine.perform(plan, null); assertProfileContainsAll("B is missing", profile1, new IInstallableUnit[] {b}); - assertEquals(1, profile1.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(1, queryResultSize(profile1.query(InstallableUnitQuery.ANY, null))); //Install A ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {a}); req2.setInstallableUnitInclusionRules(a, PlannerHelper.createStrictInclusionRule(a)); req2.setInstallableUnitProfileProperty(a, "foo", "bar"); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); - engine.perform(profile1, new DefaultPhaseSet(), plan2.getOperands(), null, null); + engine.perform(plan2, null); assertProfileContainsAll("A is missing", profile1, new IInstallableUnit[] {a, b}); - assertEquals(2, profile1.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(2, queryResultSize(profile1.query(InstallableUnitQuery.ANY, null))); //Uninstall B ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.removeInstallableUnits(new IInstallableUnit[] {b}); req3.removeInstallableUnitProfileProperty(b, "foo"); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.OK, plan3.getStatus().getSeverity()); - engine.perform(profile1, new DefaultPhaseSet(), plan3.getOperands(), null, null); + engine.perform(plan3, null); assertProfileContainsAll("A is missing", profile1, new IInstallableUnit[] {a, b}); - assertEquals(1, profile1.query(new IUProfilePropertyQuery("foo", "bar"), new Collector(), new NullProgressMonitor()).size()); - assertEquals(2, profile1.query(InstallableUnitQuery.ANY, new Collector(), null).size()); + assertEquals(1, queryResultSize(profile1.query(new IUProfilePropertyQuery("foo", "bar"), new NullProgressMonitor()))); + assertEquals(2, queryResultSize(profile1.query(InstallableUnitQuery.ANY, null))); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug262580.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug262580.java index 01c58a676..712bdc66a 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug262580.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug262580.java @@ -13,8 +13,8 @@ package org.eclipse.equinox.p2.tests.planner; import java.io.File; import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class Bug262580 extends AbstractProvisioningTest { @@ -31,7 +31,7 @@ public class Bug262580 extends AbstractProvisioningTest { assertNotNull(revertProfile); IPlanner planner = createPlanner(); - ProvisioningPlan plan = planner.getDiffPlan(currentProfile, revertProfile, getMonitor()); + IProvisioningPlan plan = planner.getDiffPlan(currentProfile, revertProfile, getMonitor()); assertTrue(plan.getStatus().isOK()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug270656.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug270656.java index a1b65edff..b6db8c800 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug270656.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug270656.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class Bug270656 extends AbstractProvisioningTest { @@ -32,11 +34,11 @@ public class Bug270656 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, true, true)}); - b12 = createIU("B", new Version(1, 2, 0), true); - b10 = createIU("B", new Version(1, 0, 0), true); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {(IRequiredCapability) MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, true, true)}); + b12 = createIU("B", Version.createOSGi(1, 2, 0), true); + b10 = createIU("B", Version.createOSGi(1, 0, 0), true); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{(IRequiredCapability) MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); createTestMetdataRepository(new IInstallableUnit[] {a1, b10, b12, p1}); @@ -49,7 +51,7 @@ public class Bug270656 extends AbstractProvisioningTest { //The requirement from A to B is broken because there is no B satisfying. Therefore A can only install if the P is installed as well ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {a1, p1}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.OK, plan1.getStatus().getSeverity()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug270683.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug270683.java index e25891895..a722081fc 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug270683.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug270683.java @@ -10,14 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class Bug270683 extends AbstractProvisioningTest { @@ -34,15 +35,15 @@ public class Bug270683 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - b1 = createIU("B", new Version(1, 0, 0), true); - b2 = createIU("B", new Version(1, 2, 0), true); - b3 = createIU("B", new Version(1, 3, 0), true); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + b1 = createIU("B", Version.createOSGi(1, 0, 0), true); + b2 = createIU("B", Version.createOSGi(1, 2, 0), true); + b3 = createIU("B", Version.createOSGi(1, 3, 0), true); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.2.0, 1.2.0]"), null, false, false, true)); - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); IRequirementChange anotherChangeB = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.3.0, 1.3.0]"), null, false, false, true)); - pp1 = createIUPatch("PP", new Version("1.0.0"), true, new IRequirementChange[] {anotherChangeB}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); + pp1 = createIUPatch("PP", Version.create("1.0.0"), true, new IRequirementChange[] {anotherChangeB}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, b2, b3, p1, pp1}); @@ -54,8 +55,8 @@ public class Bug270683 extends AbstractProvisioningTest { public void testExplanationContainsExplicitMentionOfPatch() { ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.addInstallableUnits(new IInstallableUnit[] {a1, p1, pp1}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + ProvisioningPlan plan3 = (ProvisioningPlan) planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.ERROR, plan3.getStatus().getSeverity()); - assertTrue(plan3.getRequestStatus().getExplanations().toString().contains("patched")); + assertTrue(((RequestStatus) plan3.getRequestStatus()).getExplanations().toString().contains("patched")); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug271067.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug271067.java index 5d91e9a75..5fdbf32f1 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug271067.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug271067.java @@ -10,21 +10,20 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import java.lang.reflect.Field; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.internal.provisional.p2.director.PlannerHelper; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; -import org.eclipse.equinox.p2.tests.TestActivator; public class Bug271067 extends AbstractProvisioningTest { private IProfile profile; @@ -37,7 +36,7 @@ public class Bug271067 extends AbstractProvisioningTest { File reporegistry1 = getTestData("test data bug 271067", "testData/bug271067/profileRegistry"); File tempFolder = getTempFolder(); copy("0.2", reporegistry1, tempFolder); - SimpleProfileRegistry realProfileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + SimpleProfileRegistry realProfileRegistry = (SimpleProfileRegistry) getProfileRegistry(); //Tweak the running profile registry Field profileStore = SimpleProfileRegistry.class.getDeclaredField("store"); profileStore.setAccessible(true); @@ -56,7 +55,7 @@ public class Bug271067 extends AbstractProvisioningTest { @Override protected void tearDown() throws Exception { - SimpleProfileRegistry realProfileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + SimpleProfileRegistry realProfileRegistry = (SimpleProfileRegistry) getProfileRegistry(); Field profilesMapField = SimpleProfileRegistry.class.getDeclaredField("profiles"); //$NON-NLS-1$ profilesMapField.setAccessible(true); @@ -69,8 +68,8 @@ public class Bug271067 extends AbstractProvisioningTest { } IInstallableUnit getIU(IMetadataRepository source, String id, String version) { - Collector c = repo.query(new InstallableUnitQuery(id, new Version(version)), new Collector(), new NullProgressMonitor()); - assertEquals(1, c.size()); + IQueryResult c = repo.query(new InstallableUnitQuery(id, Version.create(version)), new NullProgressMonitor()); + assertEquals(1, queryResultSize(c)); return (IInstallableUnit) c.iterator().next(); } @@ -93,9 +92,9 @@ public class Bug271067 extends AbstractProvisioningTest { installFeature1.setInstallableUnitInclusionRules(helloPatch, PlannerHelper.createOptionalInclusionRule(helloPatch)); installFeature1.setInstallableUnitInclusionRules(patchJar, PlannerHelper.createOptionalInclusionRule(patchJar)); - ProvisioningPlan feature1Plan = createPlanner().getProvisioningPlan(installFeature1, new ProvisioningContext(), null); - assertOK("installation of feature1 and patch", createEngine().perform(getProfile(profileLoadedId), new DefaultPhaseSet(), feature1Plan.getOperands(), new ProvisioningContext(), new NullProgressMonitor())); - assertEquals(1, getProfile(profileLoadedId).query(new InstallableUnitQuery("hello", new Version("1.0.0.1")), new Collector(), new NullProgressMonitor()).size()); + IProvisioningPlan feature1Plan = createPlanner().getProvisioningPlan(installFeature1, new ProvisioningContext(), null); + assertOK("installation of feature1 and patch", createEngine().perform(feature1Plan, new NullProgressMonitor())); + assertEquals(1, queryResultSize(getProfile(profileLoadedId).query(new InstallableUnitQuery("hello", Version.create("1.0.0.1")), new NullProgressMonitor()))); IInstallableUnit featureGroup2 = getIU(repo, "hello.feature.2.feature.group", "1.0.0"); IInstallableUnit helloIU2 = getIU(repo, "hello", "1.0.2"); @@ -107,9 +106,9 @@ public class Bug271067 extends AbstractProvisioningTest { installFeature2.setInstallableUnitInclusionRules(helloIU2, PlannerHelper.createOptionalInclusionRule(helloIU2)); installFeature2.setInstallableUnitInclusionRules(featureJar2, PlannerHelper.createOptionalInclusionRule(featureJar2)); - ProvisioningPlan feature2Plan = createPlanner().getProvisioningPlan(installFeature2, new ProvisioningContext(), null); - assertOK("installation of feature2", createEngine().perform(getProfile(profileLoadedId), new DefaultPhaseSet(), feature2Plan.getOperands(), new ProvisioningContext(), new NullProgressMonitor())); - assertEquals(1, getProfile(profileLoadedId).query(new InstallableUnitQuery("hello", new Version("1.0.0.1")), new Collector(), new NullProgressMonitor()).size()); + IProvisioningPlan feature2Plan = createPlanner().getProvisioningPlan(installFeature2, new ProvisioningContext(), null); + assertOK("installation of feature2", createEngine().perform(feature2Plan, new NullProgressMonitor())); + assertEquals(1, queryResultSize(getProfile(profileLoadedId).query(new InstallableUnitQuery("hello", Version.create("1.0.0.1")), new NullProgressMonitor()))); } public void testInstallFeaturePatchReverseOrder() { @@ -123,9 +122,9 @@ public class Bug271067 extends AbstractProvisioningTest { installFeature2.setInstallableUnitInclusionRules(helloIU2, PlannerHelper.createOptionalInclusionRule(helloIU2)); installFeature2.setInstallableUnitInclusionRules(featureJar2, PlannerHelper.createOptionalInclusionRule(featureJar2)); - ProvisioningPlan feature2Plan = createPlanner().getProvisioningPlan(installFeature2, new ProvisioningContext(), null); - assertOK("installation of feature2", createEngine().perform(getProfile(profileLoadedId), new DefaultPhaseSet(), feature2Plan.getOperands(), new ProvisioningContext(), new NullProgressMonitor())); - assertEquals(1, getProfile(profileLoadedId).query(new InstallableUnitQuery("hello", new Version("1.0.2")), new Collector(), new NullProgressMonitor()).size()); + IProvisioningPlan feature2Plan = createPlanner().getProvisioningPlan(installFeature2, new ProvisioningContext(), null); + assertOK("installation of feature2", createEngine().perform(feature2Plan, new NullProgressMonitor())); + assertEquals(1, queryResultSize(getProfile(profileLoadedId).query(new InstallableUnitQuery("hello", Version.create("1.0.2")), new NullProgressMonitor()))); ProfileChangeRequest installFeature1 = new ProfileChangeRequest(getProfile(profileLoadedId)); IInstallableUnit featureGroup = getIU(repo, "hello.feature.1.feature.group", "1.0.0"); @@ -144,9 +143,9 @@ public class Bug271067 extends AbstractProvisioningTest { installFeature1.setInstallableUnitInclusionRules(helloPatch, PlannerHelper.createOptionalInclusionRule(helloPatch)); installFeature1.setInstallableUnitInclusionRules(patchJar, PlannerHelper.createOptionalInclusionRule(patchJar)); - ProvisioningPlan feature1Plan = createPlanner().getProvisioningPlan(installFeature1, new ProvisioningContext(), null); - assertOK("installation of feature1 and patch", createEngine().perform(getProfile(profileLoadedId), new DefaultPhaseSet(), feature1Plan.getOperands(), new ProvisioningContext(), new NullProgressMonitor())); - assertEquals(1, getProfile(profileLoadedId).query(new InstallableUnitQuery("hello", new Version("1.0.0.1")), new Collector(), new NullProgressMonitor()).size()); + IProvisioningPlan feature1Plan = createPlanner().getProvisioningPlan(installFeature1, new ProvisioningContext(), null); + assertOK("installation of feature1 and patch", createEngine().perform(feature1Plan, new NullProgressMonitor())); + assertEquals(1, queryResultSize(getProfile(profileLoadedId).query(new InstallableUnitQuery("hello", Version.create("1.0.0.1")), new NullProgressMonitor()))); } public void installTogether() { @@ -174,8 +173,8 @@ public class Bug271067 extends AbstractProvisioningTest { installEverything.setInstallableUnitInclusionRules(helloPatch, PlannerHelper.createOptionalInclusionRule(helloPatch)); installEverything.setInstallableUnitInclusionRules(patchJar, PlannerHelper.createOptionalInclusionRule(patchJar)); - ProvisioningPlan plan = createPlanner().getProvisioningPlan(installEverything, new ProvisioningContext(), null); - assertOK("installation of feature1 and patch", createEngine().perform(getProfile(profileLoadedId), new DefaultPhaseSet(), plan.getOperands(), new ProvisioningContext(), new NullProgressMonitor())); - assertEquals(1, getProfile(profileLoadedId).query(new InstallableUnitQuery("hello", new Version("1.0.0.1")), new Collector(), new NullProgressMonitor()).size()); + IProvisioningPlan plan = createPlanner().getProvisioningPlan(installEverything, new ProvisioningContext(), null); + assertOK("installation of feature1 and patch", createEngine().perform(plan, new NullProgressMonitor())); + assertEquals(1, queryResultSize(getProfile(profileLoadedId).query(new InstallableUnitQuery("hello", Version.create("1.0.0.1")), new NullProgressMonitor()))); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug271954.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug271954.java index 7322e4048..bc4b06f8d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug271954.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug271954.java @@ -10,22 +10,19 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import java.lang.reflect.Field; import java.net.URI; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; -import org.eclipse.equinox.p2.tests.TestActivator; public class Bug271954 extends AbstractProvisioningTest { private static final String profileLoadedId = "SDKProfile"; @@ -39,7 +36,7 @@ public class Bug271954 extends AbstractProvisioningTest { File tempFolder = getTempFolder(); copy("0.2", reporegistry1, tempFolder); - SimpleProfileRegistry realProfileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + SimpleProfileRegistry realProfileRegistry = (SimpleProfileRegistry) getProfileRegistry(); //Tweak the running profile registry Field profileStore = SimpleProfileRegistry.class.getDeclaredField("store"); profileStore.setAccessible(true); @@ -60,7 +57,7 @@ public class Bug271954 extends AbstractProvisioningTest { } protected void tearDown() throws Exception { - SimpleProfileRegistry realProfileRegistry = (SimpleProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + SimpleProfileRegistry realProfileRegistry = (SimpleProfileRegistry) getProfileRegistry(); Field profilesMapField = SimpleProfileRegistry.class.getDeclaredField("profiles"); //$NON-NLS-1$ profilesMapField.setAccessible(true); @@ -78,20 +75,20 @@ public class Bug271954 extends AbstractProvisioningTest { } public void testUninstallMyBundle() { - Collector c = profile.available(new InstallableUnitQuery("A"), new Collector(), new NullProgressMonitor()); - assertEquals(1, c.size()); + IQueryResult c = profile.available(new InstallableUnitQuery("A"), new NullProgressMonitor()); + assertEquals(1, queryResultSize(c)); ProfileChangeRequest req = new ProfileChangeRequest(profile); req.removeInstallableUnits((IInstallableUnit[]) c.toArray(IInstallableUnit.class)); ProvisioningContext ctx = new ProvisioningContext(new URI[0]); ctx.setArtifactRepositories(new URI[0]); - ProvisioningPlan plan = createPlanner().getProvisioningPlan(req, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = createPlanner().getProvisioningPlan(req, ctx, new NullProgressMonitor()); assertOK("Uninstall plan for myBundle", plan.getStatus()); - assertEquals(0, plan.getInstallerPlan().getAdditions().query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); - assertEquals(0, plan.getInstallerPlan().getRemovals().query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); + assertEquals(0, queryResultSize(plan.getInstallerPlan().getAdditions().query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); + assertEquals(0, queryResultSize(plan.getInstallerPlan().getRemovals().query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); assertUninstallOperand(plan, (IInstallableUnit) c.iterator().next()); - assertEquals(2, plan.getRemovals().query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); - assertEquals(1, plan.getRemovals().query(new InstallableUnitQuery("A", new Version(1, 0, 0)), new Collector(), new NullProgressMonitor()).size()); - assertEquals(1, plan.getRemovals().query(new InstallableUnitQuery("Action1", new Version(1, 0, 0)), new Collector(), new NullProgressMonitor()).size()); + assertEquals(2, queryResultSize(plan.getRemovals().query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); + assertEquals(1, queryResultSize(plan.getRemovals().query(new InstallableUnitQuery("A", Version.createOSGi(1, 0, 0)), new NullProgressMonitor()))); + assertEquals(1, queryResultSize(plan.getRemovals().query(new InstallableUnitQuery("Action1", Version.createOSGi(1, 0, 0)), new NullProgressMonitor()))); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug272251.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug272251.java index 5e8abb9e0..188664c4e 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug272251.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug272251.java @@ -10,17 +10,18 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class Bug272251 extends AbstractProvisioningTest { @@ -45,16 +46,16 @@ public class Bug272251 extends AbstractProvisioningTest { } public void testInstallFeaturePatch() { - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.wst.jsdt.feature.patch.feature.group", new Version("3.0.4.v200904020304-1-8d7w311_15131415")), new Collector(), new NullProgressMonitor()); - assertEquals(1, c.size()); - Collector expectedIU = repo.query(new InstallableUnitQuery("org.eclipse.wst.jsdt.web.ui", new Version("1.0.105.v200904020304")), new Collector(), new NullProgressMonitor()); - assertEquals(1, expectedIU.size()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.wst.jsdt.feature.patch.feature.group", Version.create("3.0.4.v200904020304-1-8d7w311_15131415")), new NullProgressMonitor()); + assertEquals(1, queryResultSize(c)); + IQueryResult expectedIU = repo.query(new InstallableUnitQuery("org.eclipse.wst.jsdt.web.ui", Version.create("1.0.105.v200904020304")), new NullProgressMonitor()); + assertEquals(1, queryResultSize(expectedIU)); IInstallableUnit patch = (IInstallableUnit) c.iterator().next(); ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {patch}); request.setInstallableUnitInclusionRules(patch, PlannerHelper.createStrictInclusionRule(patch)); IPlanner planner = createPlanner(); - ProvisioningPlan plan = planner.getProvisioningPlan(request, null, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, null, new NullProgressMonitor()); assertOK("Plan OK", plan.getStatus()); assertNoOperand(plan, patch); assertNoOperand(plan, (IInstallableUnit) expectedIU.iterator().next()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug278668.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug278668.java index 225ab7748..aa12a06d6 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug278668.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/Bug278668.java @@ -1,14 +1,20 @@ package org.eclipse.equinox.p2.tests.planner; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; + import java.util.ArrayList; import java.util.Properties; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IProvidedCapability; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class Bug278668 extends AbstractProvisioningTest { @@ -48,10 +54,10 @@ public class Bug278668 extends AbstractProvisioningTest { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {group}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertOK("plan should be OK", plan.getStatus()); - engine.perform(profile, new DefaultPhaseSet(), plan.getOperands(), null, null); + engine.perform(plan, null); repo = getMetadataRepositoryManager().loadRepository(getTestData("test data bug 278668", "testData/bug278668").toURI(), null); } @@ -62,27 +68,27 @@ public class Bug278668 extends AbstractProvisioningTest { } public void testInstallFeaturePatch() { - Collector c = repo.query(new InstallableUnitQuery("com.borland.tg.modeling.8.2.0.hotfixexp.patch.feature.group"), new Collector(), new NullProgressMonitor()); - assertEquals(1, c.size()); - Collector c2 = repo.query(new InstallableUnitQuery("com.borland.tg.modeling.8.2.0.nl.patch.feature.group"), new Collector(), new NullProgressMonitor()); - assertEquals(1, c2.size()); + IQueryResult c = repo.query(new InstallableUnitQuery("com.borland.tg.modeling.8.2.0.hotfixexp.patch.feature.group"), new NullProgressMonitor()); + assertEquals(1, queryResultSize(c)); + IQueryResult c2 = repo.query(new InstallableUnitQuery("com.borland.tg.modeling.8.2.0.nl.patch.feature.group"), new NullProgressMonitor()); + assertEquals(1, queryResultSize(c2)); ProfileChangeRequest request = new ProfileChangeRequest(profile); request.addInstallableUnits(new IInstallableUnit[] {(IInstallableUnit) c.iterator().next()}); IPlanner planner = createPlanner(); - ProvisioningPlan plan = planner.getProvisioningPlan(request, null, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, null, new NullProgressMonitor()); assertOK("Plan OK", plan.getStatus()); ProfileChangeRequest request2 = new ProfileChangeRequest(profile); request2.addInstallableUnits(new IInstallableUnit[] {(IInstallableUnit) c2.iterator().next()}); IPlanner planner2 = createPlanner(); - ProvisioningPlan plan2 = planner2.getProvisioningPlan(request2, null, new NullProgressMonitor()); + IProvisioningPlan plan2 = planner2.getProvisioningPlan(request2, null, new NullProgressMonitor()); assertOK("Plan OK", plan2.getStatus()); ProfileChangeRequest request3 = new ProfileChangeRequest(profile); request3.addInstallableUnits(new IInstallableUnit[] {(IInstallableUnit) c.iterator().next(), (IInstallableUnit) c2.iterator().next()}); IPlanner planner3 = createPlanner(); - ProvisioningPlan plan3 = planner3.getProvisioningPlan(request3, null, new NullProgressMonitor()); + IProvisioningPlan plan3 = planner3.getProvisioningPlan(request3, null, new NullProgressMonitor()); assertNotOK("Plan Not OK", plan3.getStatus()); ProfileChangeRequest request4 = new ProfileChangeRequest(profile); @@ -90,7 +96,7 @@ public class Bug278668 extends AbstractProvisioningTest { request4.setInstallableUnitInclusionRules((IInstallableUnit) c.iterator().next(), PlannerHelper.createOptionalInclusionRule((IInstallableUnit) c.iterator().next())); request4.setInstallableUnitInclusionRules((IInstallableUnit) c2.iterator().next(), PlannerHelper.createOptionalInclusionRule((IInstallableUnit) c2.iterator().next())); IPlanner planner4 = createPlanner(); - ProvisioningPlan plan4 = planner4.getProvisioningPlan(request4, null, new NullProgressMonitor()); + IProvisioningPlan plan4 = planner4.getProvisioningPlan(request4, null, new NullProgressMonitor()); assertOK("Plan OK", plan4.getStatus()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/DependencyOnSelf.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/DependencyOnSelf.java index c6e326f90..7edb4168f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/DependencyOnSelf.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/DependencyOnSelf.java @@ -10,14 +10,14 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class DependencyOnSelf extends AbstractProvisioningTest { @@ -28,7 +28,7 @@ public class DependencyOnSelf extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"), null)); + a1 = createIU("A", Version.create("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"))); createTestMetdataRepository(new IInstallableUnit[] {a1}); profile = createProfile(DependencyOnSelf.class.getName()); planner = createPlanner(); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/DisabledExplanation.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/DisabledExplanation.java index a41319a2e..630e7d807 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/DisabledExplanation.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/DisabledExplanation.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class DisabledExplanation extends AbstractProvisioningTest { @@ -28,12 +30,12 @@ public class DisabledExplanation extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), true); + a1 = createIU("A", Version.create("1.0.0"), true); //Missing non optional dependency IRequiredCapability[] req = new IRequiredCapability[1]; req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, false, false, true); - b1 = createIU("B", new Version("1.0.0"), req); + b1 = createIU("B", Version.create("1.0.0"), req); createTestMetdataRepository(new IInstallableUnit[] {a1, b1}); @@ -46,7 +48,7 @@ public class DisabledExplanation extends AbstractProvisioningTest { req.addInstallableUnits(new IInstallableUnit[] {a1, b1}); ProvisioningContext ctx = new ProvisioningContext(); ctx.setProperty("org.eclipse.equinox.p2.director.explain", "false"); - ProvisioningPlan plan = planner.getProvisioningPlan(req, ctx, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(req, ctx, null); assertEquals(IStatus.ERROR, plan.getStatus().getSeverity()); assertNull(plan.getRequestStatus()); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/DropinsScenario.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/DropinsScenario.java index 1db12523d..59cfa193d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/DropinsScenario.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/DropinsScenario.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class DropinsScenario extends AbstractProvisioningTest { @@ -29,18 +33,18 @@ public class DropinsScenario extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), true); + a1 = createIU("A", Version.create("1.0.0"), true); - b1 = createIU("B", new Version("1.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); - a0 = createIU("A", new Version("0.0.0"), true); - b0 = createIU("B", new Version("0.0.0"), true); + a0 = createIU("A", Version.create("0.0.0"), true); + b0 = createIU("B", Version.create("0.0.0"), true); IRequiredCapability[] reqAs = new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[0.0.0, 1.0.0]"), null, false, false, true)}; - as = createIU("AS", new Version("0.0.0"), reqAs); + as = createIU("AS", Version.create("0.0.0"), reqAs); IRequiredCapability[] reqBs = new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[0.0.0, 1.0.0]"), null, false, false, true)}; - bs = createIU("BS", new Version("0.0.0"), reqBs); + bs = createIU("BS", Version.create("0.0.0"), reqBs); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, a0, b0, as, bs}); @@ -51,7 +55,7 @@ public class DropinsScenario extends AbstractProvisioningTest { public void testInstallation() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {as, bs}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationDeepConflict.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationDeepConflict.java index 8d566fca8..72090cd34 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationDeepConflict.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationDeepConflict.java @@ -10,12 +10,12 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class ExplanationDeepConflict extends AbstractProvisioningTest { @@ -27,9 +27,9 @@ public class ExplanationDeepConflict extends AbstractProvisioningTest { @Override protected void setUp() throws Exception { super.setUp(); - sdk = createIU("SDK", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[1.0.0, 1.0.0]"), null)); - IInstallableUnit sdkPart = createIU("SDKPart", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "InnerSDKPart", new VersionRange("[1.0.0, 1.0.0]"), null)); - IInstallableUnit innerSdkPart = createIU("InnerSDKPart", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "InnerInnerSDKPart", new VersionRange("[1.0.0, 1.0.0]"), null)); + sdk = createIU("SDK", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[1.0.0, 1.0.0]"))); + IInstallableUnit sdkPart = createIU("SDKPart", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "InnerSDKPart", new VersionRange("[1.0.0, 1.0.0]"))); + IInstallableUnit innerSdkPart = createIU("InnerSDKPart", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "InnerInnerSDKPart", new VersionRange("[1.0.0, 1.0.0]"))); IInstallableUnit innerInnerSDKPart = createIU("InnerInnerSDKPart", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), true); createTestMetdataRepository(new IInstallableUnit[] {sdk, sdkPart, innerSdkPart, innerInnerSDKPart}); @@ -40,25 +40,26 @@ public class ExplanationDeepConflict extends AbstractProvisioningTest { ProfileChangeRequest pcr = new ProfileChangeRequest(profile); pcr.addInstallableUnits(new IInstallableUnit[] {sdk}); - engine.perform(profile, new DefaultPhaseSet(), planner.getProvisioningPlan(pcr, null, null).getOperands(), null, null); + engine.perform(planner.getProvisioningPlan(pcr, null, null), null); assertProfileContains("1.0", profile, new IInstallableUnit[] {sdk, sdkPart, innerSdkPart, innerInnerSDKPart}); } public void testDeepSingletonConflict() { //CDT will have a singleton conflict with SDK - IInstallableUnit cdt = createIU("CDT", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "CDTPart", new VersionRange("[1.0.0, 1.0.0]"), null)); - IInstallableUnit cdtPart = createIU("CDTPart", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "InnerInnerSDKPart", new VersionRange("[2.0.0, 2.0.0]"), null)); + IInstallableUnit cdt = createIU("CDT", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "CDTPart", new VersionRange("[1.0.0, 1.0.0]"))); + IInstallableUnit cdtPart = createIU("CDTPart", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "InnerInnerSDKPart", new VersionRange("[2.0.0, 2.0.0]"))); IInstallableUnit innerInnerSDKPart2 = createIU("InnerInnerSDKPart", Version.fromOSGiVersion(new org.osgi.framework.Version("2.0.0")), true); createTestMetdataRepository(new IInstallableUnit[] {cdt, cdtPart, innerInnerSDKPart2}); ProfileChangeRequest pcr = new ProfileChangeRequest(profile); pcr.addInstallableUnits(new IInstallableUnit[] {cdt}); - ProvisioningPlan plan = planner.getProvisioningPlan(pcr, null, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(pcr, null, null); // System.out.println(plan.getRequestStatus().getExplanations()); - assertTrue(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(cdt)); + RequestStatus requestStatus = (RequestStatus) plan.getRequestStatus(); + assertTrue(requestStatus.getConflictsWithInstalledRoots().contains(cdt)); //Here we verify that we only return the roots we asked the installation of. The SDK is installable since it is already installed - assertFalse(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(sdk)); - assertTrue(plan.getRequestStatus().getConflictsWithAnyRoots().contains(sdk)); + assertFalse(requestStatus.getConflictsWithInstalledRoots().contains(sdk)); + assertTrue(requestStatus.getConflictsWithAnyRoots().contains(sdk)); // assertTrue(plan.getRequestStatus(cdt).getConflictsWithAnyRoots().contains(sdk)); // assertTrue(plan.getRequestStatus(cdt).getConflictsWithInstalledRoots().contains(sdk)); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationForOptionalDependencies.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationForOptionalDependencies.java index c87a9b46b..a7aa0e159 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationForOptionalDependencies.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationForOptionalDependencies.java @@ -10,12 +10,14 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class ExplanationForOptionalDependencies extends AbstractProvisioningTest { @@ -27,7 +29,7 @@ public class ExplanationForOptionalDependencies extends AbstractProvisioningTest @Override protected void setUp() throws Exception { super.setUp(); - sdk = createIU("SDK", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[1.0.0, 1.0.0]"), null)); + sdk = createIU("SDK", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[1.0.0, 1.0.0]"))); IInstallableUnit sdkPart = createIU("SDKPart", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), true); IInstallableUnit sdkPart2 = createIU("SDKPart", Version.fromOSGiVersion(new org.osgi.framework.Version("2.0.0")), true); @@ -39,7 +41,7 @@ public class ExplanationForOptionalDependencies extends AbstractProvisioningTest ProfileChangeRequest pcr = new ProfileChangeRequest(profile); pcr.addInstallableUnits(new IInstallableUnit[] {sdk}); - engine.perform(profile, new DefaultPhaseSet(), planner.getProvisioningPlan(pcr, null, null).getOperands(), null, null); + engine.perform(planner.getProvisioningPlan(pcr, null, null), null); } @@ -55,10 +57,11 @@ public class ExplanationForOptionalDependencies extends AbstractProvisioningTest createTestMetdataRepository(new IInstallableUnit[] {cdt, emf}); ProfileChangeRequest pcr = new ProfileChangeRequest(profile); pcr.addInstallableUnits(new IInstallableUnit[] {cdt, emf}); - ProvisioningPlan plan = planner.getProvisioningPlan(pcr, null, null); - assertTrue(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(emf)); - assertFalse(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(cdt)); - assertFalse(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(sdk)); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(pcr, null, null); + RequestStatus requestStatus = (RequestStatus) plan.getRequestStatus(); + assertTrue(requestStatus.getConflictsWithInstalledRoots().contains(emf)); + assertFalse(requestStatus.getConflictsWithInstalledRoots().contains(cdt)); + assertFalse(requestStatus.getConflictsWithInstalledRoots().contains(sdk)); // assertTrue(plan.getRequestStatus(cdt).getSeverity() != IStatus.ERROR); // diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationForPartialInstallation.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationForPartialInstallation.java index 2fc286a9d..0addc22a9 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationForPartialInstallation.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationForPartialInstallation.java @@ -10,12 +10,12 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class ExplanationForPartialInstallation extends AbstractProvisioningTest { @@ -27,7 +27,7 @@ public class ExplanationForPartialInstallation extends AbstractProvisioningTest @Override protected void setUp() throws Exception { super.setUp(); - sdk = createIU("SDK", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[1.0.0, 1.0.0]"), null)); + sdk = createIU("SDK", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[1.0.0, 1.0.0]"))); IInstallableUnit sdkPart = createIU("SDKPart", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), true); IInstallableUnit sdkPart2 = createIU("SDKPart", Version.fromOSGiVersion(new org.osgi.framework.Version("2.0.0")), true); @@ -39,25 +39,26 @@ public class ExplanationForPartialInstallation extends AbstractProvisioningTest ProfileChangeRequest pcr = new ProfileChangeRequest(profile); pcr.addInstallableUnits(new IInstallableUnit[] {sdk}); - engine.perform(profile, new DefaultPhaseSet(), planner.getProvisioningPlan(pcr, null, null).getOperands(), null, null); + engine.perform(planner.getProvisioningPlan(pcr, null, null), null); } public void testPartialProblemSingleton() { //CDT will have a singleton conflict with SDK //EMF will be good - IInstallableUnit cdt = createIU("CDT", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[2.0.0, 2.0.0]"), null)); + IInstallableUnit cdt = createIU("CDT", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[2.0.0, 2.0.0]"))); IInstallableUnit emf = createIU("EMF", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), true); createTestMetdataRepository(new IInstallableUnit[] {cdt, emf}); ProfileChangeRequest pcr = new ProfileChangeRequest(profile); pcr.addInstallableUnits(new IInstallableUnit[] {cdt, emf}); - ProvisioningPlan plan = planner.getProvisioningPlan(pcr, null, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(pcr, null, null); // System.out.println(plan.getRequestStatus().getExplanations()); - assertTrue(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(cdt)); - assertFalse(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(emf)); - assertFalse(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(sdk)); + RequestStatus requestStatus = (RequestStatus) plan.getRequestStatus(); + assertTrue(requestStatus.getConflictsWithInstalledRoots().contains(cdt)); + assertFalse(requestStatus.getConflictsWithInstalledRoots().contains(emf)); + assertFalse(requestStatus.getConflictsWithInstalledRoots().contains(sdk)); // assertTrue(plan.getRequestStatus(cdt).getSeverity() == IStatus.ERROR); // assertTrue(plan.getRequestStatus(cdt).getConflictsWithAnyRoots().contains(sdk)); @@ -73,18 +74,19 @@ public class ExplanationForPartialInstallation extends AbstractProvisioningTest public void testPartialProblemRequirement() { //CDT will be missing a requirement //EMF will be good - IInstallableUnit cdt = createIU("CDT", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "MissingPart", new VersionRange("[2.0.0, 2.0.0]"), null)); + IInstallableUnit cdt = createIU("CDT", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "MissingPart", new VersionRange("[2.0.0, 2.0.0]"))); IInstallableUnit emf = createIU("EMF", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), true); createTestMetdataRepository(new IInstallableUnit[] {cdt, emf}); ProfileChangeRequest pcr = new ProfileChangeRequest(profile); pcr.addInstallableUnits(new IInstallableUnit[] {cdt, emf}); - ProvisioningPlan plan = planner.getProvisioningPlan(pcr, null, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(pcr, null, null); // System.out.println(plan.getRequestStatus().getExplanations()); - assertTrue(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(cdt)); - assertFalse(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(emf)); - assertFalse(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(sdk)); + RequestStatus requestStatus = (RequestStatus) plan.getRequestStatus(); + assertTrue(requestStatus.getConflictsWithInstalledRoots().contains(cdt)); + assertFalse(requestStatus.getConflictsWithInstalledRoots().contains(emf)); + assertFalse(requestStatus.getConflictsWithInstalledRoots().contains(sdk)); // assertTrue(plan.getRequestStatus(cdt).getSeverity() == IStatus.ERROR); // assertEquals(0, plan.getRequestStatus(cdt).getConflictsWithAnyRoots().size()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationLargeConflict.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationLargeConflict.java index 3ab52200b..4d4fa7477 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationLargeConflict.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationLargeConflict.java @@ -10,19 +10,18 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.io.File; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class ExplanationLargeConflict extends AbstractProvisioningTest { @@ -50,19 +49,19 @@ public class ExplanationLargeConflict extends AbstractProvisioningTest { long sTime = System.currentTimeMillis(); //Here we verify that two version of JDT can't be installed together. The SDKProfile is not used IProfile profile = createProfile("TestProfile." + getName()); - Collector c = repo1.query(new InstallableUnitQuery("org.eclipse.jdt.feature.group"), new Collector(), null); - assertEquals(1, c.size()); + IQueryResult c = repo1.query(new InstallableUnitQuery("org.eclipse.jdt.feature.group"), null); + assertEquals(1, queryResultSize(c)); IInstallableUnit jdt1 = (IInstallableUnit) c.iterator().next(); - Collector c2 = repo2.query(new InstallableUnitQuery("org.eclipse.jdt.feature.group"), new Collector(), null); - assertEquals(1, c2.size()); + IQueryResult c2 = repo2.query(new InstallableUnitQuery("org.eclipse.jdt.feature.group"), null); + assertEquals(1, queryResultSize(c2)); IInstallableUnit jdt2 = (IInstallableUnit) c2.iterator().next(); assertNotSame(jdt1, jdt2); ProfileChangeRequest pcr = new ProfileChangeRequest(profile); pcr.addInstallableUnits(new IInstallableUnit[] {jdt1, jdt2}); - ProvisioningPlan plan = planner.getProvisioningPlan(pcr, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(pcr, null, null); assertNotOK(plan.getStatus()); LogHelper.log(plan.getStatus()); // System.out.println(plan.getRequestStatus().getExplanations()); @@ -73,11 +72,11 @@ public class ExplanationLargeConflict extends AbstractProvisioningTest { public void testMissingRequirement() { long sTime = System.currentTimeMillis(); //Test the case of a missing requirement in the IU being installed - IRequiredCapability[] cap = createRequiredCapabilities("missing", "missing", new VersionRange("[0.0.0, 1.0.0)"), null); - IInstallableUnit otherIU2 = createIU("foo", new Version("0.9.0"), null, cap, BUNDLE_CAPABILITY, NO_PROPERTIES, TOUCHPOINT_OSGI, NO_TP_DATA, true); + IRequiredCapability[] cap = createRequiredCapabilities("missing", "missing", new VersionRange("[0.0.0, 1.0.0)")); + IInstallableUnit otherIU2 = createIU("foo", Version.create("0.9.0"), null, cap, BUNDLE_CAPABILITY, NO_PROPERTIES, TOUCHPOINT_OSGI, NO_TP_DATA, true); ProfileChangeRequest pcr3 = new ProfileChangeRequest(SDKprofile); pcr3.addInstallableUnits(new IInstallableUnit[] {otherIU2}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(pcr3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(pcr3, null, null); assertNotOK(plan3.getStatus()); LogHelper.log(plan3.getStatus()); // System.out.println(plan3.getRequestStatus().getExplanations()); @@ -88,10 +87,10 @@ public class ExplanationLargeConflict extends AbstractProvisioningTest { public void testSingletonConflict() { long sTime = System.currentTimeMillis(); //The IU being installed conflict with something already installed because of a singleton - IInstallableUnit otherIU = createIU("org.eclipse.equinox.p2.director", new Version("0.9.0"), null, NO_REQUIRES, BUNDLE_CAPABILITY, NO_PROPERTIES, TOUCHPOINT_OSGI, NO_TP_DATA, true); + IInstallableUnit otherIU = createIU("org.eclipse.equinox.p2.director", Version.create("0.9.0"), null, NO_REQUIRES, BUNDLE_CAPABILITY, NO_PROPERTIES, TOUCHPOINT_OSGI, NO_TP_DATA, true); ProfileChangeRequest pcr2 = new ProfileChangeRequest(SDKprofile); pcr2.addInstallableUnits(new IInstallableUnit[] {otherIU}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(pcr2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(pcr2, null, null); assertNotOK(plan2.getStatus()); LogHelper.log(plan2.getStatus()); // System.out.println(plan2.getRequestStatus().getExplanations()); @@ -102,13 +101,13 @@ public class ExplanationLargeConflict extends AbstractProvisioningTest { public void testExplanationLargeConflictInSDK() { long sTime = System.currentTimeMillis(); //Test large conflict. We are trying to install an inappropriate version of CVS over the already installed SDK - Collector c = repo2.query(new InstallableUnitQuery("org.eclipse.cvs.feature.group"), new Collector(), null); - assertEquals(1, c.size()); + IQueryResult c = repo2.query(new InstallableUnitQuery("org.eclipse.cvs.feature.group"), null); + assertEquals(1, queryResultSize(c)); IInstallableUnit cvs = (IInstallableUnit) c.iterator().next(); ProfileChangeRequest pcr = new ProfileChangeRequest(SDKprofile); pcr.addInstallableUnits(new IInstallableUnit[] {cvs}); - ProvisioningPlan plan = planner.getProvisioningPlan(pcr, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(pcr, null, null); assertNotOK(plan.getStatus()); LogHelper.log(plan.getStatus()); // System.out.println(plan.getRequestStatus().getExplanations()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationSeveralConflictingRoots.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationSeveralConflictingRoots.java index 664b1c819..39f734da3 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationSeveralConflictingRoots.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ExplanationSeveralConflictingRoots.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.Set; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class ExplanationSeveralConflictingRoots extends AbstractProvisioningTest { @@ -27,7 +29,7 @@ public class ExplanationSeveralConflictingRoots extends AbstractProvisioningTest @Override protected void setUp() throws Exception { super.setUp(); - sdk = createIU("SDK", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[1.0.0, 1.0.0]"), null)); + sdk = createIU("SDK", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[1.0.0, 1.0.0]"))); IInstallableUnit sdkPart = createIU("SDKPart", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), true); IInstallableUnit sdkPart2 = createIU("SDKPart", Version.fromOSGiVersion(new org.osgi.framework.Version("2.0.0")), true); @@ -39,23 +41,23 @@ public class ExplanationSeveralConflictingRoots extends AbstractProvisioningTest ProfileChangeRequest pcr = new ProfileChangeRequest(profile); pcr.addInstallableUnits(new IInstallableUnit[] {sdk}); - engine.perform(profile, new DefaultPhaseSet(), planner.getProvisioningPlan(pcr, null, null).getOperands(), null, null); + engine.perform(planner.getProvisioningPlan(pcr, null, null), null); } public void testConflictingSingletonAndMissingDependency() { //CDT will have a singleton conflict with SDK //EMF will be missing a dependency - IInstallableUnit cdt = createIU("CDT", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[2.0.0, 2.0.0]"), null)); + IInstallableUnit cdt = createIU("CDT", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[2.0.0, 2.0.0]"))); - IInstallableUnit emf = createIU("EMF", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "EMFPart", new VersionRange("[1.0.0, 1.0.0]"), null)); + IInstallableUnit emf = createIU("EMF", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "EMFPart", new VersionRange("[1.0.0, 1.0.0]"))); createTestMetdataRepository(new IInstallableUnit[] {cdt, emf}); ProfileChangeRequest pcr = new ProfileChangeRequest(profile); pcr.addInstallableUnits(new IInstallableUnit[] {cdt, emf}); - ProvisioningPlan plan = planner.getProvisioningPlan(pcr, null, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(pcr, null, null); // System.out.println(plan.getRequestStatus().getExplanations()); - Set conflictRoots = plan.getRequestStatus().getConflictsWithInstalledRoots(); + Set conflictRoots = ((RequestStatus) plan.getRequestStatus()).getConflictsWithInstalledRoots(); assertTrue(conflictRoots.contains(cdt) || conflictRoots.contains(emf)); // assertTrue(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(emf)); @@ -68,7 +70,7 @@ public class ExplanationSeveralConflictingRoots extends AbstractProvisioningTest public void testConflictingSingletonAndMissingDependency2() { //CDT will have a singleton conflict EMF //EMF will be missing a dependency and will be in conflict with CDT - IInstallableUnit cdt = createIU("CDT", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "ASingleton", new VersionRange("[2.0.0, 2.0.0]"), null)); + IInstallableUnit cdt = createIU("CDT", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "ASingleton", new VersionRange("[2.0.0, 2.0.0]"))); IInstallableUnit aSingleton1 = createIU("ASingleton", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), true); IInstallableUnit aSingleton2 = createIU("ASingleton", Version.fromOSGiVersion(new org.osgi.framework.Version("2.0.0")), true); @@ -79,9 +81,9 @@ public class ExplanationSeveralConflictingRoots extends AbstractProvisioningTest createTestMetdataRepository(new IInstallableUnit[] {aSingleton1, aSingleton2, cdt, emf}); ProfileChangeRequest pcr = new ProfileChangeRequest(profile); pcr.addInstallableUnits(new IInstallableUnit[] {cdt, emf}); - ProvisioningPlan plan = planner.getProvisioningPlan(pcr, null, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(pcr, null, null); // System.out.println(plan.getRequestStatus().getExplanations()); - Set conflictRoots = plan.getRequestStatus().getConflictsWithInstalledRoots(); + Set conflictRoots = ((RequestStatus) plan.getRequestStatus()).getConflictsWithInstalledRoots(); assertTrue(conflictRoots.contains(cdt) || conflictRoots.contains(emf)); // assertEquals(0, plan.getRequestStatus(cdt).getConflictsWithInstalledRoots().size()); @@ -93,7 +95,7 @@ public class ExplanationSeveralConflictingRoots extends AbstractProvisioningTest public void testConflictingSingletonAndMissingDependency3() { //CDT will have a singleton conflict EMF and with the SDK //EMF will be conflicting with CDT - IInstallableUnit cdt = createIU("CDT", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[2.0.0, 2.0.0]"), null)); + IInstallableUnit cdt = createIU("CDT", Version.fromOSGiVersion(new org.osgi.framework.Version("1.0.0")), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[2.0.0, 2.0.0]"))); IInstallableUnit sdkPart3 = createIU("SDKPart", Version.fromOSGiVersion(new org.osgi.framework.Version("3.0.0")), true); IRequiredCapability emfOnSingleton = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "SDKPart", new VersionRange("[1.0.0, 1.0.0]"), null, false, false); @@ -103,9 +105,9 @@ public class ExplanationSeveralConflictingRoots extends AbstractProvisioningTest createTestMetdataRepository(new IInstallableUnit[] {sdkPart3, cdt, emf}); ProfileChangeRequest pcr = new ProfileChangeRequest(profile); pcr.addInstallableUnits(new IInstallableUnit[] {cdt, emf}); - ProvisioningPlan plan = planner.getProvisioningPlan(pcr, null, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(pcr, null, null); // System.out.println(plan.getRequestStatus().getExplanations()); - Set conflictRoots = plan.getRequestStatus().getConflictsWithInstalledRoots(); + Set conflictRoots = ((RequestStatus) plan.getRequestStatus()).getConflictsWithInstalledRoots(); assertTrue(conflictRoots.contains(cdt) || conflictRoots.contains(emf)); // assertTrue(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(cdt)); // assertTrue(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(emf)); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/FindingPatchesThroughUpdates.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/FindingPatchesThroughUpdates.java index 01229c6b8..c7f0db941 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/FindingPatchesThroughUpdates.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/FindingPatchesThroughUpdates.java @@ -10,19 +10,22 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; +import java.util.Properties; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class FindingPatchesThroughUpdates extends AbstractProvisioningTest { IInstallableUnit a1; IInstallableUnit a120; - IInstallableUnitPatch patchA1, patchA2; + IInstallableUnitPatch patchA1, patchA2, anotherPatch2, anotherPatch3; IProfile profile1; IPlanner planner; @@ -30,24 +33,29 @@ public class FindingPatchesThroughUpdates extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0")); + a1 = createIU("A", Version.create("1.0.0")); IUpdateDescriptor update = MetadataFactory.createUpdateDescriptor("A", new VersionRange("[1.0.0, 1.0.0]"), 0, "update description"); - a120 = createIU("UpdateA", new Version(1, 2, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, false, update, NO_REQUIRES); + a120 = createIU("UpdateA", Version.createOSGi(1, 2, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, false, update, NO_REQUIRES); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequiredCapability lifeCycle = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.2.0]"), null, false, false); - patchA1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle); + patchA1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle); IRequirementChange change2 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequiredCapability lifeCycle2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 3.2.0]"), null, false, false); - patchA2 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change2}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle2); + patchA2 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change2}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle2); - createTestMetdataRepository(new IInstallableUnit[] {a1, a120, patchA1, patchA2}); + IRequirementChange change3 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); + IRequiredCapability lifeCycle3 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 3.2.0]"), null, false, false); + anotherPatch2 = createIUPatch("ANOTHERPATCH", Version.create("1.0.0"), true, new IRequirementChange[] {change3}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle3); + + IRequirementChange change4 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); + IRequiredCapability lifeCycle4 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 3.2.0]"), null, false, false); + anotherPatch3 = createIUPatch("ANOTHERPATCH", Version.create("2.0.0"), null, NO_REQUIRES, NO_PROVIDES, new Properties(), null, null, true, MetadataFactory.createUpdateDescriptor("ANOTHERPATCH", new VersionRange("[1.0.0, 1.0.0]"), 0, ""), new IRequirementChange[] {change4}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, lifeCycle4, NO_REQUIRES); + + createTestMetdataRepository(new IInstallableUnit[] {a1, a120, patchA1, patchA2, anotherPatch2, anotherPatch3}); - profile1 = createProfile("TestProfile." + getName()); planner = createPlanner(); - engine = createEngine(); - install(profile1, new IInstallableUnit[] {a1}, true, planner, engine); } public void testInstall() { @@ -55,4 +63,10 @@ public class FindingPatchesThroughUpdates extends AbstractProvisioningTest { assertEquals(2, updates.length); assertEquals("Checking updates", new IInstallableUnit[] {a120, patchA1}, updates, false); } + + public void testFindUpdatesOfPatches() { + IInstallableUnit[] updates = planner.updatesFor(anotherPatch2, new ProvisioningContext(), new NullProgressMonitor()); + assertEquals(1, updates.length); + assertEquals("Checking updates", new IInstallableUnit[] {anotherPatch3}, updates, false); + } } \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/GreedyRequirement.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/GreedyRequirement.java index b76fcaddd..8ef1e4dd7 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/GreedyRequirement.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/GreedyRequirement.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class GreedyRequirement extends AbstractProvisioningTest { @@ -26,15 +30,15 @@ public class GreedyRequirement extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - b1 = createIU("B", new Version("1.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); IRequiredCapability[] reqB = new IRequiredCapability[1]; reqB[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, true, false, false); - a1 = createIU("A", new Version("1.0.0"), reqB); + a1 = createIU("A", Version.create("1.0.0"), reqB); IRequiredCapability[] reqC = new IRequiredCapability[1]; reqC[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, true); - c1 = createIU("C", new Version("1.0.0"), reqC); + c1 = createIU("C", Version.create("1.0.0"), reqC); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, c1}); @@ -46,7 +50,7 @@ public class GreedyRequirement extends AbstractProvisioningTest { //The plan contains B because the requirement from A on B is non greedy, but we are installing C that has a greedy requirement on the B ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1, c1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, a1); assertInstallOperand(plan, b1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUProperties.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUProperties.java index ca7ef1cde..091cc8fc2 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUProperties.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUProperties.java @@ -8,15 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.query.IUProfilePropertyQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class IUProperties extends AbstractProvisioningTest { @@ -31,13 +33,13 @@ public class IUProperties extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B1", new VersionRange("[1.0.0, 2.0.0)"), null)); + a1 = createIU("A", Version.create("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B1", new VersionRange("[1.0.0, 2.0.0)"))); - b1 = createIU("B1", new Version("1.0.0"), true); + b1 = createIU("B1", Version.create("1.0.0"), true); - b11 = createIU("B1", new Version("1.1.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 3.0.0)"), null), NO_PROPERTIES, true); + b11 = createIU("B1", Version.create("1.1.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 3.0.0)")), NO_PROPERTIES, true); - c = createIU("C", new Version(2, 0, 0), true); + c = createIU("C", Version.createOSGi(2, 0, 0), true); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, b11, c}); @@ -53,17 +55,17 @@ public class IUProperties extends AbstractProvisioningTest { req1.addInstallableUnits(new IInstallableUnit[] {a1}); req1.setInstallableUnitProfileProperty(a1, "FOO", "BAR"); req1.setInstallableUnitProfileProperty(b1, "FOO", "BAR"); - ProvisioningPlan pp1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan pp1 = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.OK, pp1.getStatus().getSeverity()); - IStatus s = engine.perform(profile, new DefaultPhaseSet(), pp1.getOperands(), null, null); + IStatus s = engine.perform(pp1, null); if (!s.isOK()) LogHelper.log(s); - Collector collector = getProfile(profileId).query(new IUProfilePropertyQuery("FOO", null), new Collector(), null); - assertEquals(1, collector.size()); + IQueryResult queryResult = getProfile(profileId).query(new IUProfilePropertyQuery("FOO", null), null); + assertEquals(1, queryResultSize(queryResult)); ProfileChangeRequest req2 = new ProfileChangeRequest(profile); req2.removeInstallableUnitProfileProperty(b1, "FOO"); - ProvisioningPlan pp2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan pp2 = planner.getProvisioningPlan(req2, null, null); assertEquals(0, pp2.getOperands().length); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUPropertyRemoval.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUPropertyRemoval.java index 1bebfbb3a..814ae8c98 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUPropertyRemoval.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUPropertyRemoval.java @@ -8,14 +8,16 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.query.IUProfilePropertyQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class IUPropertyRemoval extends AbstractProvisioningTest { @@ -28,9 +30,9 @@ public class IUPropertyRemoval extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B1", new VersionRange("[1.0.0, 2.0.0)"), null)); + a1 = createIU("A", Version.create("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B1", new VersionRange("[1.0.0, 2.0.0)"))); - b1 = createIU("B1", new Version("1.0.0"), true); + b1 = createIU("B1", Version.create("1.0.0"), true); createTestMetdataRepository(new IInstallableUnit[] {a1, b1}); @@ -46,18 +48,18 @@ public class IUPropertyRemoval extends AbstractProvisioningTest { req1.addInstallableUnits(new IInstallableUnit[] {a1}); req1.setInstallableUnitProfileProperty(a1, "FOO", "BAR"); req1.setInstallableUnitProfileProperty(b1, "FOO", "BAR"); - ProvisioningPlan pp1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan pp1 = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.OK, pp1.getStatus().getSeverity()); - engine.perform(profile, new DefaultPhaseSet(), pp1.getOperands(), null, null); - Collector res = getProfile(profileId).query(new IUProfilePropertyQuery("FOO", null), new Collector(), null); - assertEquals(2, res.size()); + engine.perform(pp1, null); + IQueryResult res = getProfile(profileId).query(new IUProfilePropertyQuery("FOO", null), null); + assertEquals(2, queryResultSize(res)); ProfileChangeRequest req2 = new ProfileChangeRequest(profile); req2.removeInstallableUnitProfileProperty(b1, "FOO"); - ProvisioningPlan pp2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan pp2 = planner.getProvisioningPlan(req2, null, null); assertEquals(1, pp2.getOperands().length); - engine.perform(getProfile(profileId), new DefaultPhaseSet(), pp2.getOperands(), null, null); - Collector res2 = getProfile(profileId).query(new IUProfilePropertyQuery("FOO", null), new Collector(), null); - assertEquals(1, res2.size()); + engine.perform(pp2, null); + IQueryResult res2 = getProfile(profileId).query(new IUProfilePropertyQuery("FOO", null), null); + assertEquals(1, queryResultSize(res2)); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUWithFilter.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUWithFilter.java index 393c59923..83e7701a4 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUWithFilter.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUWithFilter.java @@ -10,15 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class IUWithFilter extends AbstractProvisioningTest { @@ -31,8 +31,8 @@ public class IUWithFilter extends AbstractProvisioningTest { super.setUp(); MetadataFactory.InstallableUnitDescription iud = new MetadataFactory.InstallableUnitDescription(); iud.setId("A"); - iud.setVersion(new Version("1.0.0")); - iud.setRequiredCapabilities(createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"), null)); + iud.setVersion(Version.create("1.0.0")); + iud.setRequiredCapabilities(createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"))); iud.setFilter("(invalid=true)"); a1 = MetadataFactory.createInstallableUnit(iud); createTestMetdataRepository(new IInstallableUnit[] {a1}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUWithFilter2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUWithFilter2.java index 4ae4a8a95..566a982ba 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUWithFilter2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/IUWithFilter2.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class IUWithFilter2 extends AbstractProvisioningTest { @@ -37,7 +39,7 @@ public class IUWithFilter2 extends AbstractProvisioningTest { reqsA2[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.0.0]"), null, true, false); a2 = createIU("A", reqsA2); - b1 = createIU("B", new Version("1.0.0"), "(invalid=true)", NO_PROVIDES); + b1 = createIU("B", Version.create("1.0.0"), "(invalid=true)", NO_PROVIDES); createTestMetdataRepository(new IInstallableUnit[] {a1, a2, b1}); profile = createProfile(IUWithFilter2.class.getName()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/InclusionRuleTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/InclusionRuleTest.java index da651c25e..f4fd84b9c 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/InclusionRuleTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/InclusionRuleTest.java @@ -8,14 +8,13 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class InclusionRuleTest extends AbstractProvisioningTest { @@ -31,11 +30,11 @@ public class InclusionRuleTest extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), true); + a1 = createIU("A", Version.create("1.0.0"), true); - a2 = createIU("A", new Version("2.0.0"), true); + a2 = createIU("A", Version.create("2.0.0"), true); - b1 = createIU("B", new Version("1.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); createTestMetdataRepository(new IInstallableUnit[] {a1, a2}); @@ -47,44 +46,44 @@ public class InclusionRuleTest extends AbstractProvisioningTest { profile1 = createProfile("TestProfile." + getName()); ProfileChangeRequest req = new ProfileChangeRequest(profile1); req.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); - engine.perform(profile1, new DefaultPhaseSet(), plan.getOperands(), null, null); + engine.perform(plan, null); assertProfileContainsAll("A1 is missing", profile1, new IInstallableUnit[] {a1}); - assertEquals(profile1.query(InstallableUnitQuery.ANY, new Collector(), null).size(), 1); + assertEquals(queryResultSize(profile1.query(InstallableUnitQuery.ANY, null)), 1); //Make a1 optional. ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.setInstallableUnitInclusionRules(a1, PlannerHelper.createOptionalInclusionRule(a1)); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); - engine.perform(profile1, new DefaultPhaseSet(), plan2.getOperands(), null, null); + engine.perform(plan2, null); assertProfileContainsAll("A1 is missing", profile1, new IInstallableUnit[] {a1}); - assertEquals(profile1.query(InstallableUnitQuery.ANY, new Collector(), null).size(), 1); + assertEquals(queryResultSize(profile1.query(InstallableUnitQuery.ANY, null)), 1); //Install b1 (this should not change anything for a1) ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.addInstallableUnits(new IInstallableUnit[] {b1}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.OK, plan3.getStatus().getSeverity()); - engine.perform(profile1, new DefaultPhaseSet(), plan3.getOperands(), null, null); + engine.perform(plan3, null); assertProfileContainsAll("A1 or B1 is missing", profile1, new IInstallableUnit[] {a1, b1}); - assertEquals(profile1.query(InstallableUnitQuery.ANY, new Collector(), null).size(), 2); + assertEquals(queryResultSize(profile1.query(InstallableUnitQuery.ANY, null)), 2); //Add a2, this removes a1. ProfileChangeRequest req4 = new ProfileChangeRequest(profile1); req4.addInstallableUnits(new IInstallableUnit[] {a2}); - ProvisioningPlan plan4 = planner.getProvisioningPlan(req4, null, null); + IProvisioningPlan plan4 = planner.getProvisioningPlan(req4, null, null); assertEquals(IStatus.OK, plan4.getStatus().getSeverity()); - engine.perform(profile1, new DefaultPhaseSet(), plan4.getOperands(), null, null); + engine.perform(plan4, null); assertProfileContainsAll("A2 is missing", profile1, new IInstallableUnit[] {a2}); - assertNotIUs(new IInstallableUnit[] {a1}, profile1.query(InstallableUnitQuery.ANY, new Collector(), null).iterator()); - assertEquals(profile1.query(InstallableUnitQuery.ANY, new Collector(), null).size(), 2); + assertNotIUs(new IInstallableUnit[] {a1}, profile1.query(InstallableUnitQuery.ANY, null).iterator()); + assertEquals(queryResultSize(profile1.query(InstallableUnitQuery.ANY, null)), 2); //Try to add a1 again. This will fail because since a1 has been uninstalled in the previous step and we no longer know about its optional inclusion ProfileChangeRequest req5 = new ProfileChangeRequest(profile1); req5.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); + IProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); assertEquals(IStatus.ERROR, plan5.getStatus().getSeverity()); } @@ -93,77 +92,79 @@ public class InclusionRuleTest extends AbstractProvisioningTest { //Install a1 ProfileChangeRequest req = new ProfileChangeRequest(profile2); req.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); - engine.perform(profile2, new DefaultPhaseSet(), plan.getOperands(), null, null); + engine.perform(plan, null); assertProfileContainsAll("A1 is missing", profile2, new IInstallableUnit[] {a1}); - assertEquals(profile2.query(InstallableUnitQuery.ANY, new Collector(), null).size(), 1); + assertEquals(queryResultSize(profile2.query(InstallableUnitQuery.ANY, null)), 1); //Make a1 optional. ProfileChangeRequest req2 = new ProfileChangeRequest(profile2); req2.setInstallableUnitInclusionRules(a1, PlannerHelper.createOptionalInclusionRule(a1)); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); - engine.perform(profile2, new DefaultPhaseSet(), plan2.getOperands(), null, null); + engine.perform(plan2, null); assertProfileContainsAll("A1 is missing", profile2, new IInstallableUnit[] {a1}); - assertEquals(profile2.query(InstallableUnitQuery.ANY, new Collector(), null).size(), 1); + assertEquals(queryResultSize(profile2.query(InstallableUnitQuery.ANY, null)), 1); //Install b1 (this should not change anything for a1) ProfileChangeRequest req3 = new ProfileChangeRequest(profile2); req3.addInstallableUnits(new IInstallableUnit[] {b1}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.OK, plan3.getStatus().getSeverity()); - engine.perform(profile2, new DefaultPhaseSet(), plan3.getOperands(), null, null); + engine.perform(plan3, null); + profile2 = getProfile(profile2.getProfileId()); assertProfileContainsAll("A1 or B1 is missing", profile2, new IInstallableUnit[] {a1, b1}); - assertEquals(profile2.query(InstallableUnitQuery.ANY, new Collector(), null).size(), 2); + assertEquals(queryResultSize(profile2.query(InstallableUnitQuery.ANY, null)), 2); //Remove the optional inclusion rule from a1. a1 and b1 are still here ProfileChangeRequest req5 = new ProfileChangeRequest(profile2); req5.removeInstallableUnitInclusionRules(a1); - ProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); + IProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); assertEquals(IStatus.OK, plan5.getStatus().getSeverity()); - engine.perform(profile2, new DefaultPhaseSet(), plan5.getOperands(), null, null); + engine.perform(plan5, null); + profile2 = getProfile(profile2.getProfileId()); assertProfileContainsAll("A1 or B1 is missing", profile2, new IInstallableUnit[] {a1, b1}); - assertEquals(profile2.query(InstallableUnitQuery.ANY, new Collector(), null).size(), 2); + assertEquals(queryResultSize(profile2.query(InstallableUnitQuery.ANY, null)), 2); } public void testRemoveIUandInclusionRule() { profile3 = createProfile("TestProfile3." + getName()); ProfileChangeRequest req = new ProfileChangeRequest(profile3); req.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); - engine.perform(profile3, new DefaultPhaseSet(), plan.getOperands(), null, null); + engine.perform(plan, null); assertProfileContainsAll("A1 is missing", profile3, new IInstallableUnit[] {a1}); - assertEquals(profile3.query(InstallableUnitQuery.ANY, new Collector(), null).size(), 1); + assertEquals(queryResultSize(profile3.query(InstallableUnitQuery.ANY, null)), 1); //Make a1 optional. ProfileChangeRequest req2 = new ProfileChangeRequest(profile3); req2.setInstallableUnitInclusionRules(a1, PlannerHelper.createOptionalInclusionRule(a1)); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); - engine.perform(profile3, new DefaultPhaseSet(), plan2.getOperands(), null, null); + engine.perform(plan2, null); assertProfileContainsAll("A1 is missing", profile3, new IInstallableUnit[] {a1}); - assertEquals(profile3.query(InstallableUnitQuery.ANY, new Collector(), null).size(), 1); + assertEquals(queryResultSize(profile3.query(InstallableUnitQuery.ANY, null)), 1); //Install b1 (this should not change anything for a1) ProfileChangeRequest req3 = new ProfileChangeRequest(profile3); req3.addInstallableUnits(new IInstallableUnit[] {b1}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.OK, plan3.getStatus().getSeverity()); - engine.perform(profile3, new DefaultPhaseSet(), plan3.getOperands(), null, null); + engine.perform(plan3, null); assertProfileContainsAll("A1 or B1 is missing", profile3, new IInstallableUnit[] {a1, b1}); - assertEquals(profile3.query(InstallableUnitQuery.ANY, new Collector(), null).size(), 2); + assertEquals(queryResultSize(profile3.query(InstallableUnitQuery.ANY, null)), 2); //Remove the a1 and its inclusion rule ProfileChangeRequest req5 = new ProfileChangeRequest(profile3); req5.removeInstallableUnits(new IInstallableUnit[] {a1}); req5.removeInstallableUnitInclusionRules(a1); - ProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); + IProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); assertEquals(IStatus.OK, plan5.getStatus().getSeverity()); - engine.perform(profile3, new DefaultPhaseSet(), plan5.getOperands(), null, null); + engine.perform(plan5, null); assertProfileContainsAll("bB1 is missing", profile3, new IInstallableUnit[] {b1}); - assertEquals(profile3.query(InstallableUnitQuery.ANY, new Collector(), null).size(), 1); + assertEquals(queryResultSize(profile3.query(InstallableUnitQuery.ANY, null)), 1); } public void testAdditionWithInclusionRule() { @@ -171,32 +172,32 @@ public class InclusionRuleTest extends AbstractProvisioningTest { //Try to Install a1 and a2 ProfileChangeRequest req5 = new ProfileChangeRequest(profile4); req5.addInstallableUnits(new IInstallableUnit[] {a1, a2}); - ProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); + IProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); assertEquals(IStatus.ERROR, plan5.getStatus().getSeverity()); //Install a1 and a2 marking a1 optional ProfileChangeRequest req = new ProfileChangeRequest(profile4); req.addInstallableUnits(new IInstallableUnit[] {a1, a2}); req.setInstallableUnitInclusionRules(a1, PlannerHelper.createOptionalInclusionRule(a1)); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); - engine.perform(profile4, new DefaultPhaseSet(), plan.getOperands(), null, null); + engine.perform(plan, null); assertProfileContainsAll("A2 is missing", profile4, new IInstallableUnit[] {a2}); - assertEquals(profile4.query(InstallableUnitQuery.ANY, new Collector(), null).size(), 1); + assertEquals(queryResultSize(profile4.query(InstallableUnitQuery.ANY, null)), 1); //Make a1 optional, this is a no-op since a1 is not in the system ProfileChangeRequest req2 = new ProfileChangeRequest(profile4); req2.setInstallableUnitInclusionRules(a1, PlannerHelper.createOptionalInclusionRule(a1)); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); - engine.perform(profile4, new DefaultPhaseSet(), plan2.getOperands(), null, null); + engine.perform(plan2, null); assertProfileContainsAll("A2 is missing", profile4, new IInstallableUnit[] {a2}); - assertEquals(profile4.query(InstallableUnitQuery.ANY, new Collector(), null).size(), 1); + assertEquals(queryResultSize(profile4.query(InstallableUnitQuery.ANY, null)), 1); //Install a1, this is expected to fail ProfileChangeRequest req3 = new ProfileChangeRequest(profile4); req3.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.ERROR, plan3.getStatus().getSeverity()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/InclusionRuleTest2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/InclusionRuleTest2.java index 55833cfed..668b5caf0 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/InclusionRuleTest2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/InclusionRuleTest2.java @@ -10,17 +10,19 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.query.UserVisibleRootQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.ITouchpointType; +import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; -import org.eclipse.equinox.p2.tests.TestActivator; public class InclusionRuleTest2 extends AbstractProvisioningTest { IInstallableUnit a1; @@ -31,10 +33,10 @@ public class InclusionRuleTest2 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), true); + a1 = createIU("A", Version.create("1.0.0"), true); - createIU("A", new Version("2.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, true, MetadataFactory.createUpdateDescriptor("A", VersionRange.emptyRange, 0, "foo bar"), null); - a2 = createIU("A", new Version("2.0.0"), true); + createIU("A", Version.create("2.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, true, MetadataFactory.createUpdateDescriptor("A", VersionRange.emptyRange, 0, "foo bar"), null); + a2 = createIU("A", Version.create("2.0.0"), true); createTestMetdataRepository(new IInstallableUnit[] {a1, a2}); @@ -47,26 +49,27 @@ public class InclusionRuleTest2 extends AbstractProvisioningTest { //Add into the profile the version a1; ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1}); - req.setInstallableUnitProfileProperty(a1, IInstallableUnit.PROP_PROFILE_ROOT_IU, Boolean.TRUE.toString()); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + req.setInstallableUnitProfileProperty(a1, IProfile.PROP_PROFILE_ROOT_IU, Boolean.TRUE.toString()); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); - engine.perform(profile, new DefaultPhaseSet(), plan.getOperands(), null, null); + engine.perform(plan, null); assertProfileContainsAll("A1 is missing", profile, new IInstallableUnit[] {a1}); - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(TestActivator.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = getProfileRegistry(); profile = profileRegistry.getProfile(profile.getProfileId()); - Collector c = profile.query(new IUProfilePropertyQuery(IInstallableUnit.PROP_PROFILE_ROOT_IU, Boolean.TRUE.toString()), new Collector(), null); - assertEquals(c.size(), 1); + IQueryResult c = profile.query(new UserVisibleRootQuery(), null); + assertEquals(queryResultSize(c), 1); System.gc(); ProfileChangeRequest req2 = ProfileChangeRequest.createByProfileId(profile.getProfileId()); req2.removeInstallableUnits(new IInstallableUnit[] {a1}); req2.addInstallableUnits(new IInstallableUnit[] {a2}); - // req2.setInstallableUnitProfileProperty(a2, IInstallableUnit.PROP_PROFILE_ROOT_IU, Boolean.TRUE.toString()); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + // req2.setInstallableUnitProfileProperty(a2, IProfile.PROP_PROFILE_ROOT_IU, Boolean.TRUE.toString()); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); assertInstallOperand(plan2, a2); - engine.perform(profile, new DefaultPhaseSet(), plan2.getOperands(), null, null); + engine.perform(plan2, null); + profile = getProfile(profile.getProfileId()); assertProfileContains("A2 is missing", profile, new IInstallableUnit[] {a2}); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MinimalInstall.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MinimalInstall.java index b24125558..72c232e0b 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MinimalInstall.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MinimalInstall.java @@ -10,14 +10,14 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MinimalInstall extends AbstractProvisioningTest { @@ -31,13 +31,13 @@ public class MinimalInstall extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B1", new VersionRange("[1.0.0, 2.0.0)"), null)); + a1 = createIU("A", Version.create("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B1", new VersionRange("[1.0.0, 2.0.0)"))); - b1 = createIU("B1", new Version("1.0.0"), true); + b1 = createIU("B1", Version.create("1.0.0"), true); - b11 = createIU("B1", new Version("1.1.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 3.0.0)"), null), NO_PROPERTIES, true); + b11 = createIU("B1", Version.create("1.1.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 3.0.0)")), NO_PROPERTIES, true); - c = createIU("C", new Version(2, 0, 0), true); + c = createIU("C", Version.createOSGi(2, 0, 0), true); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, b11, c}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingDependency.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingDependency.java index 50372b450..358b16a58 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingDependency.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingDependency.java @@ -10,15 +10,17 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.Set; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.director.Explanation; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MissingDependency extends AbstractProvisioningTest { @@ -29,12 +31,12 @@ public class MissingDependency extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), true); + a1 = createIU("A", Version.create("1.0.0"), true); //Missing non optional dependency IRequiredCapability[] req = new IRequiredCapability[1]; req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, false, false, true); - b1 = createIU("B", new Version("1.0.0"), req); + b1 = createIU("B", Version.create("1.0.0"), req); createTestMetdataRepository(new IInstallableUnit[] {a1, b1}); @@ -45,23 +47,24 @@ public class MissingDependency extends AbstractProvisioningTest { public void testContradiction() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1, b1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.ERROR, plan.getStatus().getSeverity()); } public void testExplanation() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1, b1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.ERROR, plan.getStatus().getSeverity()); - Set explanation = plan.getRequestStatus().getExplanations(); + RequestStatus requestStatus = (RequestStatus) plan.getRequestStatus(); + Set explanation = requestStatus.getExplanations(); // System.out.println(explanation); assertEquals(2, explanation.size()); - Set rootConflictingIUs = plan.getRequestStatus().getConflictsWithInstalledRoots(); + Set rootConflictingIUs = requestStatus.getConflictsWithInstalledRoots(); // System.out.println(rootConflictingIUs); assertEquals(1, rootConflictingIUs.size()); assertTrue(rootConflictingIUs.contains(b1)); assertFalse(rootConflictingIUs.contains(a1)); - assertEquals(Explanation.MISSING_REQUIREMENT, plan.getRequestStatus().getShortExplanation()); + assertEquals(Explanation.MISSING_REQUIREMENT, requestStatus.getShortExplanation()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingDependency2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingDependency2.java index 3df9d50e6..143987e9e 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingDependency2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingDependency2.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MissingDependency2 extends AbstractProvisioningTest { @@ -27,12 +31,12 @@ public class MissingDependency2 extends AbstractProvisioningTest { super.setUp(); IRequiredCapability[] reqA = new IRequiredCapability[1]; reqA[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, true); - a1 = createIU("A", new Version("1.0.0"), reqA); + a1 = createIU("A", Version.create("1.0.0"), reqA); //Missing optional dependency IRequiredCapability[] req = new IRequiredCapability[1]; req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, true, false, true); - b1 = createIU("B", new Version("1.0.0"), req); + b1 = createIU("B", Version.create("1.0.0"), req); createTestMetdataRepository(new IInstallableUnit[] {a1, b1}); @@ -43,7 +47,7 @@ public class MissingDependency2 extends AbstractProvisioningTest { public void testContradiction() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingDependency3.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingDependency3.java index 724161f0d..6e633fb7c 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingDependency3.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingDependency3.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MissingDependency3 extends AbstractProvisioningTest { @@ -28,12 +32,12 @@ public class MissingDependency3 extends AbstractProvisioningTest { super.setUp(); IRequiredCapability[] reqA = new IRequiredCapability[1]; reqA[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, true, false, true); - a1 = createIU("A", new Version("1.0.0"), reqA); + a1 = createIU("A", Version.create("1.0.0"), reqA); //Missing dependency IRequiredCapability[] req = new IRequiredCapability[1]; req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, false, false, true); - b1 = createIU("B", new Version("1.0.0"), req); + b1 = createIU("B", Version.create("1.0.0"), req); createTestMetdataRepository(new IInstallableUnit[] {a1, b1}); @@ -44,7 +48,7 @@ public class MissingDependency3 extends AbstractProvisioningTest { public void testContradiction() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, a1); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingNonGreedyRequirement.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingNonGreedyRequirement.java index dbee49eaf..1a40c65a1 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingNonGreedyRequirement.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingNonGreedyRequirement.java @@ -10,15 +10,17 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.Set; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.director.Explanation; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MissingNonGreedyRequirement extends AbstractProvisioningTest { @@ -30,14 +32,14 @@ public class MissingNonGreedyRequirement extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - b1 = createIU("B", new Version("1.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); - c1 = createIU("C", new Version("1.0.0"), true); + c1 = createIU("C", Version.create("1.0.0"), true); IRequiredCapability[] reqB = new IRequiredCapability[2]; reqB[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false); reqB[1] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, true, false, true); - a1 = createIU("A", new Version("1.0.0"), reqB); + a1 = createIU("A", Version.create("1.0.0"), reqB); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, c1}); @@ -49,18 +51,19 @@ public class MissingNonGreedyRequirement extends AbstractProvisioningTest { //The planner returns an error because the requirement from A on B is non greedy and no one brings in B ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.ERROR, plan.getStatus().getSeverity()); } public void testExplanation() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.ERROR, plan.getStatus().getSeverity()); - Set explanation = plan.getRequestStatus().getExplanations(); + RequestStatus requestStatus = (RequestStatus) plan.getRequestStatus(); + Set explanation = requestStatus.getExplanations(); assertFalse(explanation.isEmpty()); - assertTrue(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(a1)); - assertEquals(Explanation.MISSING_REQUIREMENT, plan.getRequestStatus().getShortExplanation()); + assertTrue(requestStatus.getConflictsWithInstalledRoots().contains(a1)); + assertEquals(Explanation.MISSING_REQUIREMENT, requestStatus.getShortExplanation()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingNonGreedyRequirement2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingNonGreedyRequirement2.java index 9e3da6d22..907cdc609 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingNonGreedyRequirement2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingNonGreedyRequirement2.java @@ -10,15 +10,17 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.Set; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.director.Explanation; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MissingNonGreedyRequirement2 extends AbstractProvisioningTest { @@ -29,12 +31,12 @@ public class MissingNonGreedyRequirement2 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - c1 = createIU("C", new Version("1.0.0"), true); + c1 = createIU("C", Version.create("1.0.0"), true); IRequiredCapability[] reqB = new IRequiredCapability[2]; reqB[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false); reqB[1] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, true, false, true); - a1 = createIU("A", new Version("1.0.0"), reqB); + a1 = createIU("A", Version.create("1.0.0"), reqB); createTestMetdataRepository(new IInstallableUnit[] {a1, c1}); @@ -46,19 +48,20 @@ public class MissingNonGreedyRequirement2 extends AbstractProvisioningTest { //The planner returns an error because the requirement from A on B is non greedy and no one brings in B. ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.ERROR, plan.getStatus().getSeverity()); } public void testExplanation() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.ERROR, plan.getStatus().getSeverity()); - Set explanation = plan.getRequestStatus().getExplanations(); + RequestStatus requestStatus = (RequestStatus) plan.getRequestStatus(); + Set explanation = requestStatus.getExplanations(); assertFalse(explanation.isEmpty()); - assertTrue(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(a1)); - assertEquals(Explanation.MISSING_REQUIREMENT, plan.getRequestStatus().getShortExplanation()); + assertTrue(requestStatus.getConflictsWithInstalledRoots().contains(a1)); + assertEquals(Explanation.MISSING_REQUIREMENT, requestStatus.getShortExplanation()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptional.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptional.java index d4dc05c29..db97fcb56 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptional.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptional.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MissingOptional extends AbstractProvisioningTest { @@ -26,8 +30,8 @@ public class MissingOptional extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), true); - b1 = createIU("B", new Version("1.0.0"), true); + a1 = createIU("A", Version.create("1.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); IRequiredCapability[] req = new IRequiredCapability[3]; req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, true); @@ -45,7 +49,7 @@ public class MissingOptional extends AbstractProvisioningTest { //Ensure that D's installation does not fail because of C's absence ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {d}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, a1); assertInstallOperand(plan, b1); //THIS May not be in diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalNonGreedyRequirement.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalNonGreedyRequirement.java index 3eca862c1..2e8e4b529 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalNonGreedyRequirement.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalNonGreedyRequirement.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MissingOptionalNonGreedyRequirement extends AbstractProvisioningTest { @@ -25,11 +29,11 @@ public class MissingOptionalNonGreedyRequirement extends AbstractProvisioningTes protected void setUp() throws Exception { super.setUp(); - b1 = createIU("B", new Version("1.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); IRequiredCapability[] reqB = new IRequiredCapability[1]; reqB[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, true, false, false); - a1 = createIU("A", new Version("1.0.0"), reqB); + a1 = createIU("A", Version.create("1.0.0"), reqB); createTestMetdataRepository(new IInstallableUnit[] {a1, b1}); @@ -41,7 +45,7 @@ public class MissingOptionalNonGreedyRequirement extends AbstractProvisioningTes //The plan does not contains B because the requirement from A on B is non greedy and no one brings in B ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, a1); assertNoOperand(plan, b1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalWithDependencies.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalWithDependencies.java index 3d99c4463..55645f68f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalWithDependencies.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalWithDependencies.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MissingOptionalWithDependencies extends AbstractProvisioningTest { @@ -26,13 +30,13 @@ public class MissingOptionalWithDependencies extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), true); + a1 = createIU("A", Version.create("1.0.0"), true); //B's dependency is missing IRequiredCapability[] reqB = new IRequiredCapability[2]; reqB[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, true, false, true); reqB[1] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, true); - b1 = createIU("B", new Version("1.0.0"), reqB); + b1 = createIU("B", Version.create("1.0.0"), reqB); IRequiredCapability[] req = new IRequiredCapability[2]; req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, true); @@ -49,7 +53,7 @@ public class MissingOptionalWithDependencies extends AbstractProvisioningTest { //Ensure that D's installation does not fail because of C's absence ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {d}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, a1); assertInstallOperand(plan, b1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalWithDependencies2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalWithDependencies2.java index 28fcba00e..5f06ca9cd 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalWithDependencies2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalWithDependencies2.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MissingOptionalWithDependencies2 extends AbstractProvisioningTest { @@ -28,15 +32,15 @@ public class MissingOptionalWithDependencies2 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), true); - c1 = createIU("C", new Version("1.0.0"), true); - c2 = createIU("C", new Version("2.0.0"), true); + a1 = createIU("A", Version.create("1.0.0"), true); + c1 = createIU("C", Version.create("1.0.0"), true); + c2 = createIU("C", Version.create("2.0.0"), true); //B's dependency on C can not be satisfied IRequiredCapability[] reqB = new IRequiredCapability[2]; reqB[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 1.0.0]"), null, true, false, true); reqB[1] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, true); - b1 = createIU("B", new Version("1.0.0"), reqB); + b1 = createIU("B", Version.create("1.0.0"), reqB); IRequiredCapability[] req = new IRequiredCapability[3]; req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, true); @@ -54,7 +58,7 @@ public class MissingOptionalWithDependencies2 extends AbstractProvisioningTest { //Ensure that D's installation does not fail because of C's absence ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {d}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, d); assertInstallOperand(plan, a1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalWithDependencies3.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalWithDependencies3.java index f19a3a5a6..2f6cdbb92 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalWithDependencies3.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MissingOptionalWithDependencies3.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MissingOptionalWithDependencies3 extends AbstractProvisioningTest { @@ -28,15 +32,15 @@ public class MissingOptionalWithDependencies3 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), true); - c1 = createIU("C", new Version("1.0.0"), true); - c2 = createIU("C", new Version("2.0.0"), true); + a1 = createIU("A", Version.create("1.0.0"), true); + c1 = createIU("C", Version.create("1.0.0"), true); + c2 = createIU("C", Version.create("2.0.0"), true); //B's dependency on C can not be satisfied IRequiredCapability[] reqB = new IRequiredCapability[2]; reqB[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 1.0.0]"), null, true, false, true); reqB[1] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, true); - b1 = createIU("B", new Version("1.0.0"), reqB); + b1 = createIU("B", Version.create("1.0.0"), reqB); IRequiredCapability[] req = new IRequiredCapability[3]; req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, true); @@ -54,7 +58,7 @@ public class MissingOptionalWithDependencies3 extends AbstractProvisioningTest { //Ensure that D's installation does not fail because of C's absence ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {d}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, a1); assertInstallOperand(plan, b1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MultipleProvider.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MultipleProvider.java index 8e24a5d42..84665e854 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MultipleProvider.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MultipleProvider.java @@ -10,14 +10,14 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MultipleProvider extends AbstractProvisioningTest { @@ -33,17 +33,17 @@ public class MultipleProvider extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B1", new VersionRange("[1.0.0, 2.0.0)"), null)); + a1 = createIU("A", Version.create("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B1", new VersionRange("[1.0.0, 2.0.0)"))); - b1 = createIU("B1", new Version("1.0.0"), true); + b1 = createIU("B1", Version.create("1.0.0"), true); - b11 = createIU("B1", new Version("1.1.0"), true); + b11 = createIU("B1", Version.create("1.1.0"), true); - b12 = createIU("B1", new Version("1.2.0"), true); + b12 = createIU("B1", Version.create("1.2.0"), true); - b13 = createIU("B1", new Version("1.3.0"), true); + b13 = createIU("B1", Version.create("1.3.0"), true); - b14 = createIU("B1", new Version("1.4.0"), true); + b14 = createIU("B1", Version.create("1.4.0"), true); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, b11, b12, b13, b14}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MultipleSingleton.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MultipleSingleton.java index 66e338422..081cc6f78 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MultipleSingleton.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/MultipleSingleton.java @@ -10,17 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.util.Set; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.director.Explanation; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.ProvisioningPlan; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MultipleSingleton extends AbstractProvisioningTest { @@ -35,32 +34,32 @@ public class MultipleSingleton extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), true); + a1 = createIU("A", Version.create("1.0.0"), true); - a2 = createIU("A", new Version("2.0.0"), true); + a2 = createIU("A", Version.create("2.0.0"), true); - a3 = createIU("A", new Version("3.0.0"), false); + a3 = createIU("A", Version.create("3.0.0"), false); - a4 = createIU("A", new Version("4.0.0"), false); + a4 = createIU("A", Version.create("4.0.0"), false); - x = createIU("X", new Version(2, 0, 0), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 4.1.0)"), null)); + x = createIU("X", Version.createOSGi(2, 0, 0), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 4.1.0)"))); IRequiredCapability c1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"), null, false, false); IRequiredCapability c2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 2.0.0]"), null, false, false); - y = createIU("Y", new Version(2, 0, 0), new IRequiredCapability[] {c1, c2}); + y = createIU("Y", Version.createOSGi(2, 0, 0), new IRequiredCapability[] {c1, c2}); IRequiredCapability c3 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[3.0.0, 3.0.0]"), null, false, false); IRequiredCapability c4 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[4.0.0, 4.0.0]"), null, false, false); - z = createIU("Z", new Version(2, 0, 0), new IRequiredCapability[] {c3, c4}); + z = createIU("Z", Version.createOSGi(2, 0, 0), new IRequiredCapability[] {c3, c4}); IRequiredCapability c5 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"), null, false, false); IRequiredCapability c6 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[3.0.0, 3.0.0]"), null, false, false); - w = createIU("W", new Version(2, 0, 0), new IRequiredCapability[] {c5, c6}); + w = createIU("W", Version.createOSGi(2, 0, 0), new IRequiredCapability[] {c5, c6}); IRequiredCapability c7 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 2.0.0]"), null, false, false); IRequiredCapability c8 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[3.0.0, 4.0.0]"), null, false, false); - v = createIU("V", new Version(2, 0, 0), new IRequiredCapability[] {c7}); - u = createIU("U", new Version(2, 0, 0), new IRequiredCapability[] {c8}); + v = createIU("V", Version.createOSGi(2, 0, 0), new IRequiredCapability[] {c7}); + u = createIU("U", Version.createOSGi(2, 0, 0), new IRequiredCapability[] {c8}); createTestMetdataRepository(new IInstallableUnit[] {a1, a2, a3, a4, w, x, y, z}); @@ -72,8 +71,8 @@ public class MultipleSingleton extends AbstractProvisioningTest { public void test1() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {x}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); - assertEquals(1, plan.getCompleteState().query(new InstallableUnitQuery("X"), new Collector(), null).size()); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(req, null, null); + assertEquals(1, queryResultSize(plan.getCompleteState().query(new InstallableUnitQuery("X"), null))); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); } @@ -87,14 +86,15 @@ public class MultipleSingleton extends AbstractProvisioningTest { public void testExplanation2() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {y}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.ERROR, plan.getStatus().getSeverity()); - Set explanation = plan.getRequestStatus().getExplanations(); + final RequestStatus requestStatus = (RequestStatus) plan.getRequestStatus(); + Set explanation = requestStatus.getExplanations(); // System.out.println(explanation); assertFalse(explanation.isEmpty()); - assertEquals(Explanation.VIOLATED_SINGLETON_CONSTRAINT, plan.getRequestStatus().getShortExplanation()); - assertTrue(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(y)); - assertEquals(1, plan.getRequestStatus().getConflictsWithInstalledRoots().size()); + assertEquals(Explanation.VIOLATED_SINGLETON_CONSTRAINT, requestStatus.getShortExplanation()); + assertTrue(requestStatus.getConflictsWithInstalledRoots().contains(y)); + assertEquals(1, requestStatus.getConflictsWithInstalledRoots().size()); } @@ -115,13 +115,14 @@ public class MultipleSingleton extends AbstractProvisioningTest { public void testExplanation4() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {w}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.ERROR, plan.getStatus().getSeverity()); - Set explanation = plan.getRequestStatus().getExplanations(); + final RequestStatus requestStatus = (RequestStatus) plan.getRequestStatus(); + Set explanation = requestStatus.getExplanations(); // System.out.println(explanation); assertFalse(explanation.isEmpty()); - assertEquals(Explanation.VIOLATED_SINGLETON_CONSTRAINT, plan.getRequestStatus().getShortExplanation()); - assertTrue(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(w)); + assertEquals(Explanation.VIOLATED_SINGLETON_CONSTRAINT, requestStatus.getShortExplanation()); + assertTrue(requestStatus.getConflictsWithInstalledRoots().contains(w)); } @@ -149,13 +150,14 @@ public class MultipleSingleton extends AbstractProvisioningTest { public void testExplanation5() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {u, v}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.ERROR, plan.getStatus().getSeverity()); - Set explanation = plan.getRequestStatus().getExplanations(); + final RequestStatus requestStatus = (RequestStatus) plan.getRequestStatus(); + Set explanation = requestStatus.getExplanations(); assertFalse(explanation.isEmpty()); - assertEquals(Explanation.VIOLATED_SINGLETON_CONSTRAINT, plan.getRequestStatus().getShortExplanation()); - assertTrue(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(u)); - assertTrue(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(v)); + assertEquals(Explanation.VIOLATED_SINGLETON_CONSTRAINT, requestStatus.getShortExplanation()); + assertTrue(requestStatus.getConflictsWithInstalledRoots().contains(u)); + assertTrue(requestStatus.getConflictsWithInstalledRoots().contains(v)); // System.out.println(explanation); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NegationTesting.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NegationTesting.java index a2e498c6f..d002ce54b 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NegationTesting.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NegationTesting.java @@ -1,52 +1,55 @@ package org.eclipse.equinox.p2.tests.planner; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; + import java.util.*; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.director.Slicer; -import org.eclipse.equinox.internal.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.ProvidedCapability; +import org.eclipse.equinox.internal.p2.metadata.RequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class NegationTesting extends AbstractProvisioningTest { private static final String NS = "theNamespace"; private static final String N = "theName"; - public void testNot1() { - RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.0.0, 1.2.0)"), null, false, false); - NotRequirement req = new NotRequirement(req1); - ProvidedCapability prov = new ProvidedCapability(NS, N, new Version(1, 5, 0)); - assertTrue(prov.satisfies(req)); - } - - public void testNot2() { - RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.0.0, 1.2.0)"), null, false, false); - NotRequirement req = new NotRequirement(req1); - ProvidedCapability prov = new ProvidedCapability(NS, N, new Version(1, 1, 0)); - assertFalse(prov.satisfies(req)); - } - - public void testNot3() { - RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.0.0, 1.2.0)"), null, false, false); - // RequiredCapability req2 = new RequiredCapability(NS, N, new VersionRange("[1.5.0, 2.0.0)"), null, false, false); - NotRequirement req = new NotRequirement(req1); - ProvidedCapability prov = new ProvidedCapability("foo", "bar", new Version(1, 5, 0)); - assertTrue(prov.satisfies(req)); - } + // public void testNot1() { + // RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.0.0, 1.2.0)"), null, 0, 0, false); + // ProvidedCapability prov = new ProvidedCapability(NS, N, Version.createOSGi(1, 5, 0)); + // assertTrue(prov.satisfies(req1)); + // } + // + // public void testNot2() { + // RequiredCapability req = new RequiredCapability(NS, N, new VersionRange("[1.0.0, 1.2.0)"), null, 0, 0, false); + // ProvidedCapability prov = new ProvidedCapability(NS, N, Version.createOSGi(1, 1, 0)); + // assertFalse(prov.satisfies(req)); + // } + // + // public void testNot3() { + // RequiredCapability req = new RequiredCapability(NS, N, new VersionRange("[1.0.0, 1.2.0)"), null, 0, 0, false); + // // RequiredCapability req2 = new RequiredCapability(NS, N, new VersionRange("[1.5.0, 2.0.0)"), null, false, false); + // ProvidedCapability prov = new ProvidedCapability("foo", "bar", Version.createOSGi(1, 5, 0)); + // assertTrue(prov.satisfies(req)); + // } //Test the slicer and the resolver. public void testNot4() { MetadataFactory.InstallableUnitDescription iud1 = new MetadataFactory.InstallableUnitDescription(); iud1.setId("TestNegation4"); iud1.setVersion(Version.create("1.0.0")); - RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.1.0, 1.2.0)"), null, false, false); - NotRequirement req = new NotRequirement(req1); + RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.1.0, 1.2.0)"), null, 0, 0, false); RequiredCapability req2 = new RequiredCapability(NS, N, new VersionRange("[1.0.0, 2.0.0)"), null, false, false); Collection requirements = new ArrayList(); - requirements.add(req); + requirements.add(req1); requirements.add(req2); iud1.addRequiredCapabilities(requirements); Collection capabilities = new ArrayList(); @@ -76,21 +79,21 @@ public class NegationTesting extends AbstractProvisioningTest { // Verify that the slice includes iu3 because the requirement from iu1 is a range including the provided capability of iu3. Slicer slicer = new Slicer(repo, new Properties(), false); IQueryable slice = slicer.slice(new IInstallableUnit[] {iu1}, new NullProgressMonitor()); - assertEquals(3, slice.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); + assertEquals(3, queryResultSize(slice.query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); //Verify that the resolution succeeds and does not return iu3 since it is excluded by the requirement of iu1 IProfile profile = createProfile("TestProfile." + getName()); IPlanner planner = createPlanner(); ProfileChangeRequest changeRequest = new ProfileChangeRequest(profile); changeRequest.addInstallableUnits(new IInstallableUnit[] {iu1}); - ProvisioningPlan plan = planner.getProvisioningPlan(changeRequest, null, null); - assertEquals(0, plan.getCompleteState().query(new InstallableUnitQuery("ProviderOf1_1_1"), new Collector(), null).size()); - assertEquals(2, plan.getCompleteState().query(InstallableUnitQuery.ANY, new Collector(), null).size()); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(changeRequest, null, null); + assertEquals(0, queryResultSize(plan.getCompleteState().query(new InstallableUnitQuery("ProviderOf1_1_1"), null))); + assertEquals(2, queryResultSize(plan.getCompleteState().query(InstallableUnitQuery.ANY, null))); //Verify that the installing iu1 and iu3 will result in a conflict since iu3 is excluded by the requirement of iu1 ProfileChangeRequest changeRequest2 = new ProfileChangeRequest(profile); changeRequest2.addInstallableUnits(new IInstallableUnit[] {iu1, iu3}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(changeRequest2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(changeRequest2, null, null); assertNotOK("The resolution should be failing because of the negation requirement.", plan2.getStatus()); } @@ -98,11 +101,10 @@ public class NegationTesting extends AbstractProvisioningTest { MetadataFactory.InstallableUnitDescription iud1 = new MetadataFactory.InstallableUnitDescription(); iud1.setId("TestNegation4"); iud1.setVersion(Version.create("1.0.0")); - RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.1.0, 1.2.0)"), null, false, false); - NotRequirement req = new NotRequirement(req1); + RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.1.0, 1.2.0)"), null, 0, 0, false); RequiredCapability req2 = new RequiredCapability(NS, N, new VersionRange("[1.0.0, 1.1.0)"), null, false, false); Collection requirements = new ArrayList(); - requirements.add(req); + requirements.add(req1); requirements.add(req2); iud1.addRequiredCapabilities(requirements); Collection capabilities = new ArrayList(); @@ -132,19 +134,18 @@ public class NegationTesting extends AbstractProvisioningTest { //Test the slicer. The slice will not contain iu3 because none of the range of iu1 cause it to be brought in. Slicer slicer = new Slicer(repo, new Properties(), false); IQueryable slice = slicer.slice(new IInstallableUnit[] {iu1}, new NullProgressMonitor()); - assertEquals(0, slice.query(new InstallableUnitQuery("ProviderOf1_1_1"), new Collector(), new NullProgressMonitor()).size()); - assertEquals(2, slice.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); + assertEquals(0, queryResultSize(slice.query(new InstallableUnitQuery("ProviderOf1_1_1"), new NullProgressMonitor()))); + assertEquals(2, queryResultSize(slice.query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); } public void testNot6() { MetadataFactory.InstallableUnitDescription iud1 = new MetadataFactory.InstallableUnitDescription(); iud1.setId("TestNegation4"); iud1.setVersion(Version.create("1.0.0")); - RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.1.0, 1.2.0)"), null, false, false); - NotRequirement req = new NotRequirement(req1); + RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.1.0, 1.2.0)"), null, 0, 0, false); RequiredCapability req2 = new RequiredCapability(NS, N, new VersionRange("[1.0.0, 1.1.0)"), null, false, false); Collection requirements = new ArrayList(); - requirements.add(req); + requirements.add(req1); requirements.add(req2); iud1.addRequiredCapabilities(requirements); Collection capabilities = new ArrayList(); @@ -165,17 +166,17 @@ public class NegationTesting extends AbstractProvisioningTest { //Test the slicer. The slice will not contain iu3 because none of the range of iu1 cause it to be brought in. Slicer slicer = new Slicer(repo, new Properties(), false); IQueryable slice = slicer.slice(new IInstallableUnit[] {iu1}, new NullProgressMonitor()); - assertEquals(0, slice.query(new InstallableUnitQuery("ProviderOf1_1_1"), new Collector(), new NullProgressMonitor()).size()); - assertEquals(2, slice.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); + assertEquals(0, queryResultSize(slice.query(new InstallableUnitQuery("ProviderOf1_1_1"), new NullProgressMonitor()))); + assertEquals(2, queryResultSize(slice.query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); //Verify that the negation can not fail the resolution when the IUs satisfying the negative requirement are not there IProfile profile = createProfile("TestProfile." + getName()); IPlanner planner = createPlanner(); ProfileChangeRequest changeRequest = new ProfileChangeRequest(profile); changeRequest.addInstallableUnits(new IInstallableUnit[] {iu1}); - ProvisioningPlan plan = planner.getProvisioningPlan(changeRequest, null, null); - assertEquals(0, plan.getCompleteState().query(new InstallableUnitQuery("ProviderOf1_1_1"), new Collector(), null).size()); - assertEquals(2, plan.getCompleteState().query(InstallableUnitQuery.ANY, new Collector(), null).size()); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(changeRequest, null, null); + assertEquals(0, queryResultSize(plan.getCompleteState().query(new InstallableUnitQuery("ProviderOf1_1_1"), null))); + assertEquals(2, queryResultSize(plan.getCompleteState().query(InstallableUnitQuery.ANY, null))); } //Test the slicer and the resolver. @@ -183,11 +184,10 @@ public class NegationTesting extends AbstractProvisioningTest { MetadataFactory.InstallableUnitDescription iud1 = new MetadataFactory.InstallableUnitDescription(); iud1.setId("TestNegation4"); iud1.setVersion(Version.create("1.0.0")); - RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.1.0, 1.2.0)"), null, false, false); - NotRequirement req = new NotRequirement(req1); + RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.1.0, 1.2.0)"), null, 0, 0, false); RequiredCapability req2 = new RequiredCapability(NS, N, new VersionRange("[1.0.0, 2.0.0)"), null, false, false); Collection requirements = new ArrayList(); - requirements.add(req); + requirements.add(req1); requirements.add(req2); iud1.addRequiredCapabilities(requirements); Collection capabilities = new ArrayList(); @@ -220,21 +220,21 @@ public class NegationTesting extends AbstractProvisioningTest { // Verify that the slice includes iu3 because the requirement from iu1 is a range including the provided capability of iu3. Slicer slicer = new Slicer(repo, new Properties(), false); IQueryable slice = slicer.slice(new IInstallableUnit[] {iu1}, new NullProgressMonitor()); - assertEquals(3, slice.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); + assertEquals(3, queryResultSize(slice.query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); //Verify that the resolution succeeds and does not return iu3 since it is excluded by the requirement of iu1 IProfile profile = createProfile("TestProfile." + getName()); IPlanner planner = createPlanner(); ProfileChangeRequest changeRequest = new ProfileChangeRequest(profile); changeRequest.addInstallableUnits(new IInstallableUnit[] {iu1}); - ProvisioningPlan plan = planner.getProvisioningPlan(changeRequest, null, null); - assertEquals(0, plan.getCompleteState().query(new InstallableUnitQuery("ProviderOf1_1_1"), new Collector(), null).size()); - assertEquals(2, plan.getCompleteState().query(InstallableUnitQuery.ANY, new Collector(), null).size()); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(changeRequest, null, null); + assertEquals(0, queryResultSize(plan.getCompleteState().query(new InstallableUnitQuery("ProviderOf1_1_1"), null))); + assertEquals(2, queryResultSize(plan.getCompleteState().query(InstallableUnitQuery.ANY, null))); //Verify that the installing iu1 and iu3 will result in a conflict since iu3 is excluded by the requirement of iu1 ProfileChangeRequest changeRequest2 = new ProfileChangeRequest(profile); changeRequest2.addInstallableUnits(new IInstallableUnit[] {iu1, iu3}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(changeRequest2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(changeRequest2, null, null); assertNotOK("The resolution should be failing because of the negation requirement.", plan2.getStatus()); } @@ -242,11 +242,10 @@ public class NegationTesting extends AbstractProvisioningTest { MetadataFactory.InstallableUnitDescription iud1 = new MetadataFactory.InstallableUnitDescription(); iud1.setId("TestNegation4"); iud1.setVersion(Version.create("1.0.0")); - RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.1.0, 1.2.0)"), null, false, false); - NotRequirement req = new NotRequirement(req1); + RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.1.0, 1.2.0)"), null, 0, 0, false); RequiredCapability req2 = new RequiredCapability(NS, N, new VersionRange("[1.0.0, 2.0.0)"), null, false, false); Collection requirements = new ArrayList(); - requirements.add(req); + requirements.add(req1); requirements.add(req2); iud1.addRequiredCapabilities(requirements); Collection capabilities = new ArrayList(); @@ -287,26 +286,26 @@ public class NegationTesting extends AbstractProvisioningTest { // Verify that the slice includes iu3 Slicer slicer = new Slicer(repo, new Properties(), false); IQueryable slice = slicer.slice(new IInstallableUnit[] {iu1, iu4}, new NullProgressMonitor()); - assertEquals(4, slice.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); + assertEquals(4, queryResultSize(slice.query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); // Verify that the slice includes iu3 Slicer slicer2 = new Slicer(repo, new Properties(), false); IQueryable slice2 = slicer2.slice(new IInstallableUnit[] {iu4}, new NullProgressMonitor()); - assertEquals(2, slice2.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); + assertEquals(2, queryResultSize(slice2.query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); //Verify that the resolution succeeds and does not return iu3 since it is excluded by the requirement of iu1 IProfile profile = createProfile("TestProfile." + getName()); IPlanner planner = createPlanner(); ProfileChangeRequest changeRequest = new ProfileChangeRequest(profile); changeRequest.addInstallableUnits(new IInstallableUnit[] {iu1}); - ProvisioningPlan plan = planner.getProvisioningPlan(changeRequest, null, null); - assertEquals(0, plan.getCompleteState().query(new InstallableUnitQuery("ProviderOf1_1_1"), new Collector(), null).size()); - assertEquals(2, plan.getCompleteState().query(InstallableUnitQuery.ANY, new Collector(), null).size()); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(changeRequest, null, null); + assertEquals(0, queryResultSize(plan.getCompleteState().query(new InstallableUnitQuery("ProviderOf1_1_1"), null))); + assertEquals(2, queryResultSize(plan.getCompleteState().query(InstallableUnitQuery.ANY, null))); //Verify that the installing iu1 and iu4 will result in a conflict since iu3 is excluded by the requirement of iu1 ProfileChangeRequest changeRequest2 = new ProfileChangeRequest(profile); changeRequest2.addInstallableUnits(new IInstallableUnit[] {iu1, iu4}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(changeRequest2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(changeRequest2, null, null); assertNotOK("The resolution should be failing because of the negation requirement.", plan2.getStatus()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NoRequirements.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NoRequirements.java index d607a6cd4..7b6dc4d68 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NoRequirements.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NoRequirements.java @@ -10,14 +10,14 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class NoRequirements extends AbstractProvisioningTest { @@ -28,7 +28,7 @@ public class NoRequirements extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"), null)); + a1 = createIU("A", Version.create("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"))); createTestMetdataRepository(new IInstallableUnit[] {a1}); profile = createProfile(NoRequirements.class.getName()); planner = createPlanner(); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NonMinimalState.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NonMinimalState.java index b192e0201..b9d58f27a 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NonMinimalState.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NonMinimalState.java @@ -15,11 +15,15 @@ import java.net.URI; import java.util.*; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.query.IUProfilePropertyQuery; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.ExpressionQuery; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class NonMinimalState extends AbstractProvisioningTest { @@ -42,9 +46,9 @@ public class NonMinimalState extends AbstractProvisioningTest { public void testValidateProfileWithRepository() { IPlanner planner = createPlanner(); ProfileChangeRequest request = new ProfileChangeRequest(profile); - ProvisioningPlan plan = planner.getProvisioningPlan(request, null, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, null, new NullProgressMonitor()); assertOK("Plan OK", plan.getStatus()); - assertEquals(0, plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.tptp.platform.agentcontroller"), new Collector(), null).size()); + assertTrue(plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.tptp.platform.agentcontroller"), null).isEmpty()); why("slf4j.api"); why("slf4j.jcl"); why("org.eclipse.tptp.platform.iac.administrator"); @@ -55,15 +59,15 @@ public class NonMinimalState extends AbstractProvisioningTest { IPlanner planner = createPlanner(); ProfileChangeRequest request = new ProfileChangeRequest(profile); ProvisioningContext ctx = new ProvisioningContext(new URI[0]); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); assertOK("Plan OK", plan.getStatus()); - assertEquals(0, plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.tptp.platform.agentcontroller"), new Collector(), null).size()); + assertTrue(plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.tptp.platform.agentcontroller"), null).isEmpty()); } private void why(String id) { System.out.println("=-=-=" + id + "=-=-="); visited = new HashSet(); - Collector roots = profile.query(new IUProfilePropertyQuery("org.eclipse.equinox.p2.type.root", "true"), new Collector(), null); + IQueryResult roots = profile.query(new IUProfilePropertyQuery("org.eclipse.equinox.p2.type.root", "true"), null); searchedId = id; for (Iterator iterator = roots.iterator(); iterator.hasNext();) { IInstallableUnit type = (IInstallableUnit) iterator.next(); @@ -82,19 +86,19 @@ public class NonMinimalState extends AbstractProvisioningTest { visited.add(iu); return false; } - IRequiredCapability[] caps = iu.getRequiredCapabilities(); - for (int i = 0; i < caps.length; i++) { - boolean result = expandRequirement(iu, caps[i]); + Collection reqs = iu.getRequiredCapabilities(); + for (IRequirement req : reqs) { + boolean result = expandRequirement(iu, req); if (result) { - System.out.println(iu + " because " + caps[i].toString()); + System.out.println(iu + " because " + req.toString()); return true; } } return false; } - private boolean expandRequirement(IInstallableUnit iu, IRequiredCapability req) { - Collector matches = profile.query(new CapabilityQuery(req), new Collector(), null); + private boolean expandRequirement(IInstallableUnit iu, IRequirement req) { + IQueryResult matches = profile.query(new ExpressionQuery(IInstallableUnit.class, req.getMatches()), null); for (Iterator iterator = matches.iterator(); iterator.hasNext();) { IInstallableUnit match = (IInstallableUnit) iterator.next(); if (match.getId().equals(searchedId)) diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NonMinimalState2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NonMinimalState2.java index b6b3973b0..500229461 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NonMinimalState2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/NonMinimalState2.java @@ -10,16 +10,19 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class NonMinimalState2 extends AbstractProvisioningTest { @@ -35,12 +38,12 @@ public class NonMinimalState2 extends AbstractProvisioningTest { IPlanner planner = createPlanner(); ProfileChangeRequest request = new ProfileChangeRequest(profile); - request.addInstallableUnits((IInstallableUnit[]) getMetadataRepositoryManager().query(new InstallableUnitQuery("org.mortbay.jetty.server"), new Collector(), null).toArray(IInstallableUnit.class)); - ProvisioningPlan plan = planner.getProvisioningPlan(request, null, new NullProgressMonitor()); + request.addInstallableUnits((IInstallableUnit[]) getMetadataRepositoryManager().query(new InstallableUnitQuery("org.mortbay.jetty.server"), null).toArray(IInstallableUnit.class)); + IProvisioningPlan plan = planner.getProvisioningPlan(request, null, new NullProgressMonitor()); assertOK("Plan OK", plan.getStatus()); - assertEquals(0, plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.tptp.platform.agentcontroller"), new Collector(), null).size()); - assertEquals(0, plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.tptp.platform.iac.administrator"), new Collector(), null).size()); + assertTrue(plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.tptp.platform.agentcontroller"), null).isEmpty()); + assertTrue(plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.tptp.platform.iac.administrator"), null).isEmpty()); } // public void testp2Source() { @@ -60,12 +63,12 @@ public class NonMinimalState2 extends AbstractProvisioningTest { IPlanner planner = createPlanner(); ProfileChangeRequest request = new ProfileChangeRequest(profile); - request.addInstallableUnits((IInstallableUnit[]) getMetadataRepositoryManager().query(new InstallableUnitQuery("org.mortbay.jetty.server"), new Collector(), null).toArray(IInstallableUnit.class)); - ProvisioningPlan plan = planner.getProvisioningPlan(request, null, new NullProgressMonitor()); + request.addInstallableUnits((IInstallableUnit[]) getMetadataRepositoryManager().query(new InstallableUnitQuery("org.mortbay.jetty.server"), null).toArray(IInstallableUnit.class)); + IProvisioningPlan plan = planner.getProvisioningPlan(request, null, new NullProgressMonitor()); assertOK("Plan OK", plan.getStatus()); - assertEquals(0, plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.tptp.platform.agentcontroller"), new Collector(), null).size()); - assertEquals(0, plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.tptp.platform.iac.administrator"), new Collector(), null).size()); + assertTrue(plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.tptp.platform.agentcontroller"), null).isEmpty()); + assertTrue(plan.getAdditions().query(new InstallableUnitQuery("org.eclipse.tptp.platform.iac.administrator"), null).isEmpty()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ORTesting.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ORTesting.java deleted file mode 100644 index 2b391867a..000000000 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ORTesting.java +++ /dev/null @@ -1,150 +0,0 @@ -package org.eclipse.equinox.p2.tests.planner; - -import java.util.ArrayList; -import java.util.Collection; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.equinox.internal.p2.director.Slicer; -import org.eclipse.equinox.internal.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; - -public class ORTesting extends AbstractProvisioningTest { - //A[1.0] v A[1.1] - //!A[1.0.2] - - //A v C v !D[1.0.0, 1.1.0] <-- What is the semantics of negation on a range? - - private static final String NS = "theNamespace"; - private static final String N = "theName"; - - //A v C v C[1.0.0] - public void testOR() { - RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.0.0, 1.2.0)"), null, false, false); - // RequiredCapability req2 = new RequiredCapability(NS, N, new VersionRange("[1.5.0, 2.0.0)"), null, false, false); - ORRequirement req = new ORRequirement(new IRequiredCapability[] {req1}); - ProvidedCapability prov = new ProvidedCapability(NS, N, new Version(1, 5, 0)); - assertFalse(prov.satisfies(req)); - } - - public void testOR2() { - RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.0.0, 1.2.0)"), null, false, false); - RequiredCapability req2 = new RequiredCapability(NS, N, new VersionRange("[1.5.0, 2.0.0)"), null, false, false); - ORRequirement req = new ORRequirement(new IRequiredCapability[] {req1, req2}); - ProvidedCapability prov = new ProvidedCapability(NS, N, new Version(1, 5, 0)); - assertTrue(prov.satisfies(req)); - } - - public void testOR3() { - MetadataFactory.InstallableUnitDescription iud1 = new MetadataFactory.InstallableUnitDescription(); - iud1.setId("TestOr"); - iud1.setVersion(Version.create("1.0.0")); - RequiredCapability req1 = new RequiredCapability(NS, N, new VersionRange("[1.1.0, 1.2.0)"), null, false, false); - RequiredCapability req2 = new RequiredCapability(NS, N, new VersionRange("[1.3.0, 1.4.0)"), null, false, false); - Collection requirements = new ArrayList(); - requirements.add(new ORRequirement(new IRequiredCapability[] {req1, req2})); - iud1.addRequiredCapabilities(requirements); - Collection capabilities = new ArrayList(); - capabilities.add(new ProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, "TestOr", Version.create("1.0.0"))); - iud1.addProvidedCapabilities(capabilities); - IInstallableUnit iu1 = MetadataFactory.createInstallableUnit(iud1); - - MetadataFactory.InstallableUnitDescription iud2 = new MetadataFactory.InstallableUnitDescription(); - iud2.setId("ProviderOf1_0_0"); - iud2.setVersion(Version.create("1.0.0")); - Collection capabilities2 = new ArrayList(); - capabilities2.add(MetadataFactory.createProvidedCapability(NS, N, Version.create("1.0.0"))); - iud2.addProvidedCapabilities(capabilities2); - IInstallableUnit iu2 = MetadataFactory.createInstallableUnit(iud2); - - MetadataFactory.InstallableUnitDescription iud3 = new MetadataFactory.InstallableUnitDescription(); - iud3.setId("ProviderOf1_1_1"); - iud3.setVersion(Version.create("1.0.0")); - Collection capabilities3 = new ArrayList(); - capabilities3.add(MetadataFactory.createProvidedCapability(NS, N, Version.create("1.1.1"))); - capabilities3.add(new ProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, "ProviderOf1_1_1", Version.create("1.0.0"))); - iud3.addProvidedCapabilities(capabilities3); - IInstallableUnit iu3 = MetadataFactory.createInstallableUnit(iud3); - - MetadataFactory.InstallableUnitDescription iud4 = new MetadataFactory.InstallableUnitDescription(); - iud4.setId("ProviderOf1_3_0"); - iud4.setVersion(Version.create("1.0.0")); - Collection capabilities4 = new ArrayList(); - capabilities4.add(MetadataFactory.createProvidedCapability(NS, N, Version.create("1.3.0"))); - capabilities4.add(new ProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, "ProviderOf1_3_0", Version.create("1.0.0"))); - iud4.addProvidedCapabilities(capabilities4); - IInstallableUnit iu4 = MetadataFactory.createInstallableUnit(iud4); - - IMetadataRepository repo = createTestMetdataRepository(new IInstallableUnit[] {iu1, iu2, iu3, iu4}); - - Slicer slicer = new Slicer(repo, null, false); - IQueryable slice = slicer.slice(new IInstallableUnit[] {iu1}, new NullProgressMonitor()); - Collector c = slice.query(InstallableUnitQuery.ANY, new Collector(), null); - assertEquals(3, c.size()); - - IPlanner planner = createPlanner(); - IProfile profile = createProfile("testOR3"); - ProfileChangeRequest changeRequest = new ProfileChangeRequest(profile); - changeRequest.addInstallableUnits(new IInstallableUnit[] {iu1}); - ProvisioningPlan plan = planner.getProvisioningPlan(changeRequest, null, null); - assertOK("Plan OK", plan.getStatus()); - // assertEquals(1, plan.getCompleteState().query(new InstallableUnitQuery(id), collector, monitor)) - } - - public void testOR4() { - IInstallableUnit a1 = createIU("A", Version.create("1.0.0"), true); - IInstallableUnit a2 = createIU("A", Version.create("2.0.0"), true); - - MetadataFactory.InstallableUnitDescription iud1 = new MetadataFactory.InstallableUnitDescription(); - iud1.setId("TestOr"); - iud1.setVersion(Version.create("1.0.0")); - RequiredCapability req1 = new RequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.2.0)"), null, false, false); - RequiredCapability req2 = new RequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 2.2.0)"), null, false, false); - - Collection requirements = new ArrayList(); - requirements.add(new ORRequirement(new IRequiredCapability[] {req1, req2})); - iud1.addRequiredCapabilities(requirements); - Collection capabilities = new ArrayList(); - capabilities.add(new ProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, "TestOr", Version.create("1.0.0"))); - iud1.addProvidedCapabilities(capabilities); - IInstallableUnit iu1 = MetadataFactory.createInstallableUnit(iud1); - - createTestMetdataRepository(new IInstallableUnit[] {iu1, a2, a1}); - - IPlanner planner = createPlanner(); - IProfile profile = createProfile("TestOr4"); - ProfileChangeRequest changeRequest = new ProfileChangeRequest(profile); - changeRequest.addInstallableUnits(new IInstallableUnit[] {iu1}); - ProvisioningPlan plan = planner.getProvisioningPlan(changeRequest, null, null); - assertOK("Plan OK", plan.getStatus()); - // assertEquals(1, plan.getCompleteState().query(new InstallableUnitQuery(id), collector, monitor)) - } - - public void testOR5() { - MetadataFactory.InstallableUnitDescription iud1 = new MetadataFactory.InstallableUnitDescription(); - iud1.setId("TestOr"); - iud1.setVersion(Version.create("1.0.0")); - RequiredCapability req1 = new RequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.2.0)"), null, false, false); - RequiredCapability req2 = new RequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 2.2.0)"), null, false, false); - Collection requirements = new ArrayList(); - requirements.add(new ORRequirement(new IRequiredCapability[] {req1, req2})); - iud1.addRequiredCapabilities(requirements); - Collection capabilities = new ArrayList(); - capabilities.add(new ProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, "TestOr", Version.create("1.0.0"))); - iud1.addProvidedCapabilities(capabilities); - IInstallableUnit iu1 = MetadataFactory.createInstallableUnit(iud1); - - createTestMetdataRepository(new IInstallableUnit[] {iu1}); - - IPlanner planner = createPlanner(); - IProfile profile = createProfile("TestOr4"); - ProfileChangeRequest changeRequest = new ProfileChangeRequest(profile); - changeRequest.addInstallableUnits(new IInstallableUnit[] {iu1}); - ProvisioningPlan plan = planner.getProvisioningPlan(changeRequest, null, null); - assertNotOK("Plan Not OK", plan.getStatus()); - // assertEquals(1, plan.getCompleteState().query(new InstallableUnitQuery(id), collector, monitor)) - } -} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PP2ShouldFailToInstall.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PP2ShouldFailToInstall.java index 785488397..36650a296 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PP2ShouldFailToInstall.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PP2ShouldFailToInstall.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IEngine; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PP2ShouldFailToInstall extends AbstractProvisioningTest { @@ -34,21 +36,21 @@ public class PP2ShouldFailToInstall extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - p2Feature = createIU("p2.feature", new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "P1", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "P2", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); - p1 = createIU("P1", new Version(1, 0, 0), true); - p2 = createIU("P2", new Version(1, 0, 0), true); - p1b = createIU("P1", new Version(1, 1, 1), true); - p2b = createIU("P2", new Version(1, 1, 1), true); + p2Feature = createIU("p2.feature", Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "P1", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "P2", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p1 = createIU("P1", Version.createOSGi(1, 0, 0), true); + p2 = createIU("P2", Version.createOSGi(1, 0, 0), true); + p1b = createIU("P1", Version.createOSGi(1, 1, 1), true); + p2b = createIU("P2", Version.createOSGi(1, 1, 1), true); IRequirementChange changepp1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "P1", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "P1", new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "p2.feature", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "p2.feature", new VersionRange("[1.0.0,1.0.0]"), null, false, false)}}; - pp1 = createIUPatch("PP1", new Version("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); + pp1 = createIUPatch("PP1", Version.create("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); IRequirementChange changepp2 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "P2", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "P2", new VersionRange("[3.1.1, 3.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "p2.feature", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp2 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "p2.feature", new VersionRange("[1.0.0, 1.0.0]"), null, false, false)}}; - pp2 = createIUPatch("PP2", new Version("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); + pp2 = createIUPatch("PP2", Version.create("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); createTestMetdataRepository(new IInstallableUnit[] {p2Feature, p1, p2, p1b, p2b, pp1, pp2}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchFailingToInstall.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchFailingToInstall.java index 63700f374..c2e29f222 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchFailingToInstall.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchFailingToInstall.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IEngine; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchFailingToInstall extends AbstractProvisioningTest { @@ -34,21 +36,21 @@ public class PatchFailingToInstall extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - p2Feature = createIU("p2.feature", new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "P1", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "P2", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); - p1 = createIU("P1", new Version(1, 0, 0), true); - p2 = createIU("P2", new Version(1, 0, 0), true); - p1b = createIU("P1", new Version(1, 1, 1), true); - p2b = createIU("P2", new Version(1, 1, 1), true); + p2Feature = createIU("p2.feature", Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "P1", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "P2", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p1 = createIU("P1", Version.createOSGi(1, 0, 0), true); + p2 = createIU("P2", Version.createOSGi(1, 0, 0), true); + p1b = createIU("P1", Version.createOSGi(1, 1, 1), true); + p2b = createIU("P2", Version.createOSGi(1, 1, 1), true); IRequirementChange changepp1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequiredCapability lifeCyclepp1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "p2.feature", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "P1", new VersionRange("[1.1.1,1.1.1]"), null, false, false)}}; - pp1 = createIUPatch("PP1", new Version("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); + pp1 = createIUPatch("PP1", Version.create("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); IRequirementChange changepp2 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequiredCapability lifeCyclepp2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "p2.feature", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp2 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "P2", new VersionRange("[1.1.1,1.1.1]"), null, false, false)}}; - pp2 = createIUPatch("PP2", new Version("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); + pp2 = createIUPatch("PP2", Version.create("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); createTestMetdataRepository(new IInstallableUnit[] {p2Feature, p1, p2, p1b, p2b, pp1, pp2}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest1.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest1.java index 5cfcb737a..2c323f982 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest1.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest1.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest1 extends AbstractProvisioningTest { @@ -31,10 +33,10 @@ public class PatchTest1 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - b1 = createIU("B", new Version(1, 2, 0), true); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + b1 = createIU("B", Version.createOSGi(1, 2, 0), true); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, p1}); @@ -47,7 +49,7 @@ public class PatchTest1 extends AbstractProvisioningTest { //The requirement from A to B is broken because there is no B satisifying. Therefore A can only install if the P is installed as well ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {a1, p1}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.OK, plan1.getStatus().getSeverity()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest10.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest10.java index 0cf1378ed..2f72df7f9 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest10.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest10.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest10 extends AbstractProvisioningTest { @@ -34,15 +36,15 @@ public class PatchTest10 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - b1 = createIU("B", new Version(1, 0, 0), true); - b2 = createIU("B", new Version(1, 2, 0), true); - b3 = createIU("B", new Version(1, 3, 0), true); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + b1 = createIU("B", Version.createOSGi(1, 0, 0), true); + b2 = createIU("B", Version.createOSGi(1, 2, 0), true); + b3 = createIU("B", Version.createOSGi(1, 3, 0), true); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.2.0, 1.2.0]"), null, false, false, true)); - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); IRequirementChange anotherChangeB = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.3.0, 1.3.0]"), null, false, false, true)); - pp1 = createIUPatch("PP", new Version("1.0.0"), true, new IRequirementChange[] {anotherChangeB}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); + pp1 = createIUPatch("PP", Version.create("1.0.0"), true, new IRequirementChange[] {anotherChangeB}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, b2, b3, p1, pp1}); @@ -55,7 +57,7 @@ public class PatchTest10 extends AbstractProvisioningTest { //a1 and p1 can be installed together ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {a1, p1}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.OK, plan1.getStatus().getSeverity()); assertInstallOperand(plan1, a1); assertInstallOperand(plan1, p1); @@ -64,7 +66,7 @@ public class PatchTest10 extends AbstractProvisioningTest { //a1 and pp1 can be installed together ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {a1, pp1}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); assertInstallOperand(plan2, a1); assertInstallOperand(plan2, pp1); @@ -73,14 +75,14 @@ public class PatchTest10 extends AbstractProvisioningTest { //a1, p1, and pp1 can not be installed together ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.addInstallableUnits(new IInstallableUnit[] {a1, p1, pp1}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.ERROR, plan3.getStatus().getSeverity()); } public void testExplanation() { ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.addInstallableUnits(new IInstallableUnit[] {a1, p1, pp1}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.ERROR, plan3.getStatus().getSeverity()); // Set problems = plan3.getRequestStatus().getConflictsWithInstalledRoots(); // System.out.println(problems); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest11.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest11.java index bca51d3e0..694599a00 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest11.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest11.java @@ -10,14 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest11 extends AbstractProvisioningTest { @@ -32,11 +33,11 @@ public class PatchTest11 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true, true)}); - b1 = createIU("B", new Version(1, 0, 0), true); - b2 = createIU("B", new Version(1, 2, 0), true); - IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), "foo=bar", false, false, true)); - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true, true)}); + b1 = createIU("B", Version.createOSGi(1, 0, 0), true); + b2 = createIU("B", Version.createOSGi(1, 2, 0), true); + IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), "(foo=bar)", false, false, true)); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, b2, p1}); @@ -51,7 +52,7 @@ public class PatchTest11 extends AbstractProvisioningTest { ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {a1, p1}); req2.setInstallableUnitInclusionRules(p1, PlannerHelper.createOptionalInclusionRule(p1)); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertTrue(IStatus.ERROR != plan2.getStatus().getSeverity()); assertNoOperand(plan2, b1); assertNoOperand(plan2, b2); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest12.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest12.java index c21886249..3d362de02 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest12.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest12.java @@ -10,16 +10,17 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.Set; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.director.Explanation; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest12 extends AbstractProvisioningTest { @@ -34,11 +35,11 @@ public class PatchTest12 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true, true)}); - b1 = createIU("B", new Version(1, 0, 0), true); - b2 = createIU("B", new Version(1, 2, 0), true); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true, true)}); + b1 = createIU("B", Version.createOSGi(1, 0, 0), true); + b2 = createIU("B", Version.createOSGi(1, 2, 0), true); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.4.0, 1.5.0)"), null, false, true, true)); - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, b2, p1}); @@ -54,7 +55,7 @@ public class PatchTest12 extends AbstractProvisioningTest { ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {a1, p1}); req2.setInstallableUnitInclusionRules(p1, PlannerHelper.createOptionalInclusionRule(p1)); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertTrue(IStatus.ERROR != plan2.getStatus().getSeverity()); assertNoOperand(plan2, p1); assertNoOperand(plan2, b2); @@ -65,7 +66,7 @@ public class PatchTest12 extends AbstractProvisioningTest { //Try to install a1 and p1. This should fail because the patch adds an invalid filter ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.addInstallableUnits(new IInstallableUnit[] {a1, p1}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertTrue(IStatus.ERROR == plan3.getStatus().getSeverity()); } @@ -73,10 +74,11 @@ public class PatchTest12 extends AbstractProvisioningTest { public void testExplanation1() { ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.addInstallableUnits(new IInstallableUnit[] {a1, p1}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + ProvisioningPlan plan3 = (ProvisioningPlan) planner.getProvisioningPlan(req3, null, null); assertTrue(IStatus.ERROR == plan3.getStatus().getSeverity()); - Set conflictRootIUs = plan3.getRequestStatus().getConflictsWithInstalledRoots(); + final RequestStatus requestStatus = (RequestStatus) plan3.getRequestStatus(); + Set conflictRootIUs = requestStatus.getConflictsWithInstalledRoots(); assertTrue(conflictRootIUs.contains(p1)); - assertEquals(Explanation.MISSING_REQUIREMENT, plan3.getRequestStatus().getShortExplanation()); + assertEquals(Explanation.MISSING_REQUIREMENT, requestStatus.getShortExplanation()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest13.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest13.java index 6ee942f09..4e1f7bd92 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest13.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest13.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest13 extends AbstractProvisioningTest { @@ -33,12 +35,12 @@ public class PatchTest13 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - b1 = createIU("B", new Version(1, 0, 0), true); - d1 = createIU("D", new Version(1, 0, 0), true); - c1 = createIU("C", new Version(1, 0, 0), true); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + b1 = createIU("B", Version.createOSGi(1, 0, 0), true); + d1 = createIU("D", Version.createOSGi(1, 0, 0), true); + c1 = createIU("C", Version.createOSGi(1, 0, 0), true); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", new VersionRange("[1.0.0, 1.3.0)"), null, false, false, true)); - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, c1, d1, p1}); @@ -50,7 +52,7 @@ public class PatchTest13 extends AbstractProvisioningTest { public void testInstall() { ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {a1, p1}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertTrue(IStatus.ERROR != plan1.getStatus().getSeverity()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest1b.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest1b.java index 3c7e4771d..464dbcf01 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest1b.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest1b.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest1b extends AbstractProvisioningTest { @@ -32,11 +34,11 @@ public class PatchTest1b extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - b1 = createIU("B", new Version(1, 0, 0), true); - b2 = createIU("B", new Version(1, 2, 0), true); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + b1 = createIU("B", Version.createOSGi(1, 0, 0), true); + b2 = createIU("B", Version.createOSGi(1, 2, 0), true); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, b2, p1}); @@ -49,7 +51,7 @@ public class PatchTest1b extends AbstractProvisioningTest { //A requires B 1.0, the installation of the P will result in B 1.2 to be installed ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {a1, p1}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertTrue(IStatus.ERROR != plan1.getStatus().getSeverity()); assertInstallOperand(plan1, a1); assertInstallOperand(plan1, p1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest1c.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest1c.java index 0dd2608c8..4b16ecc15 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest1c.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest1c.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest1c extends AbstractProvisioningTest { @@ -33,12 +35,12 @@ public class PatchTest1c extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - b1 = createIU("B", new Version(1, 0, 0), true); - b2 = createIU("B", new Version(1, 2, 0), true); - b3 = createIU("B", new Version(1, 3, 0), true); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + b1 = createIU("B", Version.createOSGi(1, 0, 0), true); + b2 = createIU("B", Version.createOSGi(1, 2, 0), true); + b3 = createIU("B", Version.createOSGi(1, 3, 0), true); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.2.0, 1.2.0]"), null, false, false, true)); - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, b2, p1}); @@ -51,7 +53,7 @@ public class PatchTest1c extends AbstractProvisioningTest { //A requires B [1.0, 1.1), the installation of P will result in B 1.2 to be installed ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {a1, p1}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertTrue(IStatus.ERROR != plan1.getStatus().getSeverity()); assertInstallOperand(plan1, a1); assertInstallOperand(plan1, p1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest2.java index 7bf64d544..70571a580 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest2.java @@ -10,16 +10,17 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.Set; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.director.Explanation; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest2 extends AbstractProvisioningTest { @@ -38,16 +39,16 @@ public class PatchTest2 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - IProvidedCapability[] cap = new IProvidedCapability[] {MetadataFactory.createProvidedCapability("foo", "bar", new Version(1, 0, 0))}; - a1 = createIU("A", new Version("1.0.0"), null, new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, false)}, cap, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); - b1 = createIU("B", new Version(1, 2, 0), true); + IProvidedCapability[] cap = new IProvidedCapability[] {MetadataFactory.createProvidedCapability("foo", "bar", Version.createOSGi(1, 0, 0))}; + a1 = createIU("A", Version.create("1.0.0"), null, new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, false)}, cap, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); + b1 = createIU("B", Version.createOSGi(1, 2, 0), true); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.1.0]"), null, false, false, false)}}, null); - p2 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.3.0, 1.5.0]"), null, false, false, false)}}, null); - p3 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] { {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.1.0]"), null, false, false, false)}, {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.3.0, 1.5.0]"), null, false, false, false)}}, null); - p4 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] { {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.6.0, 1.7.0]"), null, false, false, false)}, {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.3.0, 1.5.0]"), null, false, false, false)}}, null); - p5 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability("foo", "bar", new VersionRange("[1.0.0, 2.0.0)"), null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.5.0]"), null, false, false, false)}}, null); - p6 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {}, null); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.1.0]"), null, false, false, false)}}, null); + p2 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.3.0, 1.5.0]"), null, false, false, false)}}, null); + p3 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] { {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.1.0]"), null, false, false, false)}, {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.3.0, 1.5.0]"), null, false, false, false)}}, null); + p4 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] { {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.6.0, 1.7.0]"), null, false, false, false)}, {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.3.0, 1.5.0]"), null, false, false, false)}}, null); + p5 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability("foo", "bar", new VersionRange("[1.0.0, 2.0.0)"), null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.5.0]"), null, false, false, false)}}, null); + p6 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {}, null); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, p1, p2, p3, p4, p5, p6}); profile1 = createProfile("TestProfile." + getName()); @@ -59,37 +60,37 @@ public class PatchTest2 extends AbstractProvisioningTest { //p6 applies to all IUs therefore A's installation succeed ProfileChangeRequest req8 = new ProfileChangeRequest(profile1); req8.addInstallableUnits(new IInstallableUnit[] {a1, p6}); - ProvisioningPlan plan8 = planner.getProvisioningPlan(req8, null, null); + IProvisioningPlan plan8 = planner.getProvisioningPlan(req8, null, null); assertEquals(IStatus.OK, plan8.getStatus().getSeverity()); //p5 does not causes a1 to resolve therefore the application fails ProfileChangeRequest req6 = new ProfileChangeRequest(profile1); req6.addInstallableUnits(new IInstallableUnit[] {a1, p5}); - ProvisioningPlan plan6 = planner.getProvisioningPlan(req6, null, null); + IProvisioningPlan plan6 = planner.getProvisioningPlan(req6, null, null); assertEquals(IStatus.OK, plan6.getStatus().getSeverity()); //Ensure that p1 causes a1 to resolve ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {a1, p1}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); //p2 does not causes a1 to resolve therefore the application fails ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.addInstallableUnits(new IInstallableUnit[] {a1, p2}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.ERROR, plan3.getStatus().getSeverity()); //Ensure that p3 causes a1 to resolve since it has two scopes where one is applicable ProfileChangeRequest req4 = new ProfileChangeRequest(profile1); req4.addInstallableUnits(new IInstallableUnit[] {a1, p3}); - ProvisioningPlan plan4 = planner.getProvisioningPlan(req4, null, null); + IProvisioningPlan plan4 = planner.getProvisioningPlan(req4, null, null); assertEquals(IStatus.OK, plan4.getStatus().getSeverity()); //p4 does not causes a1 to resolve therefore the application fails ProfileChangeRequest req5 = new ProfileChangeRequest(profile1); req5.addInstallableUnits(new IInstallableUnit[] {a1, p4}); - ProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); + IProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); assertEquals(IStatus.ERROR, plan5.getStatus().getSeverity()); } @@ -98,11 +99,12 @@ public class PatchTest2 extends AbstractProvisioningTest { //p2 does not cause a1 to resolve therefore the application fails ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.addInstallableUnits(new IInstallableUnit[] {a1, p2}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + ProvisioningPlan plan3 = (ProvisioningPlan) planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.ERROR, plan3.getStatus().getSeverity()); - assertEquals(Explanation.MISSING_REQUIREMENT, plan3.getRequestStatus().getShortExplanation()); + final RequestStatus requestStatus = (RequestStatus) plan3.getRequestStatus(); + assertEquals(Explanation.MISSING_REQUIREMENT, requestStatus.getShortExplanation()); // System.out.println(plan3.getRequestStatus().getExplanations()); - Set conflictingRoot = plan3.getRequestStatus().getConflictsWithInstalledRoots(); + Set conflictingRoot = requestStatus.getConflictsWithInstalledRoots(); assertTrue(conflictingRoot.contains(a1)); assertEquals(1, conflictingRoot.size()); } @@ -111,11 +113,12 @@ public class PatchTest2 extends AbstractProvisioningTest { //p4 does not cause a1 to resolve therefore the application fails ProfileChangeRequest req5 = new ProfileChangeRequest(profile1); req5.addInstallableUnits(new IInstallableUnit[] {a1, p4}); - ProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); + ProvisioningPlan plan5 = (ProvisioningPlan) planner.getProvisioningPlan(req5, null, null); assertEquals(IStatus.ERROR, plan5.getStatus().getSeverity()); - assertEquals(Explanation.MISSING_REQUIREMENT, plan5.getRequestStatus().getShortExplanation()); + final RequestStatus requestStatus = (RequestStatus) plan5.getRequestStatus(); + assertEquals(Explanation.MISSING_REQUIREMENT, requestStatus.getShortExplanation()); // System.out.println(plan5.getRequestStatus().getExplanations()); - Set conflictingRoot = plan5.getRequestStatus().getConflictsWithInstalledRoots(); + Set conflictingRoot = requestStatus.getConflictsWithInstalledRoots(); assertTrue(conflictingRoot.contains(a1)); assertEquals(1, conflictingRoot.size()); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest3.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest3.java index 2a873da4a..a7d0dc30e 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest3.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest3.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest3 extends AbstractProvisioningTest { @@ -33,16 +35,16 @@ public class PatchTest3 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - f1 = createIU("F", new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.1.0]"), null, false, false, true)}); - f2 = createIU("F", new Version(2, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[3.0.0, 4.0.0)"), null, false, false, true)}); - IProvidedCapability[] cap = new IProvidedCapability[] {MetadataFactory.createProvidedCapability("foo", "bar", new Version(1, 0, 0))}; - a1 = createIU("A", new Version("1.0.0"), null, new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, false)}, cap, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); - a3 = createIU("A", new Version(3, 0, 0), true); - b1 = createIU("B", new Version(1, 0, 0), true); - b2 = createIU("B", new Version(2, 0, 0), true); + f1 = createIU("F", Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.1.0]"), null, false, false, true)}); + f2 = createIU("F", Version.createOSGi(2, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[3.0.0, 4.0.0)"), null, false, false, true)}); + IProvidedCapability[] cap = new IProvidedCapability[] {MetadataFactory.createProvidedCapability("foo", "bar", Version.createOSGi(1, 0, 0))}; + a1 = createIU("A", Version.create("1.0.0"), null, new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, false)}, cap, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, null); + a3 = createIU("A", Version.createOSGi(3, 0, 0), true); + b1 = createIU("B", Version.createOSGi(1, 0, 0), true); + b2 = createIU("B", Version.createOSGi(2, 0, 0), true); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[2.0.0, 2.1.0)"), null, false, false, true)); IRequiredCapability lifeCycle = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "F", new VersionRange("[1.0.0, 1.1.0)"), null, false, false, false); - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.1.0]"), null, false, false, false)}}, lifeCycle); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.1.0]"), null, false, false, false)}}, lifeCycle); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, b2, p1, a3, f1, f2}); profile1 = createProfile("TestProfile." + getName()); @@ -54,12 +56,12 @@ public class PatchTest3 extends AbstractProvisioningTest { // Install a1 ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {f1}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.OK, plan1.getStatus().getSeverity()); assertInstallOperand(plan1, b1); assertInstallOperand(plan1, a1); assertInstallOperand(plan1, f1); - engine.perform(profile1, new DefaultPhaseSet(), plan1.getOperands(), null, null); + engine.perform(plan1, null); assertProfileContainsAll("A1 is missing", profile1, new IInstallableUnit[] {a1}); assertProfileContainsAll("B1 is missing", profile1, new IInstallableUnit[] {b1}); assertProfileContainsAll("B1 is missing", profile1, new IInstallableUnit[] {f1}); @@ -68,11 +70,11 @@ public class PatchTest3 extends AbstractProvisioningTest { ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {p1}); req2.setInstallableUnitInclusionRules(p1, PlannerHelper.createOptionalInclusionRule(p1)); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertTrue(IStatus.ERROR != plan2.getStatus().getSeverity()); assertInstallOperand(plan2, p1); assertInstallOperand(plan2, b2); - engine.perform(profile1, new DefaultPhaseSet(), plan2.getOperands(), null, null); + engine.perform(plan2, null); assertProfileContainsAll("A1 is missing", profile1, new IInstallableUnit[] {a1}); assertProfileContainsAll("B2 is missing", profile1, new IInstallableUnit[] {b2}); assertProfileContainsAll("P1 is missing", profile1, new IInstallableUnit[] {p1}); @@ -81,7 +83,7 @@ public class PatchTest3 extends AbstractProvisioningTest { //Try to uninstall p1, this causes b1 to come back and b2 to go away ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.removeInstallableUnits(new IInstallableUnit[] {p1}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertTrue(IStatus.ERROR != plan3.getStatus().getSeverity()); assertInstallOperand(plan3, b1); assertUninstallOperand(plan3, b2); @@ -90,7 +92,7 @@ public class PatchTest3 extends AbstractProvisioningTest { //Try to uninstall f should not be blocked by p1 since it is installed optionally ProfileChangeRequest req4 = new ProfileChangeRequest(profile1); req4.removeInstallableUnits(new IInstallableUnit[] {f1}); - ProvisioningPlan plan4 = planner.getProvisioningPlan(req4, null, null); + IProvisioningPlan plan4 = planner.getProvisioningPlan(req4, null, null); assertTrue(IStatus.ERROR != plan4.getStatus().getSeverity()); assertUninstallOperand(plan4, b2); assertUninstallOperand(plan4, a1); @@ -101,7 +103,7 @@ public class PatchTest3 extends AbstractProvisioningTest { ProfileChangeRequest req5 = new ProfileChangeRequest(profile1); req5.removeInstallableUnits(new IInstallableUnit[] {f1}); req5.addInstallableUnits(new IInstallableUnit[] {f2}); - ProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); + IProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); assertTrue(IStatus.ERROR != plan5.getStatus().getSeverity()); assertUninstallOperand(plan5, b2); assertUninstallOperand(plan5, a1); @@ -109,7 +111,7 @@ public class PatchTest3 extends AbstractProvisioningTest { assertUninstallOperand(plan5, p1); assertInstallOperand(plan5, f2); assertInstallOperand(plan5, a3); - engine.perform(profile1, new DefaultPhaseSet(), plan5.getOperands(), null, null); + engine.perform(plan5, null); assertProfileContainsAll("", profile1, new IInstallableUnit[] {f2, a3}); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest4.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest4.java index 64931dabd..ff1253f15 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest4.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest4.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest4 extends AbstractProvisioningTest { @@ -37,21 +39,21 @@ public class PatchTest4 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - f1 = createIU("F", new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, false, false, true)}); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, false, true)}); - b1 = createIU("B", new Version(1, 0, 0), true); - c1 = createIU("C", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", new VersionRange("[1.0.0, 1.1.0)"), null, false, false, true)}); - d1 = createIU("D", new Version(1, 0, 0), true); - b2 = createIU("B", new Version(2, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", new VersionRange("[2.0.0, 3.1.0)"), null, false, false, true)}); - d2 = createIU("D", new Version(2, 0, 0), true); + f1 = createIU("F", Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, false, false, true)}); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, false, true)}); + b1 = createIU("B", Version.createOSGi(1, 0, 0), true); + c1 = createIU("C", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", new VersionRange("[1.0.0, 1.1.0)"), null, false, false, true)}); + d1 = createIU("D", Version.createOSGi(1, 0, 0), true); + b2 = createIU("B", Version.createOSGi(2, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", new VersionRange("[2.0.0, 3.1.0)"), null, false, false, true)}); + d2 = createIU("D", Version.createOSGi(2, 0, 0), true); IRequirementChange changeA = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[2.0.0, 2.1.0)"), null, false, false, true)); IRequirementChange changeC = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", new VersionRange("[2.0.0, 2.1.0)"), null, false, false, true)); IRequiredCapability lifeCycle = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "F", VersionRange.emptyRange, null, false, false, false); IRequiredCapability[][] scope = new IRequiredCapability[][] { {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.1.0]"), null, false, false, false)}, {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 1.1.0]"), null, false, false, false)}}; - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {changeA, changeC}, scope, lifeCycle); - p2 = createIUPatch("P", new Version("2.0.0"), true, new IRequirementChange[] {changeA, changeC}, new IRequiredCapability[0][0], lifeCycle); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {changeA, changeC}, scope, lifeCycle); + p2 = createIUPatch("P", Version.create("2.0.0"), true, new IRequirementChange[] {changeA, changeC}, new IRequiredCapability[0][0], lifeCycle); createTestMetdataRepository(new IInstallableUnit[] {f1, a1, b1, b2, c1, d1, d2, p1}); profile1 = createProfile("TestProfile." + getName()); @@ -63,12 +65,12 @@ public class PatchTest4 extends AbstractProvisioningTest { // Install f1 ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {f1}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.OK, plan1.getStatus().getSeverity()); assertInstallOperand(plan1, b1); assertInstallOperand(plan1, a1); assertInstallOperand(plan1, f1); - engine.perform(profile1, new DefaultPhaseSet(), plan1.getOperands(), null, null); + engine.perform(plan1, null); assertProfileContainsAll("A1 is missing", profile1, new IInstallableUnit[] {a1}); assertProfileContainsAll("B1 is missing", profile1, new IInstallableUnit[] {b1}); assertProfileContainsAll("C1 is missing", profile1, new IInstallableUnit[] {c1}); @@ -78,11 +80,11 @@ public class PatchTest4 extends AbstractProvisioningTest { ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {p1}); req2.setInstallableUnitInclusionRules(p1, PlannerHelper.createOptionalInclusionRule(p1)); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertTrue(IStatus.ERROR != plan2.getStatus().getSeverity()); assertInstallOperand(plan2, b2); assertInstallOperand(plan2, d2); - engine.perform(profile1, new DefaultPhaseSet(), plan2.getOperands(), null, null); + engine.perform(plan2, null); assertProfileContainsAll("A1 is missing", profile1, new IInstallableUnit[] {a1}); assertProfileContainsAll("B2 is missing", profile1, new IInstallableUnit[] {b2}); assertProfileContainsAll("P1 is missing", profile1, new IInstallableUnit[] {p1}); @@ -96,12 +98,12 @@ public class PatchTest4 extends AbstractProvisioningTest { // Install f1 ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {f1}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.OK, plan1.getStatus().getSeverity()); assertInstallOperand(plan1, b1); assertInstallOperand(plan1, a1); assertInstallOperand(plan1, f1); - engine.perform(profile1, new DefaultPhaseSet(), plan1.getOperands(), null, null); + engine.perform(plan1, null); assertProfileContainsAll("A1 is missing", profile1, new IInstallableUnit[] {a1}); assertProfileContainsAll("B1 is missing", profile1, new IInstallableUnit[] {b1}); assertProfileContainsAll("C1 is missing", profile1, new IInstallableUnit[] {c1}); @@ -111,11 +113,11 @@ public class PatchTest4 extends AbstractProvisioningTest { ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {p2}); req2.setInstallableUnitInclusionRules(p1, PlannerHelper.createOptionalInclusionRule(p1)); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertTrue(IStatus.ERROR != plan2.getStatus().getSeverity()); assertInstallOperand(plan2, b2); assertInstallOperand(plan2, d2); - engine.perform(profile1, new DefaultPhaseSet(), plan2.getOperands(), null, null); + engine.perform(plan2, null); assertProfileContainsAll("A1 is missing", profile1, new IInstallableUnit[] {a1}); assertProfileContainsAll("B2 is missing", profile1, new IInstallableUnit[] {b2}); assertProfileContainsAll("P1 is missing", profile1, new IInstallableUnit[] {p1}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest5.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest5.java index 02ab2a134..008a7b57f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest5.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest5.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest5 extends AbstractProvisioningTest { @@ -33,14 +35,14 @@ public class PatchTest5 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - top = createIU("TOP", new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "F", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); - f1 = createIU("F", new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - b1 = createIU("B", new Version(1, 2, 0), true); + top = createIU("TOP", Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "F", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + f1 = createIU("F", Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + b1 = createIU("B", Version.createOSGi(1, 2, 0), true); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequiredCapability lifeCycle = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "F", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scope = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0,1.0.0]"), null, false, false)}}; - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, scope, lifeCycle); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, scope, lifeCycle); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, f1, top, p1}); @@ -52,12 +54,12 @@ public class PatchTest5 extends AbstractProvisioningTest { public void testInstall() { ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {top}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.ERROR, plan1.getStatus().getSeverity()); ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {top, p1}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest6.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest6.java index e53a8f741..17b87a579 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest6.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest6.java @@ -10,16 +10,17 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.Set; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.director.Explanation; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest6 extends AbstractProvisioningTest { @@ -37,20 +38,20 @@ public class PatchTest6 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - b1 = createIU("B", new Version(1, 2, 0), true); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + b1 = createIU("B", Version.createOSGi(1, 2, 0), true); - c1 = createIU("C", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - d1 = createIU("D", new Version(1, 2, 0), true); + c1 = createIU("C", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + d1 = createIU("D", Version.createOSGi(1, 2, 0), true); IRequirementChange changeA = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequiredCapability[][] scopeP1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, false)}}; IRequiredCapability[] reqOnPP = new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "PP", new VersionRange("[1.0.0, 2.0.0)"), null, false, false, true)}; - p1 = createIUPatch("P", new Version("1.0.0"), null, reqOnPP, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, new IRequirementChange[] {changeA}, scopeP1, null, new IRequiredCapability[0]); + p1 = createIUPatch("P", Version.create("1.0.0"), null, reqOnPP, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, new IRequirementChange[] {changeA}, scopeP1, null, new IRequiredCapability[0]); IRequirementChange changeC = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequiredCapability[][] scopePP1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, false, false, false)}}; - pp1 = createIUPatch("PP", new Version("1.0.0"), true, new IRequirementChange[] {changeC}, scopePP1, null); + pp1 = createIUPatch("PP", Version.create("1.0.0"), true, new IRequirementChange[] {changeC}, scopePP1, null); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, c1, d1, p1, pp1}); profile1 = createProfile("TestProfile." + getName()); @@ -62,25 +63,25 @@ public class PatchTest6 extends AbstractProvisioningTest { //Confirm that a1 and c1 can't be installed ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {a1, c1}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.ERROR, plan1.getStatus().getSeverity()); //Verify that the installation of c1 and pp1 succeed ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {c1, pp1}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); //Verify that p1 can be installed alone (kind of meaningless) ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.addInstallableUnits(new IInstallableUnit[] {p1}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.OK, plan3.getStatus().getSeverity()); //Install a1 and p1. ProfileChangeRequest req4 = new ProfileChangeRequest(profile1); req4.addInstallableUnits(new IInstallableUnit[] {a1, p1}); - ProvisioningPlan plan4 = planner.getProvisioningPlan(req4, null, null); + IProvisioningPlan plan4 = planner.getProvisioningPlan(req4, null, null); assertEquals(IStatus.OK, plan4.getStatus().getSeverity()); assertInstallOperand(plan4, a1); assertInstallOperand(plan4, p1); @@ -90,7 +91,7 @@ public class PatchTest6 extends AbstractProvisioningTest { //Install a1, c1 and p1. ProfileChangeRequest req5 = new ProfileChangeRequest(profile1); req5.addInstallableUnits(new IInstallableUnit[] {a1, c1, p1}); - ProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); + IProvisioningPlan plan5 = planner.getProvisioningPlan(req5, null, null); assertEquals(IStatus.OK, plan5.getStatus().getSeverity()); assertInstallOperand(plan4, a1); assertInstallOperand(plan4, p1); @@ -104,10 +105,11 @@ public class PatchTest6 extends AbstractProvisioningTest { //Confirm that a1 and c1 can't be installed ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {a1, c1}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + ProvisioningPlan plan1 = (ProvisioningPlan) planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.ERROR, plan1.getStatus().getSeverity()); - assertEquals(Explanation.MISSING_REQUIREMENT, plan1.getRequestStatus().getShortExplanation()); - Set conflictingRoots = plan1.getRequestStatus().getConflictsWithInstalledRoots(); + final RequestStatus requestStatus = (RequestStatus) plan1.getRequestStatus(); + assertEquals(Explanation.MISSING_REQUIREMENT, requestStatus.getShortExplanation()); + Set conflictingRoots = requestStatus.getConflictsWithInstalledRoots(); assertEquals(1, conflictingRoots.size()); assertTrue(conflictingRoots.contains(a1) || conflictingRoots.contains(c1)); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest7.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest7.java index a2e5f246e..0043baed3 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest7.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest7.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest7 extends AbstractProvisioningTest { @@ -38,26 +40,26 @@ public class PatchTest7 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - // x1 = createIU("X", new Version(1, 2, 0), true); - y1 = createIU("Y", new Version(1, 0, 0), true); - y2 = createIU("Y", new Version(1, 2, 0), true); - // a1 = createIU("A", new Version("1.0.0"), new RequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "X", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - // b1 = createIU("B", new Version("1.0.0"), new RequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "X", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - c1 = createIU("C", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "Y", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + // x1 = createIU("X", Version.createOSGi(1, 2, 0), true); + y1 = createIU("Y", Version.createOSGi(1, 0, 0), true); + y2 = createIU("Y", Version.createOSGi(1, 2, 0), true); + // a1 = createIU("A", Version.create("1.0.0"), new RequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "X", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + // b1 = createIU("B", Version.create("1.0.0"), new RequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "X", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + c1 = createIU("C", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "Y", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); IRequiredCapability[] req = new IRequiredCapability[1]; // req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.1.0)"), null, false, true); // req[1] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true); req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 1.1.0)"), null, false, true); - f1 = createIU("F", new Version(1, 0, 0), req); + f1 = createIU("F", Version.createOSGi(1, 0, 0), req); // RequirementChange changeX = new RequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "X", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "X", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); // RequiredCapability[][] scope = new RequiredCapability[0][0]; //new RequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, false)}}; - // p1 = createIUPatch("P", new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, TouchpointType.NONE, NO_TP_DATA, false, null, new RequirementChange[] {changeX}, scope, null); + // p1 = createIUPatch("P", Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, TouchpointType.NONE, NO_TP_DATA, false, null, new RequirementChange[] {changeX}, scope, null); IRequirementChange changeY = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "Y", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "Y", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequiredCapability[][] scopePP = new IRequiredCapability[0][0]; //new RequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, false, false, false)}}; - pp1 = createIUPatch("PP", new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, new IRequirementChange[] {changeY}, scopePP, null, new IRequiredCapability[0]); + pp1 = createIUPatch("PP", Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, new IRequirementChange[] {changeY}, scopePP, null, new IRequiredCapability[0]); // createTestMetdataRepository(new IInstallableUnit[] {a1, b1, c1, x1, y1, y2, f1, p1, pp1}); createTestMetdataRepository(new IInstallableUnit[] {c1, y1, y2, f1, pp1}); @@ -90,7 +92,7 @@ public class PatchTest7 extends AbstractProvisioningTest { //Verify that the installation of f1 and p1 succeed ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.addInstallableUnits(new IInstallableUnit[] {f1, pp1}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.OK, plan3.getStatus().getSeverity()); assertInstallOperand(plan3, f1); // assertInstallOperand(plan3, a1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest7b.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest7b.java index e6cb09235..0e143f71f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest7b.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest7b.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest7b extends AbstractProvisioningTest { @@ -38,26 +40,26 @@ public class PatchTest7b extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - x1 = createIU("X", new Version(1, 2, 0), true); - y1 = createIU("Y", new Version(1, 0, 0), true); - y2 = createIU("Y", new Version(1, 2, 0), true); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "X", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - b1 = createIU("B", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "X", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - c1 = createIU("C", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "Y", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + x1 = createIU("X", Version.createOSGi(1, 2, 0), true); + y1 = createIU("Y", Version.createOSGi(1, 0, 0), true); + y2 = createIU("Y", Version.createOSGi(1, 2, 0), true); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "X", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + b1 = createIU("B", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "X", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + c1 = createIU("C", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "Y", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); IRequiredCapability[] req = new IRequiredCapability[3]; req[2] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.1.0)"), null, false, true); req[1] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true); req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 1.1.0)"), null, false, true); - f1 = createIU("F", new Version(1, 0, 0), req); + f1 = createIU("F", Version.createOSGi(1, 0, 0), req); IRequirementChange changeX = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "X", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "X", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequiredCapability[][] scope = new IRequiredCapability[0][0]; //new RequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, false)}}; - p1 = createIUPatch("P", new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, new IRequirementChange[] {changeX}, scope, null, new IRequiredCapability[0]); + p1 = createIUPatch("P", Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, new IRequirementChange[] {changeX}, scope, null, new IRequiredCapability[0]); IRequirementChange changeY = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "Y", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "Y", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequiredCapability[][] scopePP = new IRequiredCapability[0][0]; //new RequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, false, false, false)}}; - pp1 = createIUPatch("PP", new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, new IRequirementChange[] {changeY}, scopePP, null, new IRequiredCapability[0]); + pp1 = createIUPatch("PP", Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, new IRequirementChange[] {changeY}, scopePP, null, new IRequiredCapability[0]); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, c1, x1, y1, y2, f1, p1, pp1}); // createTestMetdataRepository(new IInstallableUnit[] {c1, y1, y2, f1, pp1}); @@ -77,7 +79,7 @@ public class PatchTest7b extends AbstractProvisioningTest { //Verify that the installation of f1 and p1 succeed ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {f1, p1}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); assertInstallOperand(plan2, f1); assertInstallOperand(plan2, a1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest8.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest8.java index ede44e0db..c24ded126 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest8.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest8.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest8 extends AbstractProvisioningTest { @@ -37,25 +39,25 @@ public class PatchTest8 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version(1, 0, 0), true); - a2 = createIU("A", new Version("2.0.0"), true); - b1 = createIU("B", new Version("1.0.0"), true); - b2 = createIU("B", new Version("2.0.0"), true); - c2 = createIU("C", new Version("2.0.0"), true); + a1 = createIU("A", Version.createOSGi(1, 0, 0), true); + a2 = createIU("A", Version.create("2.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); + b2 = createIU("B", Version.create("2.0.0"), true); + c2 = createIU("C", Version.create("2.0.0"), true); IRequiredCapability[] req = new IRequiredCapability[3]; req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.1.0)"), null, false, true); req[1] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true); req[2] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[2.0.0, 3.1.0)"), null, false, true); - f1 = createIU("F", new Version(1, 0, 0), req); + f1 = createIU("F", Version.createOSGi(1, 0, 0), req); IRequirementChange changeA = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 3.0.0)"), null, false, false, true)); IRequiredCapability[][] scope = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "F", VersionRange.emptyRange, null, false, false, false)}}; - p1 = createIUPatch("P", new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, new IRequirementChange[] {changeA}, scope, null, new IRequiredCapability[0]); + p1 = createIUPatch("P", Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, new IRequirementChange[] {changeA}, scope, null, new IRequiredCapability[0]); IRequirementChange changeB = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[2.0.0, 3.0.0)"), null, false, false, true)); IRequiredCapability[][] scopePP = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "F", VersionRange.emptyRange, null, false, false, false)}}; - r1 = createIUPatch("R", new Version("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, new IRequirementChange[] {changeB}, scopePP, null, new IRequiredCapability[0]); + r1 = createIUPatch("R", Version.create("1.0.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, null, new IRequirementChange[] {changeB}, scopePP, null, new IRequiredCapability[0]); createTestMetdataRepository(new IInstallableUnit[] {a1, a2, b1, b2, c2, f1, p1, r1}); @@ -87,7 +89,7 @@ public class PatchTest8 extends AbstractProvisioningTest { //Verify that the installation of f1 and p1 succeed ProfileChangeRequest req3 = new ProfileChangeRequest(profile1); req3.addInstallableUnits(new IInstallableUnit[] {f1, p1, r1}); - ProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); + IProvisioningPlan plan3 = planner.getProvisioningPlan(req3, null, null); assertEquals(IStatus.OK, plan3.getStatus().getSeverity()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest9.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest9.java index c2bde8342..0a9f4a759 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest9.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTest9.java @@ -10,16 +10,17 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.Set; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.director.Explanation; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTest9 extends AbstractProvisioningTest { @@ -36,16 +37,16 @@ public class PatchTest9 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); - b1 = createIU("B", new Version(1, 0, 0), true); - b2 = createIU("B", new Version(1, 2, 0), true); - c1 = createIU("C", new Version(1, 0, 0), true); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.1.0)"), null, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 1.1.0)"), null, false, true)}); + b1 = createIU("B", Version.createOSGi(1, 0, 0), true); + b2 = createIU("B", Version.createOSGi(1, 2, 0), true); + c1 = createIU("C", Version.createOSGi(1, 0, 0), true); IRequirementChange changeB = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); IRequirementChange changeC = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.1.0, 1.3.0)"), null, false, false, true)); - p1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {changeB, changeC}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); + p1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {changeB, changeC}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); IRequirementChange anotherChangeC = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.1.0, 1.3.0)"), null, true, false, true)); - pp1 = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {changeB, anotherChangeC}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); + pp1 = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {changeB, anotherChangeC}, new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, false, false)}}, null); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, b2, c1, p1, pp1}); @@ -58,7 +59,7 @@ public class PatchTest9 extends AbstractProvisioningTest { //The application of the patch does not succeed because there is no C matching the requirement imposed by the patch ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {a1, p1}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.ERROR, plan1.getStatus().getSeverity()); } @@ -66,10 +67,11 @@ public class PatchTest9 extends AbstractProvisioningTest { //The application of the patch does not succeed because there is no C matching the requirement imposed by the patch ProfileChangeRequest req1 = new ProfileChangeRequest(profile1); req1.addInstallableUnits(new IInstallableUnit[] {a1, p1}); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + ProvisioningPlan plan1 = (ProvisioningPlan) planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.ERROR, plan1.getStatus().getSeverity()); - assertEquals(Explanation.MISSING_REQUIREMENT, plan1.getRequestStatus().getShortExplanation()); - Set conflictingRoots = plan1.getRequestStatus().getConflictsWithInstalledRoots(); + final RequestStatus requestStatus = (RequestStatus) plan1.getRequestStatus(); + assertEquals(Explanation.MISSING_REQUIREMENT, requestStatus.getShortExplanation()); + Set conflictingRoots = requestStatus.getConflictsWithInstalledRoots(); assertEquals(1, conflictingRoots.size()); assertTrue(conflictingRoots.contains(p1)); } @@ -78,7 +80,7 @@ public class PatchTest9 extends AbstractProvisioningTest { //The application of the patch succeed because the dependency that PP puts on C is optional ProfileChangeRequest req2 = new ProfileChangeRequest(profile1); req2.addInstallableUnits(new IInstallableUnit[] {a1, pp1}); - ProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req2, null, null); assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); assertInstallOperand(plan2, a1); assertInstallOperand(plan2, pp1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestMultiplePatch.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestMultiplePatch.java index d61858b25..0776f5d5b 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestMultiplePatch.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestMultiplePatch.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IEngine; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTestMultiplePatch extends AbstractProvisioningTest { @@ -40,22 +42,22 @@ public class PatchTestMultiplePatch extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - p2Feature = createIU(P2_FEATURE, new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P3, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); - p1 = createIU(P1, new Version(1, 0, 0), true); - p2 = createIU(P2, new Version(1, 0, 0), true); - p1b = createIU(P1, new Version(1, 1, 1), true); - p2b = createIU(P2, new Version(1, 1, 1), true); - p3 = createIU(P3, new Version(1, 0, 0), true); + p2Feature = createIU(P2_FEATURE, Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P3, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p1 = createIU(P1, Version.createOSGi(1, 0, 0), true); + p2 = createIU(P2, Version.createOSGi(1, 0, 0), true); + p1b = createIU(P1, Version.createOSGi(1, 1, 1), true); + p2b = createIU(P2, Version.createOSGi(1, 1, 1), true); + p3 = createIU(P3, Version.createOSGi(1, 0, 0), true); IRequirementChange changepp1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0,1.0.0]"), null, false, false)}}; - pp1 = createIUPatch(PP1, new Version("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); + pp1 = createIUPatch(PP1, Version.create("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); IRequirementChange changepp2 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp2 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false)}}; - pp2 = createIUPatch(PP2, new Version("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); + pp2 = createIUPatch(PP2, Version.create("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); createTestMetdataRepository(new IInstallableUnit[] {p2Feature, p1, p2, p3, p1b, p2b, pp1, pp2}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestMultiplePatch2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestMultiplePatch2.java new file mode 100644 index 000000000..81b2b0a43 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestMultiplePatch2.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.tests.planner; + +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; + +public class PatchTestMultiplePatch2 extends AbstractProvisioningTest { + private static final String PP2 = "PatchForIUP2"; + private static final String PP1 = "PatchForIUP1"; + private static final String P3 = "P3"; + private static final String P2 = "P2"; + private static final String P1 = "P1"; + private static final String P2_FEATURE = "p2.feature"; + private IInstallableUnit p2Feature; + private IInstallableUnit p1; + private IInstallableUnit p2; + private IInstallableUnit p3; + private IInstallableUnitPatch pp1; + private IInstallableUnitPatch pp2; + private IInstallableUnit p1c; + private IInstallableUnit p1b; + private IProfile profile1; + private IPlanner planner; + private IEngine engine; + + protected void setUp() throws Exception { + super.setUp(); + p2Feature = createIU(P2_FEATURE, Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P3, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p1 = createIU(P1, Version.createOSGi(1, 0, 0), true); + p2 = createIU(P2, Version.createOSGi(1, 0, 0), true); + p1b = createIU(P1, Version.createOSGi(1, 1, 1), true); + p1c = createIU(P1, Version.createOSGi(1, 1, 2), true); + p3 = createIU(P3, Version.createOSGi(1, 0, 0), true); + + IRequirementChange changepp1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); + IRequiredCapability lifeCyclepp1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); + IRequiredCapability[][] scopepp1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0,1.0.0]"), null, false, false)}}; + pp1 = createIUPatch(PP1, Version.create("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); + + IRequirementChange changepp2 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.2, 1.1.2]"), null, false, false, true)); + IRequiredCapability lifeCyclepp2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); + IRequiredCapability[][] scopepp2 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false)}}; + pp2 = createIUPatch(PP2, Version.create("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); + + createTestMetdataRepository(new IInstallableUnit[] {p2Feature, p1, p2, p3, p1b, p1c, pp1, pp2}); + + profile1 = createProfile("TestProfile." + getName()); + planner = createPlanner(); + engine = createEngine(); + } + + //Try to force the installation of two contradicting patches. + public void testFailingInstall() { + install(profile1, new IInstallableUnit[] {}, true, planner, engine); + ProfileChangeRequest req = new ProfileChangeRequest(profile1); + req.addInstallableUnits(new IInstallableUnit[] {p2Feature, pp1, pp2}); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + assertEquals(IStatus.ERROR, plan.getStatus().getSeverity()); + } +} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestMultiplePatch3.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestMultiplePatch3.java new file mode 100644 index 000000000..d8e753492 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestMultiplePatch3.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.tests.planner; + +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; + +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; + +public class PatchTestMultiplePatch3 extends AbstractProvisioningTest { + private static final String PP2 = "PatchForIUP2"; + private static final String PP1 = "PatchForIUP1"; + private static final String P3 = "P3"; + private static final String P2 = "P2"; + private static final String P1 = "P1"; + private static final String P2_FEATURE = "p2.feature"; + private IInstallableUnit p2Feature; + private IInstallableUnit p1; + private IInstallableUnit p2; + private IInstallableUnit p3; + private IInstallableUnitPatch pp1; + private IInstallableUnitPatch pp2; + private IInstallableUnit p1c; + private IInstallableUnit p1b; + private IProfile profile1; + private IPlanner planner; + + protected void setUp() throws Exception { + super.setUp(); + p2Feature = createIU(P2_FEATURE, Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P3, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p1 = createIU(P1, Version.createOSGi(1, 0, 0), true); + p2 = createIU(P2, Version.createOSGi(1, 0, 0), true); + p1b = createIU(P1, Version.createOSGi(1, 1, 1), true); + p1c = createIU(P1, Version.createOSGi(1, 1, 2), true); + p3 = createIU(P3, Version.createOSGi(1, 0, 0), true); + + IRequirementChange changepp1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); + IRequiredCapability lifeCyclepp1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); + IRequiredCapability[][] scopepp1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0,1.0.0]"), null, false, false)}}; + pp1 = createIUPatch(PP1, Version.create("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); + + IRequirementChange changepp2 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.2, 1.1.2]"), null, false, false, true)); + IRequiredCapability lifeCyclepp2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); + IRequiredCapability[][] scopepp2 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false)}}; + pp2 = createIUPatch(PP2, Version.create("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); + pp2 = createIUPatch(PP2, Version.create("5.0.0"), null, new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "missingThing", new VersionRange("[1.0.0, 1.0.0]"), null, false, false)}, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, true, null, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2, NO_REQUIRES); + createTestMetdataRepository(new IInstallableUnit[] {p2Feature, p1, p2, p3, p1b, p1c, pp1, pp2}); + + profile1 = createProfile("TestProfile." + getName()); + planner = createPlanner(); + } + + //Test that two patches applying to the same requirement of an IU being patched does not cause any problem when one of the two patch is not applied. + public void testFailingInstall() { + ProfileChangeRequest req = new ProfileChangeRequest(profile1); + req.addInstallableUnits(new IInstallableUnit[] {p2Feature}); + req.addInstallableUnits(new IInstallableUnit[] {pp1}); + req.addInstallableUnits(new IInstallableUnit[] {pp2}); + req.setInstallableUnitInclusionRules(pp2, PlannerHelper.createOptionalInclusionRule(pp2)); + + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + assertOK("Planning should be ok", plan.getStatus()); + } +} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestOptional.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestOptional.java index cb65318d2..dadbee8f1 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestOptional.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestOptional.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IEngine; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTestOptional extends AbstractProvisioningTest { @@ -36,16 +38,16 @@ public class PatchTestOptional extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - p2Feature = createIU(P2_FEATURE, new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); - p1 = createIU(P1, new Version(1, 0, 0), true); - p2 = createIU(P2, new Version(1, 0, 0), true); - p1b = createIU(P1, new Version(1, 1, 1), true); - p2b = createIU(P2, new Version(1, 1, 1), true); + p2Feature = createIU(P2_FEATURE, Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p1 = createIU(P1, Version.createOSGi(1, 0, 0), true); + p2 = createIU(P2, Version.createOSGi(1, 0, 0), true); + p1b = createIU(P1, Version.createOSGi(1, 1, 1), true); + p2b = createIU(P2, Version.createOSGi(1, 1, 1), true); IRequirementChange changepp1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.1, 1.1.1]"), null, true, false, true)); IRequiredCapability lifeCyclepp1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0,1.0.0]"), null, false, false)}}; - pp1 = createIUPatch(PP1, new Version("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); + pp1 = createIUPatch(PP1, Version.create("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); createTestMetdataRepository(new IInstallableUnit[] {p2Feature, p1, p2, p1b, p2b, pp1}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestOptional2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestOptional2.java index 861c00eca..cde7abc17 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestOptional2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestOptional2.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IEngine; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTestOptional2 extends AbstractProvisioningTest { @@ -35,15 +37,15 @@ public class PatchTestOptional2 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - p2Feature = createIU(P2_FEATURE, new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); - p1 = createIU(P1, new Version(1, 0, 0), true); - p2 = createIU(P2, new Version(1, 0, 0), true); - p2b = createIU(P2, new Version(1, 1, 1), true); + p2Feature = createIU(P2_FEATURE, Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p1 = createIU(P1, Version.createOSGi(1, 0, 0), true); + p2 = createIU(P2, Version.createOSGi(1, 0, 0), true); + p2b = createIU(P2, Version.createOSGi(1, 1, 1), true); IRequirementChange changepp1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.1, 1.1.1]"), null, true, false, true)); IRequiredCapability lifeCyclepp1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0,1.0.0]"), null, false, false)}}; - pp1 = createIUPatch(PP1, new Version("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); + pp1 = createIUPatch(PP1, Version.create("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); createTestMetdataRepository(new IInstallableUnit[] {p2Feature, p1, p2, p2b, pp1}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestOptional3.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestOptional3.java index 91d3b7ebc..e02c1f0f1 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestOptional3.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestOptional3.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IEngine; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTestOptional3 extends AbstractProvisioningTest { @@ -36,16 +38,16 @@ public class PatchTestOptional3 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - p2Feature = createIU(P2_FEATURE, new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); - p1 = createIU(P1, new Version(1, 0, 0), true); - p2 = createIU(P2, new Version(1, 0, 0), true); - p2b = createIU(P2, new Version(1, 1, 1), true); + p2Feature = createIU(P2_FEATURE, Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p1 = createIU(P1, Version.createOSGi(1, 0, 0), true); + p2 = createIU(P2, Version.createOSGi(1, 0, 0), true); + p2b = createIU(P2, Version.createOSGi(1, 1, 1), true); IRequirementChange changepp1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.1, 1.1.1]"), null, true, false, true)); IRequirementChange changepp2 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0,1.0.0]"), null, false, false)}}; - pp1 = createIUPatch(PP1, new Version("3.0.0"), true, new IRequirementChange[] {changepp1, changepp2}, scopepp1, lifeCyclepp1); + pp1 = createIUPatch(PP1, Version.create("3.0.0"), true, new IRequirementChange[] {changepp1, changepp2}, scopepp1, lifeCyclepp1); createTestMetdataRepository(new IInstallableUnit[] {p2Feature, p1, p2, p1b, p2b, pp1}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUninstall.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUninstall.java index 08c7d77ef..2c56c9998 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUninstall.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUninstall.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IEngine; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTestUninstall extends AbstractProvisioningTest { @@ -39,21 +41,21 @@ public class PatchTestUninstall extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - p2Feature = createIU(P2_FEATURE, new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); - p1 = createIU(P1, new Version(1, 0, 0), true); - p2 = createIU(P2, new Version(1, 0, 0), true); - p1b = createIU(P1, new Version(1, 1, 1), true); - p2b = createIU(P2, new Version(1, 1, 1), true); + p2Feature = createIU(P2_FEATURE, Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p1 = createIU(P1, Version.createOSGi(1, 0, 0), true); + p2 = createIU(P2, Version.createOSGi(1, 0, 0), true); + p1b = createIU(P1, Version.createOSGi(1, 1, 1), true); + p2b = createIU(P2, Version.createOSGi(1, 1, 1), true); IRequirementChange changepp1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0,1.0.0]"), null, false, false)}}; - pp1 = createIUPatch(PP1, new Version("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); + pp1 = createIUPatch(PP1, Version.create("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); IRequirementChange changepp2 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp2 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false)}}; - pp2 = createIUPatch(PP2, new Version("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); + pp2 = createIUPatch(PP2, Version.create("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); createTestMetdataRepository(new IInstallableUnit[] {p2Feature, p1, p2, p1b, p2b, pp1, pp2}); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate.java index 7ca2a56bb..f092723d1 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate.java @@ -10,16 +10,17 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.Set; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.director.Explanation; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTestUpdate extends AbstractProvisioningTest { @@ -42,23 +43,23 @@ public class PatchTestUpdate extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - p2Feature = createIU(P2_FEATURE, new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); - p1 = createIU(P1, new Version(1, 0, 0), true); - p2 = createIU(P2, new Version(1, 0, 0), true); - p1b = createIU(P1, new Version(1, 1, 1), true); - p2b = createIU(P2, new Version(1, 1, 1), true); + p2Feature = createIU(P2_FEATURE, Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p1 = createIU(P1, Version.createOSGi(1, 0, 0), true); + p2 = createIU(P2, Version.createOSGi(1, 0, 0), true); + p1b = createIU(P1, Version.createOSGi(1, 1, 1), true); + p2b = createIU(P2, Version.createOSGi(1, 1, 1), true); IRequirementChange changepp1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0,1.0.0]"), null, false, false)}}; - pp1 = createIUPatch(PP1, new Version("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); + pp1 = createIUPatch(PP1, Version.create("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); IRequirementChange changepp2 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp2 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false)}}; - pp2 = createIUPatch(PP2, new Version("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); + pp2 = createIUPatch(PP2, Version.create("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); - p2Feature20 = createIU(P2_FEATURE, new Version(2, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p2Feature20 = createIU(P2_FEATURE, Version.createOSGi(2, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); createTestMetdataRepository(new IInstallableUnit[] {p2Feature, p1, p2, p1b, p2b, pp1, pp2, p2Feature20}); profile1 = createProfile("TestProfile." + getName()); @@ -77,7 +78,7 @@ public class PatchTestUpdate extends AbstractProvisioningTest { req1.addInstallableUnits(new IInstallableUnit[] {p2Feature20}); req1.setInstallableUnitInclusionRules(p2Feature20, PlannerHelper.createStrictInclusionRule(p2Feature20)); req1.removeInstallableUnits(new IInstallableUnit[] {p2Feature}); - ProvisioningPlan plan = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.ERROR, plan.getStatus().getSeverity()); } @@ -87,11 +88,12 @@ public class PatchTestUpdate extends AbstractProvisioningTest { req1.addInstallableUnits(new IInstallableUnit[] {p2Feature20}); req1.setInstallableUnitInclusionRules(p2Feature20, PlannerHelper.createStrictInclusionRule(p2Feature20)); req1.removeInstallableUnits(new IInstallableUnit[] {p2Feature}); - ProvisioningPlan plan = planner.getProvisioningPlan(req1, null, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.ERROR, plan.getStatus().getSeverity()); - Set conflictingRoot = plan.getRequestStatus().getConflictsWithInstalledRoots(); + final RequestStatus requestStatus = (RequestStatus) plan.getRequestStatus(); + Set conflictingRoot = requestStatus.getConflictsWithInstalledRoots(); assertEquals(1, conflictingRoot.size()); assertTrue(conflictingRoot.contains(p2Feature20)); - assertEquals(Explanation.VIOLATED_SINGLETON_CONSTRAINT, plan.getRequestStatus().getShortExplanation()); + assertEquals(Explanation.VIOLATED_SINGLETON_CONSTRAINT, requestStatus.getShortExplanation()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate2.java index 56b2a3004..33435997a 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate2.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTestUpdate2 extends AbstractProvisioningTest { @@ -39,23 +41,23 @@ public class PatchTestUpdate2 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - p2Feature = createIU(P2_FEATURE, new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); - p1 = createIU(P1, new Version(1, 0, 0), true); - p2 = createIU(P2, new Version(1, 0, 0), true); - p1b = createIU(P1, new Version(1, 1, 1), true); - p2b = createIU(P2, new Version(1, 1, 1), true); + p2Feature = createIU(P2_FEATURE, Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p1 = createIU(P1, Version.createOSGi(1, 0, 0), true); + p2 = createIU(P2, Version.createOSGi(1, 0, 0), true); + p1b = createIU(P1, Version.createOSGi(1, 1, 1), true); + p2b = createIU(P2, Version.createOSGi(1, 1, 1), true); IRequirementChange changepp1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0,1.0.0]"), null, false, false)}}; - pp1 = createIUPatch(PP1, new Version("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); + pp1 = createIUPatch(PP1, Version.create("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); IRequirementChange changepp2 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp2 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false)}}; - pp2 = createIUPatch(PP2, new Version("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); + pp2 = createIUPatch(PP2, Version.create("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); - p2Feature20 = createIU(P2_FEATURE, new Version(2, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)}); + p2Feature20 = createIU(P2_FEATURE, Version.createOSGi(2, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)}); createTestMetdataRepository(new IInstallableUnit[] {p2Feature, p1, p2, p1b, p2b, pp1, pp2, p2Feature20}); profile1 = createProfile("TestProfile." + getName()); @@ -77,10 +79,10 @@ public class PatchTestUpdate2 extends AbstractProvisioningTest { req1.addInstallableUnits(new IInstallableUnit[] {p2Feature20}); req1.setInstallableUnitInclusionRules(p2Feature20, PlannerHelper.createStrictInclusionRule(p2Feature20)); req1.removeInstallableUnits(new IInstallableUnit[] {p2Feature}); - ProvisioningPlan plan = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req1, null, null); assertEquals(true, IStatus.ERROR != plan.getStatus().getSeverity()); - engine.perform(profile1, new DefaultPhaseSet(), plan.getOperands(), null, null); + engine.perform(plan, null); assertProfileContains("The profile contains unexpected IUs", profile1, new IInstallableUnit[] {p2Feature20, p1b, p2b}); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate3.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate3.java index 3682f440b..3a801f153 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate3.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate3.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.net.URI; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTestUpdate3 extends AbstractProvisioningTest { @@ -39,23 +41,23 @@ public class PatchTestUpdate3 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - p2Feature = createIU(P2_FEATURE, new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); - p1 = createIU(P1, new Version(1, 0, 0), true); - p2 = createIU(P2, new Version(1, 0, 0), true); - p1b = createIU(P1, new Version(1, 1, 1), true); - p2b = createIU(P2, new Version(1, 1, 1), true); + p2Feature = createIU(P2_FEATURE, Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p1 = createIU(P1, Version.createOSGi(1, 0, 0), true); + p2 = createIU(P2, Version.createOSGi(1, 0, 0), true); + p1b = createIU(P1, Version.createOSGi(1, 1, 1), true); + p2b = createIU(P2, Version.createOSGi(1, 1, 1), true); IRequirementChange changepp1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 3.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 3.0.0]"), null, false, false)}}; - pp1 = createIUPatch(PP1, new Version("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); + pp1 = createIUPatch(PP1, Version.create("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); IRequirementChange changepp2 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp2 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 1.0.0]"), null, false, false)}}; - pp2 = createIUPatch(PP2, new Version("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); + pp2 = createIUPatch(PP2, Version.create("5.0.0"), true, new IRequirementChange[] {changepp2}, scopepp2, lifeCyclepp2); - p2Feature20 = createIU(P2_FEATURE, new Version(2, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p2Feature20 = createIU(P2_FEATURE, Version.createOSGi(2, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); createTestMetdataRepository(new IInstallableUnit[] {p2Feature, p1, p2, p1b, p2b, pp1, pp2, p2Feature20}); createProfile("TestProfile." + getName()); @@ -84,10 +86,10 @@ public class PatchTestUpdate3 extends AbstractProvisioningTest { req1.addInstallableUnits(new IInstallableUnit[] {p2Feature20}); req1.setInstallableUnitInclusionRules(p2Feature20, PlannerHelper.createStrictInclusionRule(p2Feature20)); req1.removeInstallableUnits(new IInstallableUnit[] {p2Feature}); - ProvisioningPlan plan = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req1, null, null); assertEquals(true, IStatus.ERROR != plan.getStatus().getSeverity()); - engine.perform(getProfile("TestProfile." + getName()), new DefaultPhaseSet(), plan.getOperands(), null, null); + engine.perform(plan, null); assertProfileContains("The profile contains unexpected IUs", getProfile("TestProfile." + getName()), new IInstallableUnit[] {p2Feature20, p1b, pp1, p2}); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate4.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate4.java index 54e2baf66..8ccff47f3 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate4.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate4.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTestUpdate4 extends AbstractProvisioningTest { @@ -38,18 +40,18 @@ public class PatchTestUpdate4 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - p2Feature = createIU(P2_FEATURE, new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); - p1 = createIU(P1, new Version(1, 0, 0), true); - p2 = createIU(P2, new Version(1, 0, 0), true); - p1b = createIU(P1, new Version(1, 1, 1), true); - p2b = createIU(P2, new Version(1, 1, 1), true); + p2Feature = createIU(P2_FEATURE, Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p1 = createIU(P1, Version.createOSGi(1, 0, 0), true); + p2 = createIU(P2, Version.createOSGi(1, 0, 0), true); + p1b = createIU(P1, Version.createOSGi(1, 1, 1), true); + p2b = createIU(P2, Version.createOSGi(1, 1, 1), true); IRequirementChange changepp1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, true); IRequiredCapability[][] scopepp1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 3.0.0]"), null, false, false)}}; - pp1 = createIUPatch(PP1, new Version("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); + pp1 = createIUPatch(PP1, Version.create("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); - p2Feature20 = createIU(P2_FEATURE, new Version(2, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p2Feature20 = createIU(P2_FEATURE, Version.createOSGi(2, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); createTestMetdataRepository(new IInstallableUnit[] {p2Feature, p1, p2, p1b, p2b, pp1, p2Feature20}); profile1 = createProfile("TestProfile." + getName()); @@ -71,10 +73,10 @@ public class PatchTestUpdate4 extends AbstractProvisioningTest { req1.addInstallableUnits(new IInstallableUnit[] {p2Feature20}); req1.setInstallableUnitInclusionRules(p2Feature20, PlannerHelper.createStrictInclusionRule(p2Feature20)); req1.removeInstallableUnits(new IInstallableUnit[] {p2Feature}); - ProvisioningPlan plan = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req1, null, null); assertEquals(true, IStatus.ERROR != plan.getStatus().getSeverity()); - engine.perform(profile1, new DefaultPhaseSet(), plan.getOperands(), null, null); + engine.perform(plan, null); assertProfileContains("The profile contains unexpected IUs", profile1, new IInstallableUnit[] {p2Feature20, p1b, p2, pp1}); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate5.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate5.java index e46e49d22..532aff861 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate5.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PatchTestUpdate5.java @@ -10,14 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IEngine; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PatchTestUpdate5 extends AbstractProvisioningTest { @@ -39,18 +41,18 @@ public class PatchTestUpdate5 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - p2Feature = createIU(P2_FEATURE, new Version(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); - p1 = createIU(P1, new Version(1, 0, 0), true); - p2 = createIU(P2, new Version(1, 0, 0), true); - p1b = createIU(P1, new Version(1, 1, 1), true); - p2b = createIU(P2, new Version(1, 1, 1), true); + p2Feature = createIU(P2_FEATURE, Version.createOSGi(1, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p1 = createIU(P1, Version.createOSGi(1, 0, 0), true); + p2 = createIU(P2, Version.createOSGi(1, 0, 0), true); + p1b = createIU(P1, Version.createOSGi(1, 1, 1), true); + p2b = createIU(P2, Version.createOSGi(1, 1, 1), true); IRequirementChange changepp1 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.1.1, 1.1.1]"), null, false, false, true)); IRequiredCapability lifeCyclepp1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); IRequiredCapability[][] scopepp1 = new IRequiredCapability[][] {{MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2_FEATURE, new VersionRange("[1.0.0, 3.0.0]"), null, false, false)}}; - pp1 = createIUPatch(PP1, new Version("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); + pp1 = createIUPatch(PP1, Version.create("3.0.0"), true, new IRequirementChange[] {changepp1}, scopepp1, lifeCyclepp1); - p2Feature20 = createIU(P2_FEATURE, new Version(2, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); + p2Feature20 = createIU(P2_FEATURE, Version.createOSGi(2, 0, 0), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P1, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, P2, new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true)}); createTestMetdataRepository(new IInstallableUnit[] {p2Feature, p1, p2, p1b, p2b, pp1, p2Feature20}); profile1 = createProfile("TestProfile." + getName()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PermissiveSlicerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PermissiveSlicerTest.java index 6cdf9ab1d..77f5e0f35 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PermissiveSlicerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/PermissiveSlicerTest.java @@ -10,15 +10,17 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.io.File; import java.util.Properties; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.director.PermissiveSlicer; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class PermissiveSlicerTest extends AbstractProvisioningTest { @@ -33,36 +35,36 @@ public class PermissiveSlicerTest extends AbstractProvisioningTest { public void testSliceRCPOut() { PermissiveSlicer slicer = new PermissiveSlicer(repo, new Properties(), true, false, true, false, false); - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); IQueryable result = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()); assertNotNull(result); - result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size(); - assertEquals(66, result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); - assertEquals(1, result.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()).size()); + queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())); + assertEquals(66, queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); + assertEquals(1, queryResultSize(result.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()))); // assertOK("1.0", slicer.getStatus()); } //Test with and without optional pieces public void testSliceRCPWithOptionalPieces() { PermissiveSlicer slicer = new PermissiveSlicer(repo, new Properties(), false, false, true, false, false); - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); IQueryable result = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()); assertNotNull(result); - result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size(); - assertEquals(64, result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); + queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())); + assertEquals(64, queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); // assertOK("1.0", slicer.getStatus()); } public void testSliceRCPWithIgnoringGreed() { PermissiveSlicer slicer = new PermissiveSlicer(repo, new Properties(), false, true, true, false, false); - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); IQueryable result = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()); assertNotNull(result); - result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size(); - assertEquals(64, result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); + queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())); + assertEquals(64, queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); // assertOK("1.0", slicer.getStatus()); } @@ -72,13 +74,13 @@ public class PermissiveSlicerTest extends AbstractProvisioningTest { p.setProperty("osgi.ws", "win32"); p.setProperty("osgi.arch", "x86"); PermissiveSlicer slicer = new PermissiveSlicer(repo, p, true, true, false, false, false); - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); IQueryable result = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()); assertNotNull(result); - result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size(); - assertEquals(0, result.query(new InstallableUnitQuery("org.eclipse.swt.motif.linux.x86"), new Collector(), new NullProgressMonitor()).size()); - assertEquals(34, result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); + queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())); + assertEquals(0, queryResultSize(result.query(new InstallableUnitQuery("org.eclipse.swt.motif.linux.x86"), new NullProgressMonitor()))); + assertEquals(34, queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); // assertOK("1.0", slicer.getStatus()); } @@ -88,25 +90,25 @@ public class PermissiveSlicerTest extends AbstractProvisioningTest { p.setProperty("osgi.ws", "win32"); p.setProperty("osgi.arch", "x86"); PermissiveSlicer slicer = new PermissiveSlicer(repo, p, true, false, false, true, false); - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); IQueryable result = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()); assertNotNull(result); - result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size(); - assertEquals(0, result.query(new InstallableUnitQuery("org.eclipse.ecf"), new Collector(), new NullProgressMonitor()).size()); - assertEquals(29, result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); + queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())); + assertEquals(0, queryResultSize(result.query(new InstallableUnitQuery("org.eclipse.ecf"), new NullProgressMonitor()))); + assertEquals(29, queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); // assertOK("1.0", slicer.getStatus()); } public void testExtractPlatformIndependentPieces() { PermissiveSlicer slicer = new PermissiveSlicer(repo, new Properties(), true, false, false, false, false); - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); IQueryable result = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()); assertNotNull(result); - result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size(); - assertEquals(32, result.query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); - assertEquals(1, result.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()).size()); + queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor())); + assertEquals(32, queryResultSize(result.query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); + assertEquals(1, queryResultSize(result.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()))); // assertOK("1.0", slicer.getStatus()); } @@ -114,12 +116,12 @@ public class PermissiveSlicerTest extends AbstractProvisioningTest { IProvidedCapability act1Cap = MetadataFactory.createProvidedCapability("p2.action", "action1", DEFAULT_VERSION); IInstallableUnit act1 = createIU("Action1", DEFAULT_VERSION, null, NO_REQUIRES, new IProvidedCapability[] {act1Cap}, NO_PROPERTIES, null, NO_TP_DATA, true); - IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] metaReq = createRequiredCapabilities("p2.action", "action1", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit a = createIUWithMetaRequirement("A", DEFAULT_VERSION, true, NO_REQUIRES, metaReq); PermissiveSlicer slicer = new PermissiveSlicer(createTestMetdataRepository(new IInstallableUnit[] {a, act1}), new Properties(), true, false, false, false, false); IQueryable result = slicer.slice(new IInstallableUnit[] {a}, new NullProgressMonitor()); - assertEquals(1, result.query(new InstallableUnitQuery("Action1"), new Collector(), null).size()); + assertEquals(1, queryResultSize(result.query(new InstallableUnitQuery("Action1"), null))); } public void testValidateIU() { @@ -128,14 +130,14 @@ public class PermissiveSlicerTest extends AbstractProvisioningTest { p.setProperty("osgi.ws", "win32"); p.setProperty("osgi.arch", "x86"); PermissiveSlicer slicer = new PermissiveSlicer(repo, p, true, false, false, true, false); - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.swt.cocoa.macosx"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.swt.cocoa.macosx"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); assertNull(slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor())); assertNotOK(slicer.getStatus()); } public void testMissingNecessaryPiece() { - IRequiredCapability[] req = createRequiredCapabilities("B", "B", new VersionRange("[0.0.0, 1.0.0]"), null); + IRequiredCapability[] req = createRequiredCapabilities("B", "B", new VersionRange("[0.0.0, 1.0.0]")); IInstallableUnit iuA = createIU("A", DEFAULT_VERSION, null, req, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, true); PermissiveSlicer slicer = new PermissiveSlicer(createTestMetdataRepository(new IInstallableUnit[] {iuA}), new Properties(), true, false, false, false, false); IQueryable result = slicer.slice(new IInstallableUnit[] {iuA}, new NullProgressMonitor()); @@ -149,19 +151,19 @@ public class PermissiveSlicerTest extends AbstractProvisioningTest { p.setProperty("osgi.ws", "win32"); p.setProperty("osgi.arch", "x86"); PermissiveSlicer slicer = new PermissiveSlicer(repo, p, true, false, false, false, true); - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); - Collector resultCollector = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()).query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()); - assertEquals(3, resultCollector.size()); + IQueryResult resultCollector = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()).query(InstallableUnitQuery.ANY, new NullProgressMonitor()); + assertEquals(3, queryResultSize(resultCollector)); } public void testExtractOnlyPlatformSpecific() { Properties p = new Properties(); PermissiveSlicer slicer = new PermissiveSlicer(repo, p, true, false, true, false, true); - Collector c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new Collector(), new NullProgressMonitor()); + IQueryResult c = repo.query(new InstallableUnitQuery("org.eclipse.rcp.feature.group"), new NullProgressMonitor()); IInstallableUnit iu = (IInstallableUnit) c.iterator().next(); - Collector resultCollector = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()).query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()); - assertEquals(35, resultCollector.size()); + IQueryResult resultCollector = slicer.slice(new IInstallableUnit[] {iu}, new NullProgressMonitor()).query(InstallableUnitQuery.ANY, new NullProgressMonitor()); + assertEquals(35, queryResultSize(resultCollector)); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ProvisioningPlanQueryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ProvisioningPlanQueryTest.java index 4a8dc4754..e237cedb9 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ProvisioningPlanQueryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/ProvisioningPlanQueryTest.java @@ -12,37 +12,35 @@ package org.eclipse.equinox.p2.tests.planner; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.engine.Operand; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class ProvisioningPlanQueryTest extends AbstractProvisioningTest { public void testNull() { - Collector c = new ProvisioningPlan(Status.OK_STATUS, null, null).getAdditions().query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()); + IQueryResult c = new ProvisioningPlan(Status.OK_STATUS, null, null, null).getAdditions().query(InstallableUnitQuery.ANY, new NullProgressMonitor()); assertTrue(c.isEmpty()); } public void testAddition() { Operand[] ops = new Operand[] {new InstallableUnitOperand(null, createIU("A"))}; - Collector c = new ProvisioningPlan(Status.OK_STATUS, ops, null, null, null, null, null).getAdditions().query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()); - assertEquals(1, c.size()); - assertEquals(0, new ProvisioningPlan(Status.OK_STATUS, ops, null, null, null, null, null).getRemovals().query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); + IQueryResult c = new ProvisioningPlan(null, ops, null).getAdditions().query(InstallableUnitQuery.ANY, new NullProgressMonitor()); + assertEquals(1, queryResultSize(c)); + assertTrue(new ProvisioningPlan(null, ops, null).getRemovals().query(InstallableUnitQuery.ANY, new NullProgressMonitor()).isEmpty()); } public void testRemoval() { Operand[] ops = new Operand[] {new InstallableUnitOperand(createIU("A"), null)}; - Collector c = new ProvisioningPlan(Status.OK_STATUS, ops, null, null, null, null, null).getRemovals().query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()); - assertEquals(1, c.size()); - assertEquals(0, new ProvisioningPlan(Status.OK_STATUS, ops, null, null, null, null, null).getAdditions().query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); + IQueryResult c = new ProvisioningPlan(null, ops, null).getRemovals().query(InstallableUnitQuery.ANY, new NullProgressMonitor()); + assertEquals(1, queryResultSize(c)); + assertTrue(new ProvisioningPlan(null, ops, null).getAdditions().query(InstallableUnitQuery.ANY, new NullProgressMonitor()).isEmpty()); } public void testUpdate() { Operand[] ops = new Operand[] {new InstallableUnitOperand(createIU("A"), createIU("B"))}; - Collector c = new ProvisioningPlan(Status.OK_STATUS, ops, null, null, null, null, null).getRemovals().query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()); - assertEquals(1, c.size()); - assertEquals(1, new ProvisioningPlan(Status.OK_STATUS, ops, null, null, null, null, null).getAdditions().query(InstallableUnitQuery.ANY, new Collector(), new NullProgressMonitor()).size()); + IQueryResult c = new ProvisioningPlan(null, ops, null).getRemovals().query(InstallableUnitQuery.ANY, new NullProgressMonitor()); + assertEquals(1, queryResultSize(c)); + assertEquals(1, queryResultSize(new ProvisioningPlan(null, ops, null).getAdditions().query(InstallableUnitQuery.ANY, new NullProgressMonitor()))); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SDKPatchingTest1.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SDKPatchingTest1.java index c0edda109..1adcc25b0 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SDKPatchingTest1.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SDKPatchingTest1.java @@ -10,19 +10,20 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.io.File; import java.util.ArrayList; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirementChange; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SDKPatchingTest1 extends AbstractProvisioningTest { @@ -39,14 +40,14 @@ public class SDKPatchingTest1 extends AbstractProvisioningTest { profile = registry.getProfile("SDKPatchingTest"); assertNotNull(profile); - MetadataFactory.InstallableUnitDescription newCommon = createIUDescriptor((IInstallableUnit) profile.query(new InstallableUnitQuery("org.eclipse.equinox.common"), new Collector(), new NullProgressMonitor()).iterator().next()); - Version newVersionCommon = new Version(3, 5, 0, "zeNewVersion"); + MetadataFactory.InstallableUnitDescription newCommon = createIUDescriptor((IInstallableUnit) profile.query(new InstallableUnitQuery("org.eclipse.equinox.common"), new NullProgressMonitor()).iterator().next()); + Version newVersionCommon = Version.createOSGi(3, 5, 0, "zeNewVersion"); changeVersion(newCommon, newVersionCommon); newIUs.add(MetadataFactory.createInstallableUnit(newCommon)); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "org.eclipse.equinox.common", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "org.eclipse.equinox.common", new VersionRange(newVersionCommon, true, newVersionCommon, true), null, false, false, true)); IRequiredCapability lifeCycle = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "org.eclipse.rcp.feature.group", new VersionRange("[3.5.0.v20081110-9E9vFtpFlN1yW2Ray4WRVBYE, 3.5.0.v20081110-9E9vFtpFlN1yW2Ray4WRVBYE]"), null, false, false, true); - patchInstallingCommon = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[0][0], lifeCycle); + patchInstallingCommon = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[0][0], lifeCycle); newIUs.add(patchInstallingCommon); } @@ -58,8 +59,8 @@ public class SDKPatchingTest1 extends AbstractProvisioningTest { request.addInstallableUnits(new IInstallableUnit[] {patchInstallingCommon}); request.setInstallableUnitInclusionRules(patchInstallingCommon, PlannerHelper.createOptionalInclusionRule(patchInstallingCommon)); IPlanner planner = createPlanner(); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); assertOK("Installation plan", plan.getStatus()); - assertEquals(4, plan.getOperands().length); + assertEquals(3, countPlanElements(plan)); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SDKPatchingTest2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SDKPatchingTest2.java index d9a18113d..0f204de94 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SDKPatchingTest2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SDKPatchingTest2.java @@ -10,19 +10,20 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.io.File; import java.util.ArrayList; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirementChange; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SDKPatchingTest2 extends AbstractProvisioningTest { @@ -41,26 +42,26 @@ public class SDKPatchingTest2 extends AbstractProvisioningTest { assertNotNull(profile); //create a patch to install a new version of jdt.launching - MetadataFactory.InstallableUnitDescription newJDTLaunching = createIUDescriptor((IInstallableUnit) profile.query(new InstallableUnitQuery("org.eclipse.jdt.launching"), new Collector(), new NullProgressMonitor()).iterator().next()); - Version newJDTLaunchingVersion = new Version(3, 5, 0, "zeNewVersion"); + MetadataFactory.InstallableUnitDescription newJDTLaunching = createIUDescriptor((IInstallableUnit) profile.query(new InstallableUnitQuery("org.eclipse.jdt.launching"), new NullProgressMonitor()).iterator().next()); + Version newJDTLaunchingVersion = Version.createOSGi(3, 5, 0, "zeNewVersion"); changeVersion(newJDTLaunching, newJDTLaunchingVersion); newIUs.add(MetadataFactory.createInstallableUnit(newJDTLaunching)); IRequirementChange change = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "org.eclipse.jdt.launching", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "org.eclipse.jdt.launching", new VersionRange(newJDTLaunchingVersion, true, newJDTLaunchingVersion, true), null, false, false, true)); IRequiredCapability lifeCycle = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "org.eclipse.jdt.feature.group", new VersionRange("[3.5.0.v20081202-0800-7p83FGDFHmHuj2mNpJBSKZe, 3.5.0.v20081202-0800-7p83FGDFHmHuj2mNpJBSKZe]"), null, false, false, true); - patchInstallingJDTLaunching = createIUPatch("P", new Version("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[0][0], lifeCycle); + patchInstallingJDTLaunching = createIUPatch("P", Version.create("1.0.0"), true, new IRequirementChange[] {change}, new IRequiredCapability[0][0], lifeCycle); newIUs.add(patchInstallingJDTLaunching); //create a patch to install a new version of jdt.debug.ui - MetadataFactory.InstallableUnitDescription newDebugUI = createIUDescriptor((IInstallableUnit) profile.query(new InstallableUnitQuery("org.eclipse.jdt.debug.ui"), new Collector(), new NullProgressMonitor()).iterator().next()); - Version newDebugVersion = new Version(3, 3, 0, "zeNewVersion"); + MetadataFactory.InstallableUnitDescription newDebugUI = createIUDescriptor((IInstallableUnit) profile.query(new InstallableUnitQuery("org.eclipse.jdt.debug.ui"), new NullProgressMonitor()).iterator().next()); + Version newDebugVersion = Version.createOSGi(3, 3, 0, "zeNewVersion"); changeVersion(newDebugUI, newDebugVersion); newIUs.add(MetadataFactory.createInstallableUnit(newDebugUI)); IRequirementChange change2 = MetadataFactory.createRequirementChange(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "org.eclipse.jdt.debug.ui", VersionRange.emptyRange, null, false, false, false), MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "org.eclipse.jdt.debug.ui", new VersionRange(newDebugVersion, true, newDebugVersion, true), null, false, false, true)); IRequiredCapability lifeCycle2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "org.eclipse.jdt.feature.group", new VersionRange("[3.5.0.v20081202-0800-7p83FGDFHmHuj2mNpJBSKZe, 3.5.0.v20081202-0800-7p83FGDFHmHuj2mNpJBSKZe]"), null, false, false, true); - patchInstallingDebugUI = createIUPatch("P2", new Version("1.0.0"), true, new IRequirementChange[] {change2}, new IRequiredCapability[0][0], lifeCycle2); + patchInstallingDebugUI = createIUPatch("P2", Version.create("1.0.0"), true, new IRequirementChange[] {change2}, new IRequiredCapability[0][0], lifeCycle2); newIUs.add(patchInstallingDebugUI); @@ -70,7 +71,7 @@ public class SDKPatchingTest2 extends AbstractProvisioningTest { ProvisioningContext ctx = new ProvisioningContext(); ctx.setExtraIUs(newIUs); ProfileChangeRequest validationRequest = new ProfileChangeRequest(profile); - ProvisioningPlan validationPlan = createPlanner().getProvisioningPlan(validationRequest, null, null); + IProvisioningPlan validationPlan = createPlanner().getProvisioningPlan(validationRequest, null, null); assertOK("validation", validationPlan.getStatus()); ProfileChangeRequest request = new ProfileChangeRequest(profile); @@ -78,8 +79,8 @@ public class SDKPatchingTest2 extends AbstractProvisioningTest { request.setInstallableUnitInclusionRules(patchInstallingJDTLaunching, PlannerHelper.createOptionalInclusionRule(patchInstallingJDTLaunching)); request.setInstallableUnitInclusionRules(patchInstallingDebugUI, PlannerHelper.createOptionalInclusionRule(patchInstallingDebugUI)); IPlanner planner = createPlanner(); - ProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, ctx, new NullProgressMonitor()); assertOK("Installation plan", plan.getStatus()); - assertEquals(8, plan.getOperands().length); + assertEquals(6, countPlanElements(plan)); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SWTFragment.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SWTFragment.java index b7690faec..97f93aa7d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SWTFragment.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SWTFragment.java @@ -10,32 +10,33 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.Collector; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SWTFragment extends AbstractProvisioningTest { public void testFragmentPickedByCapability() { - IRequiredCapability[] reqs = createRequiredCapabilities("swt.fragment", "swt.fragment", new VersionRange("[1.0.0, 2.0.0)"), null); + IRequiredCapability[] reqs = createRequiredCapabilities("swt.fragment", "swt.fragment", new VersionRange("[1.0.0, 2.0.0)")); IInstallableUnit swt = createIU("SWT", reqs); MetadataFactory.InstallableUnitDescription iud = new MetadataFactory.InstallableUnitDescription(); iud.setId("SWT.WIN32"); - iud.setVersion(new Version("1.0.0")); - iud.setCapabilities(new IProvidedCapability[] {MetadataFactory.createProvidedCapability("swt.fragment", "swt.fragment", new Version(1, 0, 0))}); + iud.setVersion(Version.create("1.0.0")); + iud.setCapabilities(new IProvidedCapability[] {MetadataFactory.createProvidedCapability("swt.fragment", "swt.fragment", Version.createOSGi(1, 0, 0))}); iud.setFilter("(os=win32)"); IInstallableUnit swtW = MetadataFactory.createInstallableUnit(iud); MetadataFactory.InstallableUnitDescription iud2 = new MetadataFactory.InstallableUnitDescription(); iud.setId("SWT.LINUX"); - iud.setVersion(new Version("1.0.0")); - iud.setCapabilities(new IProvidedCapability[] {MetadataFactory.createProvidedCapability("swt.fragment", "swt.fragment", new Version(1, 0, 0))}); + iud.setVersion(Version.create("1.0.0")); + iud.setCapabilities(new IProvidedCapability[] {MetadataFactory.createProvidedCapability("swt.fragment", "swt.fragment", Version.createOSGi(1, 0, 0))}); iud.setFilter("(os=linux)"); IInstallableUnit swtL = MetadataFactory.createInstallableUnit(iud2); @@ -46,10 +47,11 @@ public class SWTFragment extends AbstractProvisioningTest { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.setProfileProperty("os", "win32"); req.addInstallableUnits(new IInstallableUnit[] {swt}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertOK("plan", plan.getStatus()); - Collector c = plan.getAdditions().query(new InstallableUnitQuery("SWT"), new Collector(), null); - plan.getAdditions().query(new InstallableUnitQuery("SWT.WIN32"), c, null); + Collector c = new Collector(); + c.addAll(plan.getAdditions().query(new InstallableUnitQuery("SWT"), null)); + c.addAll(plan.getAdditions().query(new InstallableUnitQuery("SWT.WIN32"), null)); assertEquals(2, c.size()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies.java index a4fcb004b..1c829d081 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SeveralOptionalDependencies extends AbstractProvisioningTest { @@ -31,10 +35,10 @@ public class SeveralOptionalDependencies extends AbstractProvisioningTest { IRequiredCapability reqB = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, true); //normal dependency IRequiredCapability reqC = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[0.0.0, 1.0.0)"), null, true, false, true); //will not match IRequiredCapability reqD = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", VersionRange.emptyRange, null, true, false, true); //will not match - x1 = createIU("X", new Version("1.0.0"), new IRequiredCapability[] {reqA, reqB, reqC, reqD}); - a1 = createIU("A", new Version("1.0.0"), true); - b1 = createIU("B", new Version("1.0.0"), true); - c1 = createIU("C", new Version("2.0.0"), true); + x1 = createIU("X", Version.create("1.0.0"), new IRequiredCapability[] {reqA, reqB, reqC, reqD}); + a1 = createIU("A", Version.create("1.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); + c1 = createIU("C", Version.create("2.0.0"), true); createTestMetdataRepository(new IInstallableUnit[] {x1, a1, b1, c1}); @@ -45,7 +49,7 @@ public class SeveralOptionalDependencies extends AbstractProvisioningTest { public void testInstallation() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {x1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, x1); assertInstallOperand(plan, a1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies2.java index f9d07c8ae..220e60267 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies2.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SeveralOptionalDependencies2 extends AbstractProvisioningTest { @@ -31,10 +35,10 @@ public class SeveralOptionalDependencies2 extends AbstractProvisioningTest { IRequiredCapability reqB = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, true, false, true); //optional dependency, will be satisfied IRequiredCapability reqC = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[0.0.0, 1.0.0)"), null, true, false, true); //will not match IRequiredCapability reqD = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", VersionRange.emptyRange, null, true, false, true); //will not match - x1 = createIU("X", new Version("1.0.0"), new IRequiredCapability[] {reqA, reqB, reqC, reqD}); - a1 = createIU("A", new Version("1.0.0"), true); - b1 = createIU("B", new Version("1.0.0"), true); - c1 = createIU("C", new Version("2.0.0"), true); + x1 = createIU("X", Version.create("1.0.0"), new IRequiredCapability[] {reqA, reqB, reqC, reqD}); + a1 = createIU("A", Version.create("1.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); + c1 = createIU("C", Version.create("2.0.0"), true); createTestMetdataRepository(new IInstallableUnit[] {x1, a1, b1, c1}); @@ -45,7 +49,7 @@ public class SeveralOptionalDependencies2 extends AbstractProvisioningTest { public void testInstallation() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {x1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, x1); assertInstallOperand(plan, a1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies3.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies3.java index fe87d0b28..279b553da 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies3.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies3.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SeveralOptionalDependencies3 extends AbstractProvisioningTest { @@ -28,7 +32,7 @@ public class SeveralOptionalDependencies3 extends AbstractProvisioningTest { IRequiredCapability reqB = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, true, false, true); //optional dependency, will not be satisfied IRequiredCapability reqC = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[0.0.0, 1.0.0)"), null, true, false, true); //will not match IRequiredCapability reqD = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", VersionRange.emptyRange, null, true, false, true); //will not match - x1 = createIU("X", new Version("1.0.0"), new IRequiredCapability[] {reqA, reqB, reqC, reqD}); + x1 = createIU("X", Version.create("1.0.0"), new IRequiredCapability[] {reqA, reqB, reqC, reqD}); createTestMetdataRepository(new IInstallableUnit[] {x1}); @@ -40,7 +44,7 @@ public class SeveralOptionalDependencies3 extends AbstractProvisioningTest { //X will install because all the requirements are optional ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {x1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, x1); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies4.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies4.java index abbecf395..fd4b24977 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies4.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies4.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SeveralOptionalDependencies4 extends AbstractProvisioningTest { @@ -29,10 +33,10 @@ public class SeveralOptionalDependencies4 extends AbstractProvisioningTest { super.setUp(); IRequiredCapability reqA = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, true, false, true); //optional dependency, will be satisfied IRequiredCapability reqB = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, true); //normal dependency - x1 = createIU("X", new Version("1.0.0"), new IRequiredCapability[] {reqA, reqB,}); - a1 = createIU("A", new Version("1.0.0"), true); - a2 = createIU("A", new Version("2.0.0"), true); - b1 = createIU("B", new Version("1.0.0"), true); + x1 = createIU("X", Version.create("1.0.0"), new IRequiredCapability[] {reqA, reqB,}); + a1 = createIU("A", Version.create("1.0.0"), true); + a2 = createIU("A", Version.create("2.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); createTestMetdataRepository(new IInstallableUnit[] {x1, a1, b1, a2}); @@ -43,7 +47,7 @@ public class SeveralOptionalDependencies4 extends AbstractProvisioningTest { public void testInstallation() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {x1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, x1); assertInstallOperand(plan, b1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies5.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies5.java index c083bfb85..b7f38dff2 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies5.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SeveralOptionalDependencies5.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SeveralOptionalDependencies5 extends AbstractProvisioningTest { @@ -30,15 +34,15 @@ public class SeveralOptionalDependencies5 extends AbstractProvisioningTest { IRequiredCapability reqA = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", VersionRange.emptyRange, null, true, false, true); //optional dependency, will be satisfied IRequiredCapability reqC = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", new VersionRange("[1.0.0, 2.0.0)"), null, true, false, true); //optional dependency, will be satisfied because it is the highest version IRequiredCapability reqE = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "E", new VersionRange("[1.0.0, 2.0.0)"), null, true, false, true); //optional dependency, will be satisfied because it is the highest version - x1 = createIU("X", new Version("1.0.0"), new IRequiredCapability[] {reqA, reqC, reqE}); + x1 = createIU("X", Version.create("1.0.0"), new IRequiredCapability[] {reqA, reqC, reqE}); IRequiredCapability reqB = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, true); //optional dependency, will be satisfied - a1 = createIU("A", new Version("1.0.0"), new IRequiredCapability[] {reqB}); + a1 = createIU("A", Version.create("1.0.0"), new IRequiredCapability[] {reqB}); IRequiredCapability reqD = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", VersionRange.emptyRange, null, false, false, true); //optional dependency, will be satisfied - c1 = createIU("C", new Version("1.0.0"), new IRequiredCapability[] {reqD}); + c1 = createIU("C", Version.create("1.0.0"), new IRequiredCapability[] {reqD}); - b1 = createIU("B", new Version("1.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); createTestMetdataRepository(new IInstallableUnit[] {x1, a1, b1, c1}); profile = createProfile("TestProfile." + getName()); @@ -48,7 +52,7 @@ public class SeveralOptionalDependencies5 extends AbstractProvisioningTest { public void testInstallation() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {x1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, x1); assertInstallOperand(plan, a1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest.java index 78d1f4200..40a025920 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SimpleOptionalTest extends AbstractProvisioningTest { @@ -29,12 +33,12 @@ public class SimpleOptionalTest extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - b1 = createIU("B", new Version("1.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); //B's dependency is missing IRequiredCapability[] reqA = new IRequiredCapability[1]; reqA[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, true, false, true); - a1 = createIU("A", new Version("1.0.0"), reqA); + a1 = createIU("A", Version.create("1.0.0"), reqA); createTestMetdataRepository(new IInstallableUnit[] {a1, b1}); @@ -46,7 +50,7 @@ public class SimpleOptionalTest extends AbstractProvisioningTest { //Ensure that D's installation does not fail because of C's absence ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, a1); assertInstallOperand(plan, b1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest2.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest2.java index d59c3caaf..17af35a66 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest2.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest2.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SimpleOptionalTest2 extends AbstractProvisioningTest { @@ -35,26 +39,26 @@ public class SimpleOptionalTest2 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - b1 = createIU("B", new Version("1.0.0"), true); - b2 = createIU("B", new Version("2.0.0"), true); - b3 = createIU("B", new Version("3.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); + b2 = createIU("B", Version.create("2.0.0"), true); + b3 = createIU("B", Version.create("3.0.0"), true); - c1 = createIU("C", new Version("1.0.0"), true); - c2 = createIU("C", new Version("2.0.0"), true); + c1 = createIU("C", Version.create("1.0.0"), true); + c2 = createIU("C", Version.create("2.0.0"), true); - d1 = createIU("D", new Version("1.0.0"), true); - d2 = createIU("D", new Version("2.0.0"), true); + d1 = createIU("D", Version.create("1.0.0"), true); + d2 = createIU("D", Version.create("2.0.0"), true); - y1 = createIU("Y", new Version("1.0.0"), true); + y1 = createIU("Y", Version.create("1.0.0"), true); - z1 = createIU("Z", new Version("1.0.0"), true); + z1 = createIU("Z", Version.create("1.0.0"), true); //B's dependency is missing IRequiredCapability[] reqA = new IRequiredCapability[3]; reqA[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, false, false, true); reqA[1] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, true, false, true); reqA[2] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", VersionRange.emptyRange, null, true, false, true); - a1 = createIU("A", new Version("1.0.0"), reqA); + a1 = createIU("A", Version.create("1.0.0"), reqA); IRequiredCapability[] req = new IRequiredCapability[3]; req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", new VersionRange("[1.0.0, 1.0.0]"), null, false, false, true); @@ -72,7 +76,7 @@ public class SimpleOptionalTest2 extends AbstractProvisioningTest { //Ensure that D's installation does not fail because of C's absence ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1, x1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, a1); assertInstallOperand(plan, c2); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest3.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest3.java index e02c3f170..2aff62927 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest3.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest3.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SimpleOptionalTest3 extends AbstractProvisioningTest { @@ -33,21 +37,21 @@ public class SimpleOptionalTest3 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - b1 = createIU("B", new Version("1.0.0"), true); - b2 = createIU("B", new Version("2.0.0"), true); - b3 = createIU("B", new Version("3.0.0"), true); + b1 = createIU("B", Version.create("1.0.0"), true); + b2 = createIU("B", Version.create("2.0.0"), true); + b3 = createIU("B", Version.create("3.0.0"), true); - c1 = createIU("C", new Version("1.0.0"), true); - c2 = createIU("C", new Version("2.0.0"), true); + c1 = createIU("C", Version.create("1.0.0"), true); + c2 = createIU("C", Version.create("2.0.0"), true); - d1 = createIU("D", new Version("1.0.0"), true); - d2 = createIU("D", new Version("2.0.0"), true); + d1 = createIU("D", Version.create("1.0.0"), true); + d2 = createIU("D", Version.create("2.0.0"), true); IRequiredCapability[] reqA = new IRequiredCapability[3]; reqA[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", VersionRange.emptyRange, null, true, false, true); reqA[1] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "C", VersionRange.emptyRange, null, false, false, true); reqA[2] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "D", VersionRange.emptyRange, null, true, false, true); - a1 = createIU("A", new Version("1.0.0"), reqA); + a1 = createIU("A", Version.create("1.0.0"), reqA); IRequiredCapability[] req = new IRequiredCapability[1]; req[0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 2.0.0]"), null, false, false, true); @@ -63,7 +67,7 @@ public class SimpleOptionalTest3 extends AbstractProvisioningTest { //Ensure that A and X1's installation does not fail because of C's absence ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1, x1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, a1); assertInstallOperand(plan, c2); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest4.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest4.java index d0f349f29..6d577d7a0 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest4.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleOptionalTest4.java @@ -8,13 +8,17 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SimpleOptionalTest4 extends AbstractProvisioningTest { @@ -32,10 +36,10 @@ public class SimpleOptionalTest4 extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - b1 = createIU("B", new Version("1.0.0"), false); - b2 = createIU("B", new Version("2.0.0"), false); - b3 = createIU("B", new Version("3.0.0"), false); - b4 = createIU("B", new Version("4.0.0"), false); + b1 = createIU("B", Version.create("1.0.0"), false); + b2 = createIU("B", Version.create("2.0.0"), false); + b3 = createIU("B", Version.create("3.0.0"), false); + b4 = createIU("B", Version.create("4.0.0"), false); //B's dependency is missing IRequiredCapability[] reqA = new IRequiredCapability[4]; @@ -43,7 +47,7 @@ public class SimpleOptionalTest4 extends AbstractProvisioningTest { reqA[1] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[2.0.0,2.0.0]"), null, true, false, true); reqA[2] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[3.0.0,3.0.0]"), null, true, false, true); reqA[3] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[4.0.0,4.0.0]"), null, true, false, true); - a1 = createIU("A", new Version("1.0.0"), reqA); + a1 = createIU("A", Version.create("1.0.0"), reqA); createTestMetdataRepository(new IInstallableUnit[] {a1, b1, b2, b3, b4}); @@ -55,7 +59,7 @@ public class SimpleOptionalTest4 extends AbstractProvisioningTest { //Ensure that D's installation does not fail because of C's absence ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {a1, b1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + IProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.OK, plan.getStatus().getSeverity()); assertInstallOperand(plan, a1); assertInstallOperand(plan, b1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleSingleton.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleSingleton.java index 40254100d..810e1097b 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleSingleton.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimpleSingleton.java @@ -10,14 +10,17 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.director.Explanation; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.ProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SimpleSingleton extends AbstractProvisioningTest { @@ -32,13 +35,13 @@ public class SimpleSingleton extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", new Version("1.0.0"), true); + a1 = createIU("A", Version.create("1.0.0"), true); - a2 = createIU("A", new Version("2.0.0"), true); + a2 = createIU("A", Version.create("2.0.0"), true); IRequiredCapability c1 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[1.0.0, 1.0.0]"), null, false, false); IRequiredCapability c2 = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "A", new VersionRange("[2.0.0, 2.0.0]"), null, false, false); - y = createIU("Y", new Version(2, 0, 0), new IRequiredCapability[] {c1, c2}); + y = createIU("Y", Version.createOSGi(2, 0, 0), new IRequiredCapability[] {c1, c2}); createTestMetdataRepository(new IInstallableUnit[] {a1, a2, y}); @@ -50,7 +53,7 @@ public class SimpleSingleton extends AbstractProvisioningTest { public void test1() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {y}); - ProvisioningPlan provisioningPlan = planner.getProvisioningPlan(req, null, null); + ProvisioningPlan provisioningPlan = (ProvisioningPlan) planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.ERROR, provisioningPlan.getStatus().getSeverity()); assertNotNull(provisioningPlan.getCompleteState()); } @@ -58,9 +61,10 @@ public class SimpleSingleton extends AbstractProvisioningTest { public void testExplanation() { ProfileChangeRequest req = new ProfileChangeRequest(profile); req.addInstallableUnits(new IInstallableUnit[] {y}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); + ProvisioningPlan plan = (ProvisioningPlan) planner.getProvisioningPlan(req, null, null); assertEquals(IStatus.ERROR, plan.getStatus().getSeverity()); - assertEquals(Explanation.VIOLATED_SINGLETON_CONSTRAINT, plan.getRequestStatus().getShortExplanation()); - assertTrue(plan.getRequestStatus().getConflictsWithInstalledRoots().contains(y)); + final RequestStatus requestStatus = (RequestStatus) plan.getRequestStatus(); + assertEquals(Explanation.VIOLATED_SINGLETON_CONSTRAINT, requestStatus.getShortExplanation()); + assertTrue(requestStatus.getConflictsWithInstalledRoots().contains(y)); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimulatedSharedInstallTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimulatedSharedInstallTest.java index 16d0cbdfa..170c79a24 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimulatedSharedInstallTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/SimulatedSharedInstallTest.java @@ -10,16 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.net.URI; import java.util.*; import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SimulatedSharedInstallTest extends AbstractProvisioningTest { @@ -34,7 +34,7 @@ public class SimulatedSharedInstallTest extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a1 = createIU("A", Version.parseVersion("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.0.0]"), null)); + a1 = createIU("A", Version.parseVersion("1.0.0"), createRequiredCapabilities(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.0.0]"))); b1 = createIU("B", Version.parseVersion("1.0.0")); // Note: C has an "optional" dependency on "B" c1 = createIU("C", Version.parseVersion("1.0.0"), new IRequiredCapability[] {MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "B", new VersionRange("[1.0.0, 1.0.0]"), null, true, false)}); @@ -44,28 +44,44 @@ public class SimulatedSharedInstallTest extends AbstractProvisioningTest { } public void testRemoveUnresolvedIU() { - assertEquals(IStatus.OK, engine.perform(profile, new DefaultPhaseSet(), new Operand[] {new InstallableUnitOperand(null, a1), new InstallableUnitPropertyOperand(a1, "org.eclipse.equinox.p2.internal.inclusion.rules", null, "STRICT")}, new ProvisioningContext(new URI[0]), new NullProgressMonitor()).getSeverity()); - assertTrue(profile.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection().contains(a1)); + ProfileChangeRequest request = new ProfileChangeRequest(profile); + request.setAbsoluteMode(true); + request.addInstallableUnits(new IInstallableUnit[] {a1}); + request.setInstallableUnitInclusionRules(a1, PlannerHelper.createStrictInclusionRule(a1)); + final ProvisioningContext context = new ProvisioningContext(new URI[0]); + IProvisioningPlan plan = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); + assertEquals(IStatus.OK, engine.perform(plan, new NullProgressMonitor()).getSeverity()); + assertContains(profile.query(InstallableUnitQuery.ANY, null), a1); ProfileChangeRequest req = new ProfileChangeRequest(profile); req.removeInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); - assertEquals(IStatus.OK, plan.getStatus().getSeverity()); - assertEquals(IStatus.OK, PlanExecutionHelper.executePlan(plan, engine, new ProvisioningContext(new URI[0]), new NullProgressMonitor()).getSeverity()); - assertFalse(profile.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection().contains(a1)); + + IProvisioningPlan plan2 = planner.getProvisioningPlan(req, null, null); + assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); + assertEquals(IStatus.OK, PlanExecutionHelper.executePlan(plan2, engine, context, new NullProgressMonitor()).getSeverity()); + assertNotContains(profile.query(InstallableUnitQuery.ANY, null), a1); } public void testAvailableVsQueryInProfile() { - assertEquals(IStatus.OK, engine.perform(profile, new DefaultPhaseSet(), new Operand[] {new InstallableUnitOperand(null, c1), new InstallableUnitPropertyOperand(c1, "org.eclipse.equinox.p2.internal.inclusion.rules", null, "STRICT")}, new ProvisioningContext(new URI[0]), new NullProgressMonitor()).getSeverity()); - assertTrue(profile.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection().contains(c1)); + ProfileChangeRequest request = new ProfileChangeRequest(profile); + request.setAbsoluteMode(true); + request.addInstallableUnits(new IInstallableUnit[] {c1}); + request.setInstallableUnitInclusionRules(c1, PlannerHelper.createStrictInclusionRule(c1)); + final ProvisioningContext context = new ProvisioningContext(new URI[0]); + IProvisioningPlan plan = planner.getProvisioningPlan(request, context, new NullProgressMonitor()); + assertEquals(IStatus.OK, engine.perform(plan, new NullProgressMonitor()).getSeverity()); + assertContains(profile.query(InstallableUnitQuery.ANY, null), c1); IProfile availableWrapper = new IProfile() { - public Collector available(Query query, Collector collector, IProgressMonitor monitor) { - profile.query(query, collector, monitor); + public IQueryResult available(IQuery query, IProgressMonitor monitor) { + IQueryResult queryResult = profile.query(query, monitor); + Collector collector = new Collector(); + collector.addAll(queryResult); Collection ius = new ArrayList(); ius.add(b1); - return query.perform(ius.iterator(), collector); + collector.addAll(query.perform(ius.iterator())); + return collector; } // everything else is delegated @@ -77,18 +93,6 @@ public class SimulatedSharedInstallTest extends AbstractProvisioningTest { return profile.getInstallableUnitProperty(iu, key); } - public Map getLocalProperties() { - return profile.getLocalProperties(); - } - - public String getLocalProperty(String key) { - return profile.getLocalProperty(key); - } - - public IProfile getParentProfile() { - return profile.getParentProfile(); - } - public String getProfileId() { return profile.getProfileId(); } @@ -101,33 +105,21 @@ public class SimulatedSharedInstallTest extends AbstractProvisioningTest { return profile.getProperty(key); } - public String[] getSubProfileIds() { - return profile.getSubProfileIds(); - } - public long getTimestamp() { return profile.getTimestamp(); } - public boolean hasSubProfiles() { - return profile.hasSubProfiles(); - } - - public boolean isRootProfile() { - return profile.isRootProfile(); - } - - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - return profile.query(query, collector, monitor); + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return profile.query(query, monitor); } }; ProfileChangeRequest req = new ProfileChangeRequest(availableWrapper); req.addInstallableUnits(new IInstallableUnit[] {a1}); - ProvisioningPlan plan = planner.getProvisioningPlan(req, null, null); - assertEquals(IStatus.OK, plan.getStatus().getSeverity()); + IProvisioningPlan plan2 = planner.getProvisioningPlan(req, null, null); + assertEquals(IStatus.OK, plan2.getStatus().getSeverity()); //expect to have both (a1+inclusion rule) and b1 added - assertEquals(3, plan.getOperands().length); + assertEquals(2, countPlanElements(plan2)); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/TopLevelFilterTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/TopLevelFilterTest.java index 7bb519503..95546c1f5 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/TopLevelFilterTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/TopLevelFilterTest.java @@ -10,13 +10,13 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class TopLevelFilterTest extends AbstractProvisioningTest { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/TwoVersionsOfWSDL.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/TwoVersionsOfWSDL.java index 8027fe8c2..2a1ffea34 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/TwoVersionsOfWSDL.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/TwoVersionsOfWSDL.java @@ -8,20 +8,18 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager; import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; @@ -34,10 +32,10 @@ public class TwoVersionsOfWSDL extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - IMetadataRepositoryManager repoMan = (MetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager repoMan = (MetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); IMetadataRepository repo = repoMan.loadRepository(getTestData("repository for wsdl test", "testData/metadataRepo/wsdlTestRepo/").toURI(), new NullProgressMonitor()); - wsdl15 = (IInstallableUnit) repo.query(new InstallableUnitQuery("javax.wsdl", new VersionRange("[1.5, 1.6)")), new Collector(), null).iterator().next(); - wsdl14 = (IInstallableUnit) repo.query(new InstallableUnitQuery("javax.wsdl", new VersionRange("[1.4, 1.5)")), new Collector(), null).iterator().next(); + wsdl15 = (IInstallableUnit) repo.query(new InstallableUnitQuery("javax.wsdl", new VersionRange("[1.5, 1.6)")), null).iterator().next(); + wsdl14 = (IInstallableUnit) repo.query(new InstallableUnitQuery("javax.wsdl", new VersionRange("[1.4, 1.5)")), null).iterator().next(); profile1 = createProfile("TestProfile." + getName()); planner = createPlanner(); @@ -50,7 +48,7 @@ public class TwoVersionsOfWSDL extends AbstractProvisioningTest { req1.addInstallableUnits(new IInstallableUnit[] {wsdl15, wsdl14}); req1.setInstallableUnitInclusionRules(wsdl15, PlannerHelper.createStrictInclusionRule(wsdl15)); req1.setInstallableUnitInclusionRules(wsdl14, PlannerHelper.createStrictInclusionRule(wsdl14)); - ProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); + IProvisioningPlan plan1 = planner.getProvisioningPlan(req1, null, null); assertEquals(IStatus.OK, plan1.getStatus().getSeverity()); assertInstallOperand(plan1, wsdl15); assertInstallOperand(plan1, wsdl14); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/UninstallEverything.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/UninstallEverything.java index 020a57b07..56919d657 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/UninstallEverything.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/UninstallEverything.java @@ -8,15 +8,14 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.planner; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.provisional.p2.director.IDirector; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class UninstallEverything extends AbstractProvisioningTest { @@ -27,7 +26,7 @@ public class UninstallEverything extends AbstractProvisioningTest { protected void setUp() throws Exception { super.setUp(); - a = createIU("A", new Version("1.0.0")); + a = createIU("A", Version.create("1.0.0")); createTestMetdataRepository(new IInstallableUnit[] {a}); profile = createProfile(Bug207319.class.getName()); director = createDirector(); @@ -43,7 +42,7 @@ public class UninstallEverything extends AbstractProvisioningTest { ProfileChangeRequest req2 = new ProfileChangeRequest(profile); req2.removeInstallableUnits(new IInstallableUnit[] {a}); assertEquals(IStatus.OK, director.provision(req2, null, null).getSeverity()); - assertNotIUs(new IInstallableUnit[] {a}, profile.query(InstallableUnitQuery.ANY, new Collector(), null).iterator()); + assertNotIUs(new IInstallableUnit[] {a}, profile.query(InstallableUnitQuery.ANY, null).iterator()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/UpdateQueryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/UpdateQueryTest.java new file mode 100644 index 000000000..6d8b155c1 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/UpdateQueryTest.java @@ -0,0 +1,49 @@ +package org.eclipse.equinox.p2.tests.planner; + +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; + +import org.eclipse.equinox.internal.p2.metadata.query.UpdateQuery; +import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; + +public class UpdateQueryTest extends AbstractProvisioningTest { + private IInstallableUnit a1; + private IInstallableUnit updateOfA; + private IInstallableUnit a11; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + a1 = createIU("A", Version.create("2.0.0")); + IUpdateDescriptor update = MetadataFactory.createUpdateDescriptor("A", new VersionRange("[2.0.0, 2.0.0]"), 0, "update description"); + updateOfA = createIU("UpdateA", Version.createOSGi(1, 0, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, false, update, NO_REQUIRES); + a11 = createIUUpdate(); + } + + public void testUpdateWithDifferentId() { + IMetadataRepository repo = createTestMetdataRepository(new IInstallableUnit[] {a1, updateOfA}); + IQueryResult c = repo.query(new UpdateQuery(a1), null); + assertEquals(1, queryResultSize(c)); + assertEquals(updateOfA, c.iterator().next()); + } + + public void testWithSuperiorVersion() { + IMetadataRepository repo2 = createTestMetdataRepository(new IInstallableUnit[] {a11, a1}); + IQueryResult c2 = repo2.query(new UpdateQuery(a1), null); + assertEquals(1, queryResultSize(c2)); + assertEquals(a11, c2.iterator().next()); + } + + public void testUpdateWithSameId() { + + } + + private IInstallableUnit createIUUpdate() { + return createIU("A", Version.create("2.1.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, MetadataFactory.createUpdateDescriptor("A", new VersionRange("[2.0.0, 2.1.0]"), 0, "update description"), null); + } +} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/TestArtifactRepository.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/TestArtifactRepository.java index c10371c65..aef0693c2 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/TestArtifactRepository.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/TestArtifactRepository.java @@ -17,22 +17,23 @@ import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.artifact.repository.ArtifactRequest; import org.eclipse.equinox.internal.p2.artifact.repository.Messages; import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepHandler; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; import org.eclipse.equinox.internal.provisional.p2.repository.IStateful; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.tests.TestActivator; import org.eclipse.osgi.util.NLS; -@SuppressWarnings( {"restriction", "unchecked"}) public class TestArtifactRepository implements IArtifactRepository { private static String provider = null; - private HashMap/**/repo; + private HashMap repo; private String name; private String description; private String version = "1.0.0"; //$NON-NLS-1$ - protected Map properties = new OrderedProperties(); + protected Map properties = new OrderedProperties(); public class ArtifactOutputStream extends OutputStream implements IStateful { private boolean closed; @@ -137,8 +138,7 @@ public class TestArtifactRepository implements IArtifactRepository { } public synchronized boolean contains(IArtifactKey key) { - for (Iterator/**/iterator = repo.keySet().iterator(); iterator.hasNext();) { - IArtifactDescriptor descriptor = (IArtifactDescriptor) iterator.next(); + for (IArtifactDescriptor descriptor : repo.keySet()) { if (descriptor.getArtifactKey().equals(key)) return true; } @@ -147,7 +147,7 @@ public class TestArtifactRepository implements IArtifactRepository { public IStatus getArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) { try { - byte[] repoContents = (byte[]) repo.get(descriptor); + byte[] repoContents = repo.get(descriptor); if (repoContents == null) return null; destination.write(repoContents); @@ -159,22 +159,12 @@ public class TestArtifactRepository implements IArtifactRepository { } public IArtifactDescriptor[] getArtifactDescriptors(IArtifactKey key) { - Set/**/result = new HashSet/**/(); - for (Iterator/**/iterator = repo.keySet().iterator(); iterator.hasNext();) { - IArtifactDescriptor descriptor = (IArtifactDescriptor) iterator.next(); + Set result = new HashSet(); + for (IArtifactDescriptor descriptor : repo.keySet()) { if (descriptor.getArtifactKey().equals(key)) result.add(descriptor); } - return (IArtifactDescriptor[]) result.toArray(new IArtifactDescriptor[0]); - } - - public IArtifactKey[] getArtifactKeys() { - Set/**/result = new HashSet/**/(); - for (Iterator/**/iterator = repo.keySet().iterator(); iterator.hasNext();) { - IArtifactDescriptor descriptor = (IArtifactDescriptor) iterator.next(); - result.add(descriptor.getArtifactKey()); - } - return (IArtifactKey[]) result.toArray(new IArtifactKey[0]); + return result.toArray(new IArtifactDescriptor[0]); } public IStatus getArtifacts(IArtifactRequest[] requests, IProgressMonitor monitor) { @@ -254,7 +244,7 @@ public class TestArtifactRepository implements IArtifactRepository { } public String setProperty(String key, String value) { - return (String) (value == null ? properties.remove(key) : properties.put(key, value)); + return (value == null ? properties.remove(key) : properties.put(key, value)); } public void setProvider(String value) { @@ -278,7 +268,7 @@ public class TestArtifactRepository implements IArtifactRepository { } public InputStream getRawInputStream(IArtifactDescriptor descriptor) { - return new ByteArrayInputStream((byte[]) repo.get(descriptor), 0, ((byte[]) repo.get(descriptor)).length); + return new ByteArrayInputStream(repo.get(descriptor), 0, repo.get(descriptor).length); } public ZipInputStream getZipInputStream(IArtifactDescriptor descriptor) { @@ -286,10 +276,35 @@ public class TestArtifactRepository implements IArtifactRepository { } public byte[] getBytes(IArtifactDescriptor artifactDescriptor) { - return (byte[]) repo.get(artifactDescriptor); + return repo.get(artifactDescriptor); } public IStatus getRawArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) { return getArtifact(descriptor, destination, monitor); } + + public IArtifactDescriptor createArtifactDescriptor(IArtifactKey key) { + return new ArtifactDescriptor(key); + } + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + if (monitor != null && monitor.isCanceled()) + return Collector.emptyCollector(); + + Collector collector = new Collector(); + for (IArtifactDescriptor descriptor : repo.keySet()) { + collector.accept(descriptor.getArtifactKey()); + } + return collector; + } + + public IQueryable descriptorQueryable() { + final Collection descs = repo.keySet(); + return new IQueryable() { + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return query.perform(descs.iterator()); + } + }; + } } \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AbstractPublisherActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AbstractPublisherActionTest.java index f4d8c899c..0262ec528 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AbstractPublisherActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AbstractPublisherActionTest.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.publisher.actions; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.provisional.p2.metadata.*; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.metadata.IProvidedCapability; import org.eclipse.equinox.p2.publisher.*; import org.eclipse.equinox.p2.publisher.actions.ICapabilityAdvice; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; @@ -77,9 +79,9 @@ public class AbstractPublisherActionTest extends AbstractProvisioningTest { public void testAddCapabilities() { InstallableUnitDescription iu = new InstallableUnitDescription(); iu.setId("test"); - assertEquals(0, iu.getRequiredCapabilities().length); - assertEquals(0, iu.getProvidedCapabilities().length); - assertEquals(0, iu.getMetaRequiredCapabilities().length); + assertEquals(0, iu.getRequiredCapabilities().size()); + assertEquals(0, iu.getProvidedCapabilities().size()); + assertEquals(0, iu.getMetaRequiredCapabilities().size()); IPublisherInfo info = new PublisherInfo(); IRequiredCapability testRequiredCapability = MetadataFactory.createRequiredCapability("ns1", "name1", null, null, false, false, false); @@ -90,9 +92,9 @@ public class AbstractPublisherActionTest extends AbstractProvisioningTest { TestAction action = new TestAction(); action.testProcessCapabilityAdvice(iu, info); - assertEquals("name1", iu.getRequiredCapabilities()[0].getName()); - assertEquals("name2", iu.getProvidedCapabilities()[0].getName()); - assertEquals("name3", iu.getMetaRequiredCapabilities()[0].getName()); + assertEquals("name1", ((IRequiredCapability) iu.getRequiredCapabilities().iterator().next()).getName()); + assertEquals("name2", iu.getProvidedCapabilities().iterator().next().getName()); + assertEquals("name3", ((IRequiredCapability) iu.getMetaRequiredCapabilities().iterator().next()).getName()); } public void testAddCapabilitiesIdentityCounts() { @@ -123,9 +125,9 @@ public class AbstractPublisherActionTest extends AbstractProvisioningTest { metaRequiredCapabilities[4] = MetadataFactory.createRequiredCapability("mtest3", "test3", null, null, false, false, false); iu.setMetaRequiredCapabilities(metaRequiredCapabilities); - assertEquals(5, iu.getRequiredCapabilities().length); - assertEquals(5, iu.getProvidedCapabilities().length); - assertEquals(5, iu.getMetaRequiredCapabilities().length); + assertEquals(5, iu.getRequiredCapabilities().size()); + assertEquals(5, iu.getProvidedCapabilities().size()); + assertEquals(5, iu.getMetaRequiredCapabilities().size()); IPublisherInfo info = new PublisherInfo(); IRequiredCapability testRequiredCapability = MetadataFactory.createRequiredCapability("ns1", "name1", null, null, false, false, false); @@ -136,9 +138,9 @@ public class AbstractPublisherActionTest extends AbstractProvisioningTest { TestAction action = new TestAction(); action.testProcessCapabilityAdvice(iu, info); - assertEquals(6, iu.getRequiredCapabilities().length); - assertEquals(6, iu.getProvidedCapabilities().length); - assertEquals(6, iu.getMetaRequiredCapabilities().length); + assertEquals(6, iu.getRequiredCapabilities().size()); + assertEquals(6, iu.getProvidedCapabilities().size()); + assertEquals(6, iu.getMetaRequiredCapabilities().size()); } public void testReplaceCapabilities() { @@ -148,9 +150,9 @@ public class AbstractPublisherActionTest extends AbstractProvisioningTest { iu.setCapabilities(new IProvidedCapability[] {MetadataFactory.createProvidedCapability("ns2", "name2", null)}); iu.setMetaRequiredCapabilities(createRequiredCapabilities("ns3", "name3", null, "")); - assertNotSame(9, iu.getProvidedCapabilities()[0].getVersion().getMajor()); - assertTrue(iu.getRequiredCapabilities()[0].isGreedy()); - assertTrue(iu.getMetaRequiredCapabilities()[0].isGreedy()); + assertNotSame(9, Version.toOSGiVersion(iu.getProvidedCapabilities().iterator().next().getVersion()).getMajor()); + assertTrue(iu.getRequiredCapabilities().iterator().next().isGreedy()); + assertTrue(iu.getMetaRequiredCapabilities().iterator().next().isGreedy()); IPublisherInfo info = new PublisherInfo(); IRequiredCapability testRequiredCapability = MetadataFactory.createRequiredCapability("ns1", "name1", null, null, false, false, false); @@ -161,9 +163,9 @@ public class AbstractPublisherActionTest extends AbstractProvisioningTest { TestAction action = new TestAction(); action.testProcessCapabilityAdvice(iu, info); - assertEquals(9, iu.getProvidedCapabilities()[0].getVersion().getMajor()); - assertFalse(iu.getRequiredCapabilities()[0].isGreedy()); - assertFalse(iu.getMetaRequiredCapabilities()[0].isGreedy()); + assertEquals(9, Version.toOSGiVersion(iu.getProvidedCapabilities().iterator().next().getVersion()).getMajor()); + assertFalse(iu.getRequiredCapabilities().iterator().next().isGreedy()); + assertFalse(iu.getMetaRequiredCapabilities().iterator().next().isGreedy()); } public void testReplaceCapabilitiesIdentityCounts() { @@ -194,9 +196,9 @@ public class AbstractPublisherActionTest extends AbstractProvisioningTest { metaRequiredCapabilities[4] = MetadataFactory.createRequiredCapability("mtest3", "test3", null, null, false, false, false); iu.setMetaRequiredCapabilities(metaRequiredCapabilities); - assertEquals(5, iu.getRequiredCapabilities().length); - assertEquals(5, iu.getProvidedCapabilities().length); - assertEquals(5, iu.getMetaRequiredCapabilities().length); + assertEquals(5, iu.getRequiredCapabilities().size()); + assertEquals(5, iu.getProvidedCapabilities().size()); + assertEquals(5, iu.getMetaRequiredCapabilities().size()); IPublisherInfo info = new PublisherInfo(); IRequiredCapability testRequiredCapability = MetadataFactory.createRequiredCapability("rtest1", "test1", null, null, false, false, false); @@ -207,9 +209,9 @@ public class AbstractPublisherActionTest extends AbstractProvisioningTest { TestAction action = new TestAction(); action.testProcessCapabilityAdvice(iu, info); - assertEquals(4, iu.getRequiredCapabilities().length); - assertEquals(4, iu.getProvidedCapabilities().length); - assertEquals(4, iu.getMetaRequiredCapabilities().length); + assertEquals(4, iu.getRequiredCapabilities().size()); + assertEquals(4, iu.getProvidedCapabilities().size()); + assertEquals(4, iu.getMetaRequiredCapabilities().size()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AccumulateConfigDataActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AccumulateConfigDataActionTest.java index 9eb4f1c01..8f84737a9 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AccumulateConfigDataActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AccumulateConfigDataActionTest.java @@ -14,7 +14,7 @@ import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; -import java.util.Properties; +import java.util.Map; import org.easymock.Capture; import org.easymock.EasyMock; import org.eclipse.core.runtime.NullProgressMonitor; @@ -24,7 +24,7 @@ import org.eclipse.equinox.internal.provisional.frameworkadmin.ConfigData; import org.eclipse.equinox.p2.publisher.eclipse.*; import org.eclipse.equinox.p2.tests.TestActivator; -@SuppressWarnings( {"restriction", "unchecked"}) +@SuppressWarnings({"restriction", "unchecked"}) public class AccumulateConfigDataActionTest extends ActionTest { private static String EXECUTABLE_NAME = "run.exe"; //$NON-NLS-1$ @@ -75,11 +75,11 @@ public class AccumulateConfigDataActionTest extends ActionTest { private void verifyConfigAdvice() throws Exception { ConfigAdvice captured = configAdviceCapture.getValue(); - Properties prop = captured.getProperties(); - assertTrue(prop.getProperty("eclipse.buildId").equalsIgnoreCase("TEST-ID")); //$NON-NLS-1$ //$NON-NLS-2$ - assertTrue(prop.getProperty("eclipse.p2.profile").equalsIgnoreCase("PlatformProfile")); //$NON-NLS-1$//$NON-NLS-2$ - assertTrue(prop.getProperty("org.eclipse.update.reconcile").equalsIgnoreCase("false")); //$NON-NLS-1$//$NON-NLS-2$ - assertTrue(prop.getProperty("eclipse.product").equalsIgnoreCase("org.eclipse.platform.ide")); //$NON-NLS-1$//$NON-NLS-2$ + Map prop = captured.getProperties(); + assertTrue(prop.get("eclipse.buildId").equalsIgnoreCase("TEST-ID")); //$NON-NLS-1$ //$NON-NLS-2$ + assertTrue(prop.get("eclipse.p2.profile").equalsIgnoreCase("PlatformProfile")); //$NON-NLS-1$//$NON-NLS-2$ + assertTrue(prop.get("org.eclipse.update.reconcile").equalsIgnoreCase("false")); //$NON-NLS-1$//$NON-NLS-2$ + assertTrue(prop.get("eclipse.product").equalsIgnoreCase("org.eclipse.platform.ide")); //$NON-NLS-1$//$NON-NLS-2$ assertContainsSymbolicName(captured.getBundles(), "org.eclipse.swt"); //$NON-NLS-1$ assertContainsSymbolicName(captured.getBundles(), "org.eclipse.swt.win32.win32.x86"); //$NON-NLS-1$ diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ActionTest.java index 8a24aea1c..d62123d01 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ActionTest.java @@ -11,21 +11,20 @@ package org.eclipse.equinox.p2.tests.publisher.actions; import static org.easymock.EasyMock.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - - import java.io.*; import java.util.*; import junit.framework.Assert; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil; import org.eclipse.equinox.p2.publisher.*; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; +import org.osgi.framework.Filter; -@SuppressWarnings( {"cast", "restriction", "unchecked"}) +@SuppressWarnings({"cast", "restriction", "unchecked"}) public abstract class ActionTest extends AbstractProvisioningTest { protected static final String COMMA_SEPARATOR = ","; //$NON-NLS-1$ protected static final String JAR = "jar";//$NON-NLS-1$ @@ -57,18 +56,21 @@ public abstract class ActionTest extends AbstractProvisioningTest { return (String[]) result.toArray(new String[result.size()]); } - protected void verifyProvidedCapability(IProvidedCapability[] prov, String namespace, String name, Version version) { - for (int i = 0; i < prov.length; i++) - if (prov[i].getName().equalsIgnoreCase(name) && prov[i].getNamespace().equalsIgnoreCase(namespace) && prov[i].getVersion().equals(version)) + protected void verifyProvidedCapability(Collection prov, String namespace, String name, Version version) { + for (IProvidedCapability pc : prov) { + if (pc.getName().equalsIgnoreCase(name) && pc.getNamespace().equalsIgnoreCase(namespace) && pc.getVersion().equals(version)) return; // pass + } Assert.fail("Missing ProvidedCapability: " + name + version.toString()); //$NON-NLS-1$ } - protected void verifyRequiredCapability(IRequiredCapability[] required, String namespace, String name, VersionRange range) { - for (int i = 0; i < required.length; i++) - if (required[i].getName().equalsIgnoreCase(name) && required[i].getNamespace().equalsIgnoreCase(namespace) && required[i].getRange().equals(range)) + protected void verifyRequiredCapability(Collection requirement, String namespace, String name, VersionRange range) { + for (Iterator iterator = requirement.iterator(); iterator.hasNext();) { + IRequiredCapability required = (IRequiredCapability) iterator.next(); + if (required.getName().equalsIgnoreCase(name) && required.getNamespace().equalsIgnoreCase(namespace) && required.getRange().equals(range)) return; - Assert.fail("Missing RequiredCapability: " + name + range.toString()); //$NON-NLS-1$ + } + Assert.fail("Missing RequiredCapability: " + name + " " + range.toString()); //$NON-NLS-1$ } protected IInstallableUnit mockIU(String id, Version version) { @@ -106,30 +108,28 @@ public abstract class ActionTest extends AbstractProvisioningTest { return map; } - protected void contains(IProvidedCapability[] capabilities, String namespace, String name, Version version) { - for (int i = 0; i < capabilities.length; i++) { - IProvidedCapability capability = capabilities[i]; + protected void contains(Collection capabilities, String namespace, String name, Version version) { + for (IProvidedCapability capability : capabilities) { if (capability.getNamespace().equals(namespace) && capability.getName().equals(name) && capability.getVersion().equals(version)) return; } fail(); } - protected void contains(IRequiredCapability[] capabilities, String namespace, String name, VersionRange range, String filter, boolean optional, boolean multiple) { - for (int i = 0; i < capabilities.length; i++) { - IRequiredCapability capability = capabilities[i]; + protected void contains(Collection capabilities, String namespace, String name, VersionRange range, String filterStr, boolean optional, boolean multiple) { + Filter filter = ExpressionUtil.parseLDAP(filterStr); + for (Iterator iterator = capabilities.iterator(); iterator.hasNext();) { + IRequiredCapability capability = (IRequiredCapability) iterator.next(); if (filter == null) { if (capability.getFilter() != null) continue; } else if (!filter.equals(capability.getFilter())) continue; - if (multiple != capability.isMultiple()) - continue; if (!name.equals(capability.getName())) continue; if (!namespace.equals(capability.getNamespace())) continue; - if (optional != capability.isOptional()) + if (optional != (capability.getMin() == 0)) continue; if (!range.equals(capability.getRange())) continue; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AdviceFileParserTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AdviceFileParserTest.java index 0283414ad..538fcee07 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AdviceFileParserTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AdviceFileParserTest.java @@ -10,18 +10,21 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.publisher.actions; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.util.*; import junit.framework.TestCase; +import org.eclipse.equinox.internal.p2.metadata.RequiredCapability; import org.eclipse.equinox.internal.provisional.p2.metadata.*; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.FragmentQuery; import org.eclipse.equinox.p2.publisher.eclipse.AdviceFileParser; public class AdviceFileParserTest extends TestCase { public void testNoAdvice() { - AdviceFileParser parser = new AdviceFileParser("id", Version.MIN_VERSION, Collections.EMPTY_MAP); + AdviceFileParser parser = new AdviceFileParser("id", Version.emptyVersion, Collections.EMPTY_MAP); parser.parse(); assertNull(parser.getAdditionalInstallableUnitDescriptions()); assertNull(parser.getProperties()); @@ -33,11 +36,11 @@ public class AdviceFileParserTest extends TestCase { public void testAdviceVersion() { Map map = new HashMap(); map.put("advice.version", "1.0"); - AdviceFileParser parser = new AdviceFileParser("id", Version.MIN_VERSION, map); + AdviceFileParser parser = new AdviceFileParser("id", Version.emptyVersion, map); parser.parse(); map.put("advice.version", "999"); - parser = new AdviceFileParser("id", Version.MIN_VERSION, map); + parser = new AdviceFileParser("id", Version.emptyVersion, map); try { parser.parse(); } catch (IllegalStateException e) { @@ -53,10 +56,10 @@ public class AdviceFileParserTest extends TestCase { map.put("properties.1.name", "testName2"); map.put("properties.1.value", "testValue2"); - AdviceFileParser parser = new AdviceFileParser("id", Version.MIN_VERSION, map); + AdviceFileParser parser = new AdviceFileParser("id", Version.emptyVersion, map); parser.parse(); - assertEquals("testValue1", parser.getProperties().getProperty("testName1")); - assertEquals("testValue2", parser.getProperties().getProperty("testName2")); + assertEquals("testValue1", parser.getProperties().get("testName1")); + assertEquals("testValue2", parser.getProperties().get("testName2")); } public void testProvidesAdvice() { @@ -65,28 +68,28 @@ public class AdviceFileParserTest extends TestCase { map.put("provides.0.name", "testName1"); map.put("provides.0.version", "1.2.3.$qualifier$"); - AdviceFileParser parser = new AdviceFileParser("id", new Version("1.0.0.v20090909"), map); + AdviceFileParser parser = new AdviceFileParser("id", Version.create("1.0.0.v20090909"), map); parser.parse(); IProvidedCapability[] capabilities = parser.getProvidedCapabilities(); assertEquals(1, capabilities.length); assertEquals("testNamespace1", capabilities[0].getNamespace()); assertEquals("testName1", capabilities[0].getName()); - assertEquals(new Version("1.2.3.v20090909"), capabilities[0].getVersion()); + assertEquals(Version.create("1.2.3.v20090909"), capabilities[0].getVersion()); map.put("provides.1.namespace", "testNamespace2"); map.put("provides.1.name", "testName2"); map.put("provides.1.version", "$version$"); - parser = new AdviceFileParser("id", Version.MIN_VERSION, map); + parser = new AdviceFileParser("id", Version.emptyVersion, map); parser.parse(); capabilities = parser.getProvidedCapabilities(); assertEquals(2, capabilities.length); assertEquals("testNamespace1", capabilities[0].getNamespace()); assertEquals("testName1", capabilities[0].getName()); - assertEquals(new Version("1.2.3"), capabilities[0].getVersion()); + assertEquals(Version.create("1.2.3"), capabilities[0].getVersion()); assertEquals("testNamespace2", capabilities[1].getNamespace()); assertEquals("testName2", capabilities[1].getName()); - assertEquals(Version.MIN_VERSION, capabilities[1].getVersion()); + assertEquals(Version.emptyVersion, capabilities[1].getVersion()); } public void testRequiresAdvice() { @@ -98,13 +101,13 @@ public class AdviceFileParserTest extends TestCase { map.put("requires.0.optional", Boolean.TRUE.toString()); map.put("requires.0.multiple", Boolean.TRUE.toString()); - AdviceFileParser parser = new AdviceFileParser("id", new Version("1.0.0.v20090909"), map); + AdviceFileParser parser = new AdviceFileParser("id", Version.create("1.0.0.v20090909"), map); parser.parse(); - IRequiredCapability[] capabilities = parser.getRequiredCapabilities(); - assertEquals(1, capabilities.length); - assertEquals("testNamespace1", capabilities[0].getNamespace()); - assertEquals("testName1", capabilities[0].getName()); - assertEquals(new VersionRange("[1.2.3.v20090909, 2)"), capabilities[0].getRange()); + IRequirement[] reqs = parser.getRequiredCapabilities(); + assertEquals(1, reqs.length); + assertEquals("testNamespace1", RequiredCapability.extractNamespace(reqs[0].getMatches())); + assertEquals("testName1", RequiredCapability.extractName(reqs[0].getMatches())); + assertEquals(new VersionRange("[1.2.3.v20090909, 2)"), RequiredCapability.extractRange(reqs[0].getMatches())); map.put("requires.1.namespace", "testNamespace2"); map.put("requires.1.name", "testName2"); @@ -114,22 +117,20 @@ public class AdviceFileParserTest extends TestCase { //default // map.put("requires.1.multiple", Boolean.FALSE.toString()); - parser = new AdviceFileParser("id", Version.MIN_VERSION, map); + parser = new AdviceFileParser("id", Version.emptyVersion, map); parser.parse(); - capabilities = parser.getRequiredCapabilities(); - assertEquals(2, capabilities.length); - assertEquals("testNamespace1", capabilities[0].getNamespace()); - assertEquals("testName1", capabilities[0].getName()); - assertEquals(new VersionRange("[1.2.3, 2)"), capabilities[0].getRange()); - assertEquals(true, capabilities[0].isGreedy()); - assertEquals(true, capabilities[0].isOptional()); - assertEquals(true, capabilities[0].isMultiple()); - assertEquals("testNamespace2", capabilities[1].getNamespace()); - assertEquals("testName2", capabilities[1].getName()); - assertEquals(new VersionRange(Version.MIN_VERSION.toString()), capabilities[1].getRange()); - assertEquals(false, capabilities[1].isGreedy()); - assertEquals(false, capabilities[1].isOptional()); - assertEquals(false, capabilities[1].isMultiple()); + reqs = parser.getRequiredCapabilities(); + assertEquals(2, reqs.length); + assertEquals("testNamespace1", RequiredCapability.extractNamespace(reqs[0].getMatches())); + assertEquals("testName1", RequiredCapability.extractName(reqs[0].getMatches())); + assertEquals(new VersionRange("[1.2.3, 2)"), RequiredCapability.extractRange(reqs[0].getMatches())); + assertEquals(true, reqs[0].isGreedy()); + assertEquals(0, reqs[0].getMin()); + assertEquals("testNamespace2", RequiredCapability.extractNamespace(reqs[1].getMatches())); + assertEquals("testName2", RequiredCapability.extractName(reqs[1].getMatches())); + assertEquals(new VersionRange(Version.emptyVersion.toString()), RequiredCapability.extractRange(reqs[1].getMatches())); + assertEquals(false, reqs[1].isGreedy()); + assertEquals(1, reqs[1].getMin()); } public void testMetaRequiresAdvice() { @@ -141,13 +142,13 @@ public class AdviceFileParserTest extends TestCase { map.put("metaRequirements.0.optional", Boolean.TRUE.toString()); map.put("metaRequirements.0.multiple", Boolean.TRUE.toString()); - AdviceFileParser parser = new AdviceFileParser("id", new Version("1.0.0.v20090909"), map); + AdviceFileParser parser = new AdviceFileParser("id", Version.create("1.0.0.v20090909"), map); parser.parse(); - IRequiredCapability[] capabilities = parser.getMetaRequiredCapabilities(); - assertEquals(1, capabilities.length); - assertEquals("testNamespace1", capabilities[0].getNamespace()); - assertEquals("testName1", capabilities[0].getName()); - assertEquals(new VersionRange("[1.2.3.v20090909, 2)"), capabilities[0].getRange()); + IRequirement[] reqs = parser.getMetaRequiredCapabilities(); + assertEquals(1, reqs.length); + assertEquals("testNamespace1", RequiredCapability.extractNamespace(reqs[0].getMatches())); + assertEquals("testName1", RequiredCapability.extractName(reqs[0].getMatches())); + assertEquals(new VersionRange("[1.2.3.v20090909, 2)"), RequiredCapability.extractRange(reqs[0].getMatches())); map.put("metaRequirements.1.namespace", "testNamespace2"); map.put("metaRequirements.1.name", "testName2"); @@ -157,22 +158,20 @@ public class AdviceFileParserTest extends TestCase { //default // map.put("requires.1.multiple", Boolean.FALSE.toString()); - parser = new AdviceFileParser("id", Version.MIN_VERSION, map); + parser = new AdviceFileParser("id", Version.emptyVersion, map); parser.parse(); - capabilities = parser.getMetaRequiredCapabilities(); - assertEquals(2, capabilities.length); - assertEquals("testNamespace1", capabilities[0].getNamespace()); - assertEquals("testName1", capabilities[0].getName()); - assertEquals(new VersionRange("[1.2.3, 2)"), capabilities[0].getRange()); - assertEquals(true, capabilities[0].isGreedy()); - assertEquals(true, capabilities[0].isOptional()); - assertEquals(true, capabilities[0].isMultiple()); - assertEquals("testNamespace2", capabilities[1].getNamespace()); - assertEquals("testName2", capabilities[1].getName()); - assertEquals(new VersionRange(Version.MIN_VERSION.toString()), capabilities[1].getRange()); - assertEquals(false, capabilities[1].isGreedy()); - assertEquals(false, capabilities[1].isOptional()); - assertEquals(false, capabilities[1].isMultiple()); + reqs = parser.getMetaRequiredCapabilities(); + assertEquals(2, reqs.length); + assertEquals("testNamespace1", RequiredCapability.extractNamespace(reqs[0].getMatches())); + assertEquals("testName1", RequiredCapability.extractName(reqs[0].getMatches())); + assertEquals(new VersionRange("[1.2.3, 2)"), RequiredCapability.extractRange(reqs[0].getMatches())); + assertEquals(true, reqs[0].isGreedy()); + assertEquals(0, reqs[0].getMin()); + assertEquals("testNamespace2", RequiredCapability.extractNamespace(reqs[1].getMatches())); + assertEquals("testName2", RequiredCapability.extractName(reqs[1].getMatches())); + assertEquals(new VersionRange(Version.emptyVersion.toString()), RequiredCapability.extractRange(reqs[1].getMatches())); + assertEquals(false, reqs[1].isGreedy()); + assertEquals(1, reqs[1].getMin()); } public void testInstructionsAdvice() { @@ -182,7 +181,7 @@ public class AdviceFileParserTest extends TestCase { map.put("instructions.unconfigure", "removeProgramArg(programArg:-startup); removeProgramArg(programArg:@artifact);)"); map.put("instructions.unconfigure.import", "some.removeProgramArg"); - AdviceFileParser parser = new AdviceFileParser("id", Version.MIN_VERSION, map); + AdviceFileParser parser = new AdviceFileParser("id", Version.emptyVersion, map); parser.parse(); ITouchpointInstruction configure = (ITouchpointInstruction) parser.getTouchpointInstructions().get("configure"); assertEquals(null, configure.getImportAttribute()); @@ -203,7 +202,7 @@ public class AdviceFileParserTest extends TestCase { map.put("units.1.singleton", "true"); map.put("units.1.copyright", "testCopyright"); map.put("units.1.copyright.location", "http://localhost/test"); - map.put("units.1.filter", "test=testFilter"); + map.put("units.1.filter", "(test=testFilter)"); map.put("units.1.touchpoint.id", "testTouchpointId"); map.put("units.1.touchpoint.version", "1.2.5"); map.put("units.1.update.id", "testid1"); @@ -266,114 +265,120 @@ public class AdviceFileParserTest extends TestCase { map.put("units.1.hostRequirements.1.greedy", Boolean.FALSE.toString()); map.put("units.1.hostRequirements.1.optional", Boolean.FALSE.toString()); - AdviceFileParser parser = new AdviceFileParser("id", Version.MIN_VERSION, map); + AdviceFileParser parser = new AdviceFileParser("id", Version.emptyVersion, map); parser.parse(); InstallableUnitDescription[] descriptions = parser.getAdditionalInstallableUnitDescriptions(); IInstallableUnit iu0 = MetadataFactory.createInstallableUnit(descriptions[0]); assertEquals("testid0", iu0.getId()); - assertEquals(new Version("1.2.3"), iu0.getVersion()); + assertEquals(Version.create("1.2.3"), iu0.getVersion()); assertFalse(iu0.isSingleton()); - assertFalse(iu0.isFragment()); - assertEquals(0, iu0.getArtifacts().length); + assertFalse(FragmentQuery.isFragment(iu0)); + assertEquals(0, iu0.getArtifacts().size()); assertEquals(null, iu0.getCopyright()); assertEquals(null, iu0.getFilter()); - assertEquals(null, iu0.getLicense()); + assertEquals(0, iu0.getLicenses().size()); assertEquals(0, iu0.getProperties().size()); - assertEquals(0, iu0.getRequiredCapabilities().length); - assertEquals(0, iu0.getProvidedCapabilities().length); - assertEquals(0, iu0.getMetaRequiredCapabilities().length); - assertEquals(0, iu0.getTouchpointData().length); + assertEquals(0, iu0.getRequiredCapabilities().size()); + assertEquals(0, iu0.getProvidedCapabilities().size()); + assertEquals(0, iu0.getMetaRequiredCapabilities().size()); + assertEquals(0, iu0.getTouchpointData().size()); assertEquals(ITouchpointType.NONE, iu0.getTouchpointType()); assertEquals(null, iu0.getUpdateDescriptor()); IInstallableUnit iu1 = MetadataFactory.createInstallableUnit(descriptions[1]); assertEquals("testid1", iu1.getId()); - assertEquals(new Version("1.2.4"), iu1.getVersion()); + assertEquals(Version.create("1.2.4"), iu1.getVersion()); assertTrue(iu1.isSingleton()); - assertEquals(2, iu1.getArtifacts().length); - assertEquals("testArtifact1", iu1.getArtifacts()[0].getId()); - assertEquals(new Version("1.2.6"), iu1.getArtifacts()[0].getVersion()); - assertEquals("testClassifier1", iu1.getArtifacts()[0].getClassifier()); - assertEquals("testArtifact2", iu1.getArtifacts()[1].getId()); - assertEquals(new Version("1.2.7"), iu1.getArtifacts()[1].getVersion()); - assertEquals("testClassifier2", iu1.getArtifacts()[1].getClassifier()); + assertEquals(2, iu1.getArtifacts().size()); + Iterator it = iu1.getArtifacts().iterator(); + IArtifactKey key0 = (IArtifactKey) it.next(); + IArtifactKey key1 = (IArtifactKey) it.next(); + assertEquals("testArtifact1", key0.getId()); + assertEquals(Version.create("1.2.6"), key0.getVersion()); + assertEquals("testClassifier1", key0.getClassifier()); + assertEquals("testArtifact2", key1.getId()); + assertEquals(Version.create("1.2.7"), key1.getVersion()); + assertEquals("testClassifier2", key1.getClassifier()); assertEquals("testCopyright", iu1.getCopyright().getBody()); assertEquals("http://localhost/test", iu1.getCopyright().getLocation().toString()); - assertEquals("test=testFilter", iu1.getFilter()); - assertEquals("testLicense", iu1.getLicense().getBody()); - assertEquals("http://localhost/license", iu1.getLicense().getLocation().toString()); + assertEquals("(test=testFilter)", iu1.getFilter().toString()); + assertEquals("testLicense", iu1.getLicenses().iterator().next().getBody()); + assertEquals("http://localhost/license", iu1.getLicenses().iterator().next().getLocation().toString()); assertEquals("testValue1", iu1.getProperty("testName1")); assertEquals("testValue2", iu1.getProperty("testName2")); - IRequiredCapability[] required = iu1.getRequiredCapabilities(); - assertEquals(2, required.length); - assertEquals("testNamespace1", required[0].getNamespace()); - assertEquals("testName1", required[0].getName()); - assertEquals(new VersionRange("[1.2.3, 2)"), required[0].getRange()); - assertEquals(true, required[0].isGreedy()); - assertEquals(true, required[0].isOptional()); - assertEquals(true, required[0].isMultiple()); - assertEquals("testNamespace2", required[1].getNamespace()); - assertEquals("testName2", required[1].getName()); - assertEquals(new VersionRange(Version.MIN_VERSION.toString()), required[1].getRange()); - assertEquals(false, required[1].isGreedy()); - assertEquals(false, required[1].isOptional()); - assertEquals(false, required[1].isMultiple()); - - IProvidedCapability[] provided = iu1.getProvidedCapabilities(); - assertEquals(2, provided.length); - assertEquals("testNamespace1", provided[0].getNamespace()); - assertEquals("testName1", provided[0].getName()); - assertEquals(new Version("1.2.3"), provided[0].getVersion()); - assertEquals("testNamespace2", provided[1].getNamespace()); - assertEquals("testName2", provided[1].getName()); - assertEquals(Version.MIN_VERSION, provided[1].getVersion()); - - IRequiredCapability[] metarequirements = iu1.getMetaRequiredCapabilities(); - assertEquals(2, metarequirements.length); - assertEquals("testNamespace1", metarequirements[0].getNamespace()); - assertEquals("testName1", metarequirements[0].getName()); - assertEquals(new VersionRange("[1.2.3, 2)"), metarequirements[0].getRange()); - assertEquals(true, metarequirements[0].isGreedy()); - assertEquals(true, metarequirements[0].isOptional()); - assertEquals(true, metarequirements[0].isMultiple()); - assertEquals("testNamespace2", metarequirements[1].getNamespace()); - assertEquals("testName2", metarequirements[1].getName()); - assertEquals(new VersionRange(Version.MIN_VERSION.toString()), metarequirements[1].getRange()); - assertEquals(false, metarequirements[1].isGreedy()); - assertEquals(false, metarequirements[1].isOptional()); - assertEquals(false, metarequirements[1].isMultiple()); - - assertEquals(1, iu1.getTouchpointData().length); - ITouchpointInstruction configure = iu1.getTouchpointData()[0].getInstruction("configure"); + Collection reqs = iu1.getRequiredCapabilities(); + Iterator it2 = reqs.iterator(); + IRequirement req0 = (IRequirement) it2.next(); + IRequirement req1 = (IRequirement) it2.next(); + assertEquals(2, reqs.size()); + assertEquals("testNamespace1", RequiredCapability.extractNamespace(req0.getMatches())); + assertEquals("testName1", RequiredCapability.extractName(req0.getMatches())); + assertEquals(new VersionRange("[1.2.3, 2)"), RequiredCapability.extractRange(req0.getMatches())); + assertEquals(true, req0.isGreedy()); + assertEquals(0, req0.getMin()); + assertEquals("testNamespace2", RequiredCapability.extractNamespace(req1.getMatches())); + assertEquals("testName2", RequiredCapability.extractName(req1.getMatches())); + assertEquals(new VersionRange(Version.emptyVersion.toString()), RequiredCapability.extractRange(req1.getMatches())); + assertEquals(false, req1.isGreedy()); + assertEquals(1, req1.getMin()); + + Collection provided = iu1.getProvidedCapabilities(); + Iterator it4 = provided.iterator(); + IProvidedCapability cap1 = it4.next(); + IProvidedCapability cap2 = it4.next(); + assertEquals(2, provided.size()); + assertEquals("testNamespace1", cap1.getNamespace()); + assertEquals("testName1", cap1.getName()); + assertEquals(Version.create("1.2.3"), cap1.getVersion()); + assertEquals("testNamespace2", cap2.getNamespace()); + assertEquals("testName2", cap2.getName()); + assertEquals(Version.emptyVersion, cap2.getVersion()); + + Collection metarequirements = iu1.getMetaRequiredCapabilities(); + assertEquals(2, metarequirements.size()); + Iterator it3 = metarequirements.iterator(); + IRequirement metaReq0 = (IRequirement) it3.next(); + IRequirement metaReq1 = (IRequirement) it3.next(); + + assertEquals("testNamespace1", RequiredCapability.extractNamespace(metaReq0.getMatches())); + assertEquals("testName1", RequiredCapability.extractName(metaReq0.getMatches())); + assertEquals(new VersionRange("[1.2.3, 2)"), RequiredCapability.extractRange(metaReq0.getMatches())); + assertEquals(true, metaReq0.isGreedy()); + assertEquals(0, metaReq0.getMin()); + assertEquals("testNamespace2", RequiredCapability.extractNamespace(metaReq1.getMatches())); + assertEquals("testName2", RequiredCapability.extractName(metaReq1.getMatches())); + assertEquals(new VersionRange(Version.emptyVersion.toString()), RequiredCapability.extractRange(metaReq1.getMatches())); + assertEquals(false, metaReq1.isGreedy()); + assertEquals(1, metaReq1.getMin()); + + assertEquals(1, iu1.getTouchpointData().size()); + ITouchpointInstruction configure = iu1.getTouchpointData().get(0).getInstruction("configure"); assertEquals(null, configure.getImportAttribute()); assertEquals("addProgramArg(programArg:-startup); addProgramArg(programArg:@artifact);", configure.getBody()); - ITouchpointInstruction unconfigure = iu1.getTouchpointData()[0].getInstruction("unconfigure"); + ITouchpointInstruction unconfigure = iu1.getTouchpointData().get(0).getInstruction("unconfigure"); assertEquals("some.removeProgramArg", unconfigure.getImportAttribute()); assertEquals("removeProgramArg(programArg:-startup); removeProgramArg(programArg:@artifact);)", unconfigure.getBody()); - assertEquals(MetadataFactory.createTouchpointType("testTouchpointId", new Version("1.2.5")), iu1.getTouchpointType()); + assertEquals(MetadataFactory.createTouchpointType("testTouchpointId", Version.create("1.2.5")), iu1.getTouchpointType()); assertEquals("testid1", iu1.getUpdateDescriptor().getId()); assertEquals(new VersionRange("(1,2)"), iu1.getUpdateDescriptor().getRange()); assertEquals(2, iu1.getUpdateDescriptor().getSeverity()); assertEquals("some description", iu1.getUpdateDescriptor().getDescription()); - assertTrue(iu1.isFragment()); - IRequiredCapability[] hostRequired = ((IInstallableUnitFragment) iu1).getHost(); + assertTrue(FragmentQuery.isFragment(iu1)); + IRequirement[] hostRequired = ((IInstallableUnitFragment) iu1).getHost(); assertEquals(2, hostRequired.length); - assertEquals("testNamespace1", hostRequired[0].getNamespace()); - assertEquals("testName1", hostRequired[0].getName()); - assertEquals(new VersionRange("[1.2.3, 2)"), hostRequired[0].getRange()); + assertEquals("testNamespace1", RequiredCapability.extractNamespace(hostRequired[0].getMatches())); + assertEquals("testName1", RequiredCapability.extractName(hostRequired[0].getMatches())); + assertEquals(new VersionRange("[1.2.3, 2)"), RequiredCapability.extractRange(hostRequired[0].getMatches())); assertEquals(true, hostRequired[0].isGreedy()); - assertEquals(true, hostRequired[0].isOptional()); - assertEquals(true, hostRequired[0].isMultiple()); - assertEquals("testNamespace2", hostRequired[1].getNamespace()); - assertEquals("testName2", hostRequired[1].getName()); - assertEquals(new VersionRange(Version.MIN_VERSION.toString()), hostRequired[1].getRange()); + assertEquals(0, hostRequired[0].getMin()); + assertEquals("testNamespace2", RequiredCapability.extractNamespace(hostRequired[1].getMatches())); + assertEquals("testName2", RequiredCapability.extractName(hostRequired[1].getMatches())); + assertEquals(new VersionRange(Version.emptyVersion.toString()), RequiredCapability.extractRange(hostRequired[1].getMatches())); assertEquals(false, hostRequired[1].isGreedy()); - assertEquals(false, hostRequired[1].isOptional()); - assertEquals(false, hostRequired[1].isMultiple()); + assertEquals(1, hostRequired[1].getMin()); } - } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AdviceMatcher.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AdviceMatcher.java index bf95d1f99..b99d3c3d8 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AdviceMatcher.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/AdviceMatcher.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.publisher.actions; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import org.easymock.EasyMock; import org.easymock.IArgumentMatcher; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/BundlesActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/BundlesActionTest.java index 327656ad1..6017d4130 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/BundlesActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/BundlesActionTest.java @@ -12,9 +12,8 @@ package org.eclipse.equinox.p2.tests.publisher.actions; import static org.easymock.EasyMock.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.io.*; import java.util.*; @@ -23,20 +22,22 @@ import org.easymock.EasyMock; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.director.QueryableArray; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.p2.metadata.TranslationSupport; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.publisher.*; import org.eclipse.equinox.p2.publisher.actions.*; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; import org.eclipse.equinox.p2.publisher.eclipse.IBundleShapeAdvice; -import org.eclipse.equinox.p2.tests.*; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.tests.TestActivator; +import org.eclipse.equinox.p2.tests.TestData; import org.eclipse.equinox.p2.tests.publisher.TestArtifactRepository; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; -@SuppressWarnings( {"restriction", "unchecked"}) +@SuppressWarnings({"unchecked"}) public class BundlesActionTest extends ActionTest { private static final String OSGI = PublisherHelper.OSGI_BUNDLE_CLASSIFIER; private static final String JAVA_PACKAGE = "java.package";//$NON-NLS-1$ @@ -67,16 +68,16 @@ public class BundlesActionTest extends ActionTest { private static final String TEST2_PROVX_NAMESPACE = JAVA_PACKAGE; private static final String TEST1_PROVZ_NAMESPACE = JAVA_PACKAGE; - private final Version BUNDLE1_VERSION = new Version("0.1.0");//$NON-NLS-1$ - private final Version BUNDLE2_VERSION = new Version("1.0.0.qualifier");//$NON-NLS-1$ + private final Version BUNDLE1_VERSION = Version.create("0.1.0");//$NON-NLS-1$ + private final Version BUNDLE2_VERSION = Version.create("1.0.0.qualifier");//$NON-NLS-1$ private final Version PROVBUNDLE2_VERSION = BUNDLE2_VERSION; private final Version TEST2_PROVZ_VERSION = Version.emptyVersion; private final Version TEST2_PROVY_VERSION = Version.emptyVersion; private final Version TEST2_PROVX_VERSION = Version.emptyVersion; private final VersionRange TEST2_IUA_VERSION_RANGE = VersionRange.emptyRange; private final VersionRange TEST2_IUB_VERSION_RANGE = VersionRange.emptyRange; - private final VersionRange TEST2_IUC_VERSION_RANGE = new VersionRange(new Version("1.0.0"), true, new Version(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE), true);//$NON-NLS-1$ - private final VersionRange TEST1_IUD_VERSION_RANGE = new VersionRange(new Version("1.3.0"), true, new Version(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE), true);//$NON-NLS-1$ + private final VersionRange TEST2_IUC_VERSION_RANGE = new VersionRange(Version.create("1.0.0"), true, Version.MAX_VERSION, true);//$NON-NLS-1$ + private final VersionRange TEST1_IUD_VERSION_RANGE = new VersionRange(Version.create("1.3.0"), true, Version.MAX_VERSION, true);//$NON-NLS-1$ protected TestArtifactRepository artifactRepository = new TestArtifactRepository(); @@ -120,22 +121,23 @@ public class BundlesActionTest extends ActionTest { ius = results.getIUs(null, null); assertEquals("2.0", 1, ius.size()); QueryableArray queryableArray = new QueryableArray((IInstallableUnit[]) ius.toArray(new IInstallableUnit[ius.size()])); - Collector result = queryableArray.query(new InstallableUnitQuery("foo"), new Collector(), null); - assertEquals("3.1", 1, result.size()); + IQueryResult result = queryableArray.query(new InstallableUnitQuery("foo"), null); + assertEquals("3.1", 1, queryResultSize(result)); IInstallableUnit iu = (IInstallableUnit) result.iterator().next(); - IUPropertyUtils iuPropertyUtils = new IUPropertyUtils(queryableArray); - assertEquals("3.2", "English Foo", iuPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_NAME)); + TranslationSupport utils = new TranslationSupport(); + utils.setTranslationSource(queryableArray); + assertEquals("3.2", "English Foo", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME)); bundlesAction = new BundlesAction(new File[] {foo_fragment}); bundlesAction.perform(info, results, new NullProgressMonitor()); ius = results.getIUs(null, null); assertEquals("2.0", 3, ius.size()); queryableArray = new QueryableArray((IInstallableUnit[]) ius.toArray(new IInstallableUnit[ius.size()])); - result = queryableArray.query(new InstallableUnitQuery("foo"), new Collector(), null); - assertEquals("2.1", 1, result.size()); + result = queryableArray.query(new InstallableUnitQuery("foo"), null); + assertEquals("2.1", 1, queryResultSize(result)); iu = (IInstallableUnit) result.iterator().next(); - iuPropertyUtils = new IUPropertyUtils(queryableArray); - assertEquals("2.2", "German Foo", iuPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN)); + utils.setTranslationSource(queryableArray); + assertEquals("2.2", "German Foo", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN.toString())); } private void verifyBundlesAction() throws Exception { @@ -155,7 +157,7 @@ public class BundlesActionTest extends ActionTest { int packedIdx; int canonicalIdx; - if ("packed".equals(descriptors[0].getProperty(IArtifactDescriptor.FORMAT))) { + if (IArtifactDescriptor.FORMAT_PACKED.equals(descriptors[0].getProperty(IArtifactDescriptor.FORMAT))) { packedIdx = 0; canonicalIdx = 1; } else { @@ -190,22 +192,22 @@ public class BundlesActionTest extends ActionTest { assertEquals("1.1", bundle1IU.getVersion(), BUNDLE1_VERSION); // check required capabilities - IRequiredCapability[] requiredCapability = bundle1IU.getRequiredCapabilities(); + Collection requiredCapability = bundle1IU.getRequiredCapabilities(); verifyRequiredCapability(requiredCapability, TEST1_IUD_NAMESPACE, TEST1_IUD_NAME, TEST1_IUD_VERSION_RANGE); - assertEquals("2.0", 1, requiredCapability.length); + assertEquals("2.0", 1, requiredCapability.size()); // check provided capabilities - IProvidedCapability[] providedCapabilities = bundle1IU.getProvidedCapabilities(); + Collection providedCapabilities = bundle1IU.getProvidedCapabilities(); verifyProvidedCapability(providedCapabilities, PROVBUNDLE_NAMESPACE, TEST1_PROVBUNDLE_NAME, BUNDLE1_VERSION); verifyProvidedCapability(providedCapabilities, OSGI, TEST1_PROVBUNDLE_NAME, BUNDLE1_VERSION); verifyProvidedCapability(providedCapabilities, TEST1_PROVZ_NAMESPACE, TEST1_PROVZ_NAME, TEST2_PROVZ_VERSION); - verifyProvidedCapability(providedCapabilities, PublisherHelper.NAMESPACE_ECLIPSE_TYPE, "source", new Version("1.0.0"));//$NON-NLS-1$//$NON-NLS-2$ - assertEquals("2.1", 4, providedCapabilities.length); + verifyProvidedCapability(providedCapabilities, PublisherHelper.NAMESPACE_ECLIPSE_TYPE, "source", Version.create("1.0.0"));//$NON-NLS-1$//$NON-NLS-2$ + assertEquals("2.1", 4, providedCapabilities.size()); - ITouchpointData[] data = bundle1IU.getTouchpointData(); + List data = bundle1IU.getTouchpointData(); boolean found = false; - for (int i = 0; i < data.length; i++) { - ITouchpointInstruction configure = data[i].getInstruction("configure"); + for (int i = 0; i < data.size(); i++) { + ITouchpointInstruction configure = data.get(i).getInstruction("configure"); if (configure == null) continue; String body = configure.getBody(); @@ -225,31 +227,31 @@ public class BundlesActionTest extends ActionTest { assertEquals(bundle2IU.getVersion(), BUNDLE2_VERSION); // check required capabilities - IRequiredCapability[] requiredCapabilities = bundle2IU.getRequiredCapabilities(); + Collection requiredCapabilities = bundle2IU.getRequiredCapabilities(); verifyRequiredCapability(requiredCapabilities, TEST2_IUA_NAMESPACE, TEST2_REQA_NAME, TEST2_IUA_VERSION_RANGE); verifyRequiredCapability(requiredCapabilities, TEST2_IUB_NAMESPACE, TEST2_REQB_NAME, TEST2_IUB_VERSION_RANGE); verifyRequiredCapability(requiredCapabilities, TEST2_IUC_NAMESPACE, TEST2_REQC_NAME, TEST2_IUC_VERSION_RANGE); - assertTrue(requiredCapabilities.length == 3 /*number of tested elements*/); + assertTrue(requiredCapabilities.size() == 3 /*number of tested elements*/); // check provided capabilities - IProvidedCapability[] providedCapabilities = bundle2IU.getProvidedCapabilities(); + Collection providedCapabilities = bundle2IU.getProvidedCapabilities(); verifyProvidedCapability(providedCapabilities, PROVBUNDLE_NAMESPACE, TEST2_PROVBUNDLE_NAME, PROVBUNDLE2_VERSION); verifyProvidedCapability(providedCapabilities, OSGI, TEST2_PROVBUNDLE_NAME, BUNDLE2_VERSION); verifyProvidedCapability(providedCapabilities, TEST2_PROVZ_NAMESPACE, TEST2_PROVZ_NAME, TEST2_PROVZ_VERSION); verifyProvidedCapability(providedCapabilities, TEST2_PROVY_NAMESPACE, TEST2_PROVY_NAME, TEST2_PROVY_VERSION); verifyProvidedCapability(providedCapabilities, TEST2_PROVX_NAMESPACE, TEST2_PROVX_NAME, TEST2_PROVX_VERSION); - verifyProvidedCapability(providedCapabilities, PublisherHelper.NAMESPACE_ECLIPSE_TYPE, "bundle", new Version("1.0.0"));//$NON-NLS-1$//$NON-NLS-2$ - assertTrue(providedCapabilities.length == 6 /*number of tested elements*/); + verifyProvidedCapability(providedCapabilities, PublisherHelper.NAMESPACE_ECLIPSE_TYPE, "bundle", Version.create("1.0.0"));//$NON-NLS-1$//$NON-NLS-2$ + assertTrue(providedCapabilities.size() == 6 /*number of tested elements*/); // check %bundle name is correct Map prop = bundle2IU.getProperties(); assertTrue(prop.get("org.eclipse.equinox.p2.name").toString().equalsIgnoreCase("%bundleName"));//$NON-NLS-1$//$NON-NLS-2$ assertTrue(prop.get("org.eclipse.equinox.p2.provider").toString().equalsIgnoreCase("%providerName"));//$NON-NLS-1$//$NON-NLS-2$ - ITouchpointData[] data = bundle2IU.getTouchpointData(); + List data = bundle2IU.getTouchpointData(); boolean found = false; - for (int i = 0; i < data.length; i++) { - ITouchpointInstruction configure = data[i].getInstruction("configure"); + for (int i = 0; i < data.size(); i++) { + ITouchpointInstruction configure = data.get(i).getInstruction("configure"); if (configure == null) continue; String body = configure.getBody(); @@ -272,11 +274,11 @@ public class BundlesActionTest extends ActionTest { protected void insertPublisherInfoBehavior() { //super sets publisherInfo.getMetadataRepository and publisherInfo.getContextMetadataRepository super.insertPublisherInfoBehavior(); - Properties sarProperties = new Properties(); + Map sarProperties = new HashMap(); sarProperties.put("key1", "value1");//$NON-NLS-1$//$NON-NLS-2$ sarProperties.put("key2", "value2");//$NON-NLS-1$//$NON-NLS-2$ - Properties sdkProperties = new Properties(); + Map sdkProperties = new HashMap(); sdkProperties.put("key1", "value1");//$NON-NLS-1$//$NON-NLS-2$ sdkProperties.put("key2", "value2");//$NON-NLS-1$//$NON-NLS-2$ diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ConfigCUsActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ConfigCUsActionTest.java index cf28eb389..9c896acdf 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ConfigCUsActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ConfigCUsActionTest.java @@ -12,30 +12,27 @@ package org.eclipse.equinox.p2.tests.publisher.actions; import static org.easymock.EasyMock.expect; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - - import java.io.File; -import java.util.ArrayList; +import java.util.*; import org.easymock.EasyMock; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.metadata.InstallableUnit; import org.eclipse.equinox.internal.p2.publisher.eclipse.DataLoader; import org.eclipse.equinox.internal.provisional.frameworkadmin.ConfigData; import org.eclipse.equinox.internal.provisional.frameworkadmin.LauncherData; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil; import org.eclipse.equinox.p2.publisher.IPublisherResult; import org.eclipse.equinox.p2.publisher.eclipse.*; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.TestActivator; import org.eclipse.equinox.p2.tests.TestMetadataRepository; -@SuppressWarnings( {"unchecked", "restriction"}) +@SuppressWarnings({"unchecked", "restriction"}) public class ConfigCUsActionTest extends ActionTest { private static File configLocation = new File(TestActivator.getTestDataFolder(), "ConfigCUsActionTest/level1/level2/config.ini"); //$NON-NLS-1$ private static File executableLocation = new File(TestActivator.getTestDataFolder(), "ConfigCUsActionTest/level1/run.exe"); //$NON-NLS-1$ - private static Version version = new Version("1.0.0"); //$NON-NLS-1$ + private static Version version = Version.create("1.0.0"); //$NON-NLS-1$ private static String id = "id"; //$NON-NLS-1$ private static String flavor = "tooling"; //$NON-NLS-1$ private IMetadataRepository metadataRepo; @@ -60,16 +57,16 @@ public class ConfigCUsActionTest extends ActionTest { assertTrue(iu.getId().equalsIgnoreCase(flavor + id + ".configuration")); //$NON-NLS-1$ //verify ProvidedCapabilities - IProvidedCapability[] providedCapabilities = iu.getProvidedCapabilities(); + Collection providedCapabilities = iu.getProvidedCapabilities(); verifyProvidedCapability(providedCapabilities, "org.eclipse.equinox.p2.iu", iu.getId(), version); //$NON-NLS-1$ // verifyProvidedCapability(providedCapabilities, flavor + id, id + ".config", version); //$NON-NLS-1$ - assertTrue(providedCapabilities.length == 1); + assertTrue(providedCapabilities.size() == 1); //verify RequiredCapabilities - IRequiredCapability[] requiredCapability = iu.getRequiredCapabilities(); + List requiredCapability = iu.getRequiredCapabilities(); verifyRequiredCapability(requiredCapability, IInstallableUnit.NAMESPACE_IU_ID, flavor + id + ".config." + configSpec, new VersionRange(version, true, version, true)); //$NON-NLS-1$ verifyRequiredCapability(requiredCapability, IInstallableUnit.NAMESPACE_IU_ID, flavor + id + ".ini." + configSpec, new VersionRange(version, true, version, true)); //$NON-NLS-1$ - assertTrue(requiredCapability.length == 2); + assertTrue(requiredCapability.size() == 2); //verify non root IUs verifyFragment("ini"); //$NON-NLS-1$ @@ -82,16 +79,14 @@ public class ConfigCUsActionTest extends ActionTest { for (int i = 0; i < IUs.size(); i++) { InstallableUnit iu = (InstallableUnit) IUs.get(i); if (iu.getId().equals(flavor + id + "." + cuType + "." + configSpec)) { //$NON-NLS-1$ //$NON-NLS-2$ - assertTrue(iu.getFilter().equals("(& (osgi.ws=win32)(osgi.os=win32)(osgi.arch=x86))")); //$NON-NLS-1$ + assertTrue(iu.getFilter().equals(ExpressionUtil.parseLDAP("(& (osgi.ws=win32)(osgi.os=win32)(osgi.arch=x86))"))); //$NON-NLS-1$ assertTrue(iu.getVersion().equals(version)); - assertTrue(iu.getProperty("org.eclipse.equinox.p2.type.fragment").equals("true")); //$NON-NLS-1$//$NON-NLS-2$ assertFalse(iu.isSingleton()); - IProvidedCapability[] providedCapabilities = iu.getProvidedCapabilities(); + Collection providedCapabilities = iu.getProvidedCapabilities(); verifyProvidedCapability(providedCapabilities, IInstallableUnit.NAMESPACE_IU_ID, flavor + id + "." + cuType + "." + configSpec, version); //$NON-NLS-1$//$NON-NLS-2$ verifyProvidedCapability(providedCapabilities, flavor + id, id + "." + cuType, version); //$NON-NLS-1$ - assertTrue(providedCapabilities.length == 2); - assertTrue(iu.getRequiredCapabilities().length == 0); - assertFalse(iu.isFragment()); + assertTrue(providedCapabilities.size() == 2); + assertTrue(iu.getRequiredCapabilities().size() == 0); return; //pass } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/DefaultCUsActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/DefaultCUsActionTest.java index 4efbf1258..22806f1b6 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/DefaultCUsActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/DefaultCUsActionTest.java @@ -10,18 +10,19 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.publisher.actions; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; -import java.util.ArrayList; +import java.util.Collection; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.metadata.InstallableUnitFragment; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.eclipse.DefaultCUsAction; -@SuppressWarnings( {"restriction", "unchecked"}) +@SuppressWarnings({"unchecked"}) public class DefaultCUsActionTest extends ActionTest { - private Version version = new Version("1.0.0"); //$NON-NLS-1$ + private Version version = Version.create("1.0.0"); //$NON-NLS-1$ public void testAll() throws Exception { testAction = new DefaultCUsAction(publisherInfo, flavorArg, 4 /*start level*/, true /*start*/); @@ -34,7 +35,7 @@ public class DefaultCUsActionTest extends ActionTest { } private void verifyDefaultCUs() { - ArrayList ius = (ArrayList) publisherResult.getIUs(null, null); + Collection ius = publisherResult.getIUs(null, null); assertTrue(ius.size() == 3); InstallableUnitFragment iuf1 = new InstallableUnitFragment(); iuf1.setId(flavorArg + ".source.default"); //$NON-NLS-1$ diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/EquinoxExecutableActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/EquinoxExecutableActionTest.java index 3cfcfdee3..90d6155c7 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/EquinoxExecutableActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/EquinoxExecutableActionTest.java @@ -12,23 +12,22 @@ package org.eclipse.equinox.p2.tests.publisher.actions; import static org.easymock.EasyMock.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.io.File; -import java.util.ArrayList; -import java.util.Collections; +import java.util.*; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.publisher.eclipse.ExecutablesDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil; import org.eclipse.equinox.p2.publisher.*; import org.eclipse.equinox.p2.publisher.eclipse.EquinoxExecutableAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; import org.eclipse.equinox.p2.tests.TestActivator; import org.eclipse.equinox.p2.tests.publisher.TestArtifactRepository; -@SuppressWarnings( {"restriction", "unchecked"}) +@SuppressWarnings({"restriction", "unchecked"}) public class EquinoxExecutableActionTest extends ActionTest { private static final File MAC_EXEC = new File(TestActivator.getTestDataFolder(), "EquinoxExecutableActionTest/macosx/"); //$NON-NLS-1$ @@ -41,7 +40,7 @@ public class EquinoxExecutableActionTest extends ActionTest { private String linuxConfig = "linux.gtk.x86"; //$NON-NLS-1$ private ExecutablesDescriptor executablesDescriptor; private IArtifactRepository artifactRepository; - private Version version = new Version("1.2.3"); //$NON-NLS-1$ + private Version version = Version.create("1.2.3"); //$NON-NLS-1$ public void setUp() throws Exception { setupPublisherInfo(); @@ -95,13 +94,13 @@ public class EquinoxExecutableActionTest extends ActionTest { IInstallableUnit possibleEclipse = (IInstallableUnit) iuList.get(i); if (possibleEclipse.getId().equals(flavorArg + idBase + ".executable." + configSpec)) {//$NON-NLS-1$ IInstallableUnitFragment fragment = (IInstallableUnitFragment) iuList.get(i); - IProvidedCapability[] providedCapability = fragment.getProvidedCapabilities(); + Collection providedCapability = fragment.getProvidedCapabilities(); verifyProvidedCapability(providedCapability, IInstallableUnit.NAMESPACE_IU_ID, flavorArg + idBase + ".executable." + configSpec, version); //$NON-NLS-1$ - assertTrue(providedCapability.length == 1); - IRequiredCapability[] requiredCapability = fragment.getRequiredCapabilities(); + assertTrue(providedCapability.size() == 1); + Collection requiredCapability = fragment.getRequiredCapabilities(); verifyRequiredCapability(requiredCapability, IInstallableUnit.NAMESPACE_IU_ID, idBase + ".executable." + configSpec, new VersionRange(version, true, version, true)); //$NON-NLS-1$ - assertTrue(requiredCapability.length == 1); - assertTrue(fragment.getFilter().equals("(& (osgi.ws=" + ws + ")(osgi.os=" + os + ")(osgi.arch=" + arch + "))")); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ + assertTrue(requiredCapability.size() == 1); + assertTrue(fragment.getFilter().equals(ExpressionUtil.parseLDAP("(& (osgi.ws=" + ws + ")(osgi.os=" + os + ")(osgi.arch=" + arch + "))"))); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ assertTrue(fragment.getProperty("org.eclipse.equinox.p2.type.fragment").equals("true")); //$NON-NLS-1$ //$NON-NLS-2$ return;//pass } @@ -115,11 +114,11 @@ public class EquinoxExecutableActionTest extends ActionTest { IInstallableUnit possibleEclipse = (IInstallableUnit) iuList.get(i); if (possibleEclipse.getId().equals((idBase + ".executable." + configSpec + ".eclipse"))) { //$NON-NLS-1$//$NON-NLS-2$ assertTrue(possibleEclipse.getVersion().equals(version)); - IProvidedCapability[] providedCapability = possibleEclipse.getProvidedCapabilities(); + Collection providedCapability = possibleEclipse.getProvidedCapabilities(); verifyProvidedCapability(providedCapability, IInstallableUnit.NAMESPACE_IU_ID, idBase + ".executable." + configSpec + ".eclipse", version); //$NON-NLS-1$ //$NON-NLS-2$ - assertTrue(providedCapability.length == 1); - IRequiredCapability[] req = possibleEclipse.getRequiredCapabilities(); - assertTrue(req.length == 0); + assertTrue(providedCapability.size() == 1); + Collection req = possibleEclipse.getRequiredCapabilities(); + assertTrue(req.size() == 0); return;//pass } } @@ -136,19 +135,19 @@ public class EquinoxExecutableActionTest extends ActionTest { IInstallableUnit possibleExec = (IInstallableUnit) iuList.get(i); if (possibleExec.getId().equals(idBase + ".executable." + configSpec)) { //$NON-NLS-1$ //keep checking - assertTrue(possibleExec.getFilter().equals("(& (osgi.ws=" + ws + ")(osgi.os=" + os + ")(osgi.arch=" + arch + "))")); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ - IArtifactKey eKey = possibleExec.getArtifacts()[0]; + assertTrue(possibleExec.getFilter().equals(ExpressionUtil.parseLDAP("(& (osgi.ws=" + ws + ")(osgi.os=" + os + ")(osgi.arch=" + arch + "))"))); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ + IArtifactKey eKey = possibleExec.getArtifacts().iterator().next(); assertTrue(eKey.getClassifier().equals("binary")); //$NON-NLS-1$ assertTrue(eKey.getId().equals(idBase + ".executable." + configSpec)); //$NON-NLS-1$ assertTrue(eKey.getVersion().equals(version)); - IProvidedCapability[] providedCapabilities = possibleExec.getProvidedCapabilities(); + Collection providedCapabilities = possibleExec.getProvidedCapabilities(); verifyProvidedCapability(providedCapabilities, IInstallableUnit.NAMESPACE_IU_ID, idBase + ".executable." + configSpec, version); //$NON-NLS-1$ verifyProvidedCapability(providedCapabilities, flavorArg + idBase, idBase + ".executable", version); //$NON-NLS-1$ - assertTrue(providedCapabilities.length == 2); + assertTrue(providedCapabilities.size() == 2); - IRequiredCapability[] requiredCapability = possibleExec.getRequiredCapabilities(); + Collection requiredCapability = possibleExec.getRequiredCapabilities(); verifyRequiredCapability(requiredCapability, IInstallableUnit.NAMESPACE_IU_ID, "org.eclipse.equinox.launcher." + (idBase.equals("mac") || idBase.equals("macCocoa") ? configSpec.substring(0, configSpec.lastIndexOf(".")) : configSpec), VersionRange.emptyRange); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - assertTrue(requiredCapability.length == 1); + assertTrue(requiredCapability.size() == 1); return;//pass } } @@ -157,8 +156,8 @@ public class EquinoxExecutableActionTest extends ActionTest { protected void insertPublisherInfoBehavior() { setupArtifactRepository(); - expect(publisherInfo.getArtifactRepository()).andReturn(artifactRepository); - expect(publisherInfo.getArtifactOptions()).andReturn(IPublisherInfo.A_PUBLISH); + expect(publisherInfo.getArtifactRepository()).andReturn(artifactRepository).anyTimes(); + expect(publisherInfo.getArtifactOptions()).andReturn(IPublisherInfo.A_PUBLISH).anyTimes(); expect(publisherInfo.getAdvice((String) anyObject(), anyBoolean(), (String) anyObject(), (Version) anyObject(), (Class) anyObject())).andReturn(Collections.emptyList()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/EquinoxLauncherCUActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/EquinoxLauncherCUActionTest.java index 31f170b8a..1ba56c201 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/EquinoxLauncherCUActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/EquinoxLauncherCUActionTest.java @@ -12,16 +12,14 @@ package org.eclipse.equinox.p2.tests.publisher.actions; import static org.easymock.EasyMock.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; - -import java.util.ArrayList; -import java.util.Map; +import java.util.*; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.metadata.InstallableUnitFragment; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IProvidedCapability; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IProvidedCapability; import org.eclipse.equinox.p2.publisher.IPublisherResult; import org.eclipse.equinox.p2.publisher.PublisherResult; import org.eclipse.equinox.p2.publisher.actions.IVersionAdvice; @@ -29,7 +27,7 @@ import org.eclipse.equinox.p2.publisher.actions.VersionAdvice; import org.eclipse.equinox.p2.publisher.eclipse.EquinoxLauncherCUAction; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; -@SuppressWarnings( {"restriction", "unchecked"}) +@SuppressWarnings({"restriction", "unchecked"}) public class EquinoxLauncherCUActionTest extends ActionTest { private static String a_ID = "iua.source"; //$NON-NLS-1$ @@ -56,7 +54,6 @@ public class EquinoxLauncherCUActionTest extends ActionTest { version = Version.emptyVersion; expect(result.getVersion()).andReturn(version).anyTimes(); expect(result.getFilter()).andReturn(null).anyTimes(); - expect(result.isFragment()).andReturn(fragment).anyTimes(); replay(result); return result; } @@ -70,13 +67,13 @@ public class EquinoxLauncherCUActionTest extends ActionTest { assertTrue(iu instanceof InstallableUnitFragment); //verify required capability verifyRequiredCapability(iu.getRequiredCapabilities(), PublisherHelper.OSGI_BUNDLE_CLASSIFIER, EquinoxLauncherCUAction.ORG_ECLIPSE_EQUINOX_LAUNCHER, VersionRange.emptyRange); - verifyRequiredCapability(iu.getRequiredCapabilities(), PublisherHelper.NAMESPACE_ECLIPSE_TYPE, "bundle", new VersionRange(new Version("1.0.0"), true, new Version("2.0.0"), false)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - assertTrue(iu.getRequiredCapabilities().length == 2); + verifyRequiredCapability(iu.getRequiredCapabilities(), PublisherHelper.NAMESPACE_ECLIPSE_TYPE, "bundle", new VersionRange(Version.create("1.0.0"), true, Version.create("2.0.0"), false)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + assertTrue(iu.getRequiredCapabilities().size() == 2); - IProvidedCapability[] cap = iu.getProvidedCapabilities(); + Collection cap = iu.getProvidedCapabilities(); verifyProvidedCapability(cap, IInstallableUnit.NAMESPACE_IU_ID, flavorArg + "org.eclipse.equinox.launcher", Version.emptyVersion); //$NON-NLS-1$ - verifyProvidedCapability(cap, "org.eclipse.equinox.p2.flavor", flavorArg, new Version("1.0.0")); //$NON-NLS-1$//$NON-NLS-2$ - assertTrue(cap.length == 2); + verifyProvidedCapability(cap, "org.eclipse.equinox.p2.flavor", flavorArg, Version.create("1.0.0")); //$NON-NLS-1$//$NON-NLS-2$ + assertTrue(cap.size() == 2); Map prop = iu.getProperties(); assertTrue(prop.get("org.eclipse.equinox.p2.type.fragment").equals("true")); //$NON-NLS-1$ //$NON-NLS-2$ @@ -100,7 +97,7 @@ public class EquinoxLauncherCUActionTest extends ActionTest { VersionAdvice versionAdvice = new VersionAdvice(); versionAdvice.setVersion(IInstallableUnit.NAMESPACE_IU_ID, flavorArg + "org.eclipse.equinox.launcher", Version.emptyVersion); //$NON-NLS-1$ versionAdvice.setVersion(IInstallableUnit.NAMESPACE_IU_ID, "org.eclipse.equinox.launcher", Version.emptyVersion); //$NON-NLS-1$ - versionAdvice.setVersion("org.eclipse.equinox.p2.flavor", flavorArg, new Version("1.0.0")); //$NON-NLS-1$//$NON-NLS-2$ + versionAdvice.setVersion("org.eclipse.equinox.p2.flavor", flavorArg, Version.create("1.0.0")); //$NON-NLS-1$//$NON-NLS-2$ ArrayList versionList = new ArrayList(); versionList.add(versionAdvice); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/FeaturesActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/FeaturesActionTest.java index e545682ac..4f2b41dd8 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/FeaturesActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/FeaturesActionTest.java @@ -12,10 +12,6 @@ package org.eclipse.equinox.p2.tests.publisher.actions; import static org.easymock.EasyMock.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - - import java.io.File; import java.io.IOException; import java.util.*; @@ -25,13 +21,14 @@ import org.easymock.EasyMock; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil; import org.eclipse.equinox.p2.publisher.IPublisherInfo; import org.eclipse.equinox.p2.publisher.IPublisherResult; import org.eclipse.equinox.p2.publisher.actions.*; import org.eclipse.equinox.p2.publisher.eclipse.FeaturesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; import org.eclipse.equinox.p2.tests.*; import org.eclipse.equinox.p2.tests.publisher.TestArtifactRepository; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; @@ -45,8 +42,8 @@ public class FeaturesActionTest extends ActionTest { private static File root = new File(TestActivator.getTestDataFolder().toString(), "FeaturesActionTest"); //$NON-NLS-1$ protected TestArtifactRepository artifactRepository = new TestArtifactRepository(); protected TestMetadataRepository metadataRepository; - private Version fooVersion = new Version("1.0.0"); //$NON-NLS-1$ - private Version barVersion = new Version("1.1.1"); //$NON-NLS-1$ + private Version fooVersion = Version.create("1.0.0"); //$NON-NLS-1$ + private Version barVersion = Version.create("1.1.1"); //$NON-NLS-1$ private String BAR = "bar"; //$NON-NLS-1$ private String FOO = "foo"; //$NON-NLS-1$ private Capture tpAdvice; @@ -85,38 +82,38 @@ public class FeaturesActionTest extends ActionTest { assertTrue(foo.getVersion().equals(fooVersion)); assertEquals("Foo Feature", foo.getProperty(IInstallableUnit.PROP_NAME)); assertEquals("Foo Description", foo.getProperty(IInstallableUnit.PROP_DESCRIPTION)); - assertEquals("Foo License", foo.getLicense().getBody()); + assertEquals("Foo License", foo.getLicenses().iterator().next().getBody()); assertEquals("Foo Copyright", foo.getCopyright().getBody()); assertTrue(foo.getProperty("key1").equals("value1")); //$NON-NLS-1$ //$NON-NLS-2$ assertTrue(foo.getProperty("key2").equals("value2")); //$NON-NLS-1$//$NON-NLS-2$ - assertTrue(foo.getArtifacts()[0].equals(FOO_KEY)); - assertTrue(foo.getFilter().equalsIgnoreCase("(org.eclipse.update.install.features=true)")); //$NON-NLS-1$ + assertTrue(foo.getArtifacts().iterator().next().equals(FOO_KEY)); + assertTrue(foo.getFilter().equals(ExpressionUtil.parseLDAP("(org.eclipse.update.install.features=true)"))); //$NON-NLS-1$ //check touchpointType assertTrue(foo.getTouchpointType().getId().equalsIgnoreCase("org.eclipse.equinox.p2.osgi")); //$NON-NLS-1$ assertTrue(foo.getTouchpointType().getVersion().equals(fooVersion)); //zipped=true - ITouchpointData[] tpData = foo.getTouchpointData(); - String fooValue = ((ITouchpointInstruction) tpData[0].getInstructions().get("zipped")).getBody(); //$NON-NLS-1$ + List tpData = foo.getTouchpointData(); + String fooValue = ((ITouchpointInstruction) tpData.get(0).getInstructions().get("zipped")).getBody(); //$NON-NLS-1$ assertTrue(fooValue.equalsIgnoreCase("true")); //$NON-NLS-1$ - IRequiredCapability[] fooRequiredCapabilities = foo.getRequiredCapabilities(); - assertTrue(fooRequiredCapabilities.length == 0); + Collection fooRequiredCapabilities = foo.getRequiredCapabilities(); + assertTrue(fooRequiredCapabilities.size() == 0); - IProvidedCapability[] fooProvidedCapabilities = foo.getProvidedCapabilities(); + Collection fooProvidedCapabilities = foo.getProvidedCapabilities(); contains(fooProvidedCapabilities, IInstallableUnit.NAMESPACE_IU_ID, "foo.feature.jar", fooVersion); //$NON-NLS-1$ contains(fooProvidedCapabilities, PublisherHelper.NAMESPACE_ECLIPSE_TYPE, "feature", fooVersion); //$NON-NLS-1$ contains(fooProvidedCapabilities, "org.eclipse.update.feature", FOO, fooVersion); //$NON-NLS-1$ - assertTrue(fooProvidedCapabilities.length == 3); + assertTrue(fooProvidedCapabilities.size() == 3); //feature group IU for foo fooIUs = new ArrayList(publisherResult.getIUs("foo.feature.group", IPublisherResult.ROOT)); //$NON-NLS-1$ assertTrue(fooIUs.size() == 1); IInstallableUnit fooGroup = (IInstallableUnit) fooIUs.get(0); tpData = fooGroup.getTouchpointData(); - assertEquals(1, tpData.length); - ITouchpointInstruction instruction = tpData[0].getInstruction("install"); + assertEquals(1, tpData.size()); + ITouchpointInstruction instruction = tpData.get(0).getInstruction("install"); assertNotNull(instruction); assertEquals("ln(targetDir:@artifact,linkTarget:foo/lib.1.so,linkName:lib.so);chmod(targetDir:@artifact,targetFile:lib/lib.so,permissions:755);", instruction.getBody()); System.out.println(fooGroup.getFilter()); @@ -132,21 +129,21 @@ public class FeaturesActionTest extends ActionTest { assertTrue(bar.getProperty("key2").equals("value2")); //$NON-NLS-1$//$NON-NLS-2$ assertTrue(bar.getProperties().containsKey("org.eclipse.update.installHandler")); //$NON-NLS-1$ assertTrue(bar.getProperties().containsValue("handler=bar handler")); //$NON-NLS-1$ - assertTrue(bar.getArtifacts()[0].equals(BAR_KEY)); - assertTrue(bar.getFilter().equalsIgnoreCase("(org.eclipse.update.install.features=true)")); //$NON-NLS-1$ + assertTrue(bar.getArtifacts().iterator().next().equals(BAR_KEY)); + assertTrue(bar.getFilter().equals(ExpressionUtil.parseLDAP("(org.eclipse.update.install.features=true)"))); //$NON-NLS-1$ assertTrue(bar.isSingleton()); barIUs = new ArrayList(publisherResult.getIUs("bar.feature.group", IPublisherResult.ROOT)); //$NON-NLS-1$ assertTrue(fooIUs.size() == 1); IInstallableUnit barGroup = (IInstallableUnit) barIUs.get(0); - IRequiredCapability[] barRequiredCapabilities = barGroup.getRequiredCapabilities(); + Collection barRequiredCapabilities = barGroup.getRequiredCapabilities(); //contains(barRequiredCapabilities, IInstallableUnit.NAMESPACE_IU_ID, "bar_root", new VersionRange(barVersion, true, barVersion, true), null, false /*multiple*/, false /*optional*/); //$NON-NLS-1$//$NON-NLS-2$ contains(barRequiredCapabilities, IInstallableUnit.NAMESPACE_IU_ID, "bar.feature.jar", new VersionRange(barVersion, true, barVersion, true), "(org.eclipse.update.install.features=true)", false /*multiple*/, false /*optional*/); //$NON-NLS-1$//$NON-NLS-2$ contains(barRequiredCapabilities, IInstallableUnit.NAMESPACE_IU_ID, "org.bar.feature.feature.group", VersionRange.emptyRange, "(&(|(osgi.nl=de)(osgi.nl=en)(osgi.nl=fr)))", false /*multiple*/, false /*optional*/); //$NON-NLS-1$//$NON-NLS-2$ - assertTrue(barGroup.getFilter().equalsIgnoreCase("(&(|(osgi.os=macosx)(osgi.os=win32))(|(osgi.ws=carbon)(osgi.ws=win32))(|(osgi.arch=ppc)(osgi.arch=x86))(osgi.nl=en))")); + assertTrue(barGroup.getFilter().equals(ExpressionUtil.parseLDAP("(&(|(osgi.os=macosx)(osgi.os=win32))(|(osgi.ws=carbon)(osgi.ws=win32))(|(osgi.arch=ppc)(osgi.arch=x86))(osgi.nl=en))"))); //check zipped=true in touchpointData - String barValue = ((ITouchpointInstruction) bar.getTouchpointData()[0].getInstructions().get("zipped")).getBody(); //$NON-NLS-1$ + String barValue = ((ITouchpointInstruction) bar.getTouchpointData().get(0).getInstructions().get("zipped")).getBody(); //$NON-NLS-1$ assertTrue(barValue.equalsIgnoreCase("true")); //$NON-NLS-1$ //check touchpointType @@ -155,13 +152,13 @@ public class FeaturesActionTest extends ActionTest { //String namespace, String name, VersionRange range, String filter, boolean optional, boolean multiple, boolean greedy) barRequiredCapabilities = bar.getRequiredCapabilities(); - assertTrue(barRequiredCapabilities.length == 0); + assertTrue(barRequiredCapabilities.size() == 0); - IProvidedCapability[] barProvidedCapabilities = bar.getProvidedCapabilities(); + Collection barProvidedCapabilities = bar.getProvidedCapabilities(); contains(barProvidedCapabilities, IInstallableUnit.NAMESPACE_IU_ID, "bar.feature.jar", barVersion); //$NON-NLS-1$ contains(barProvidedCapabilities, PublisherHelper.NAMESPACE_ECLIPSE_TYPE, "feature", fooVersion); //$NON-NLS-1$ contains(barProvidedCapabilities, "org.eclipse.update.feature", BAR, barVersion); //$NON-NLS-1$ - assertTrue(barProvidedCapabilities.length == 3); + assertTrue(barProvidedCapabilities.size() == 3); } private void verifyArtifacts() throws IOException { @@ -204,9 +201,9 @@ public class FeaturesActionTest extends ActionTest { } private ArrayList fillAdvice(ArrayList adviceCollection) { - Properties prop = new Properties(); - prop.setProperty("key1", "value1"); //$NON-NLS-1$//$NON-NLS-2$ - prop.setProperty("key2", "value2"); //$NON-NLS-1$//$NON-NLS-2$ + Map prop = new HashMap(); + prop.put("key1", "value1"); //$NON-NLS-1$//$NON-NLS-2$ + prop.put("key2", "value2"); //$NON-NLS-1$//$NON-NLS-2$ IPropertyAdvice propertyAdvice = EasyMock.createMock(IPropertyAdvice.class); expect(propertyAdvice.getInstallableUnitProperties((InstallableUnitDescription) EasyMock.anyObject())).andReturn(prop).anyTimes(); expect(propertyAdvice.getArtifactProperties((IInstallableUnit) EasyMock.anyObject(), (IArtifactDescriptor) EasyMock.anyObject())).andReturn(null).anyTimes(); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/JREActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/JREActionTest.java index aa75a955a..6f1e28c72 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/JREActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/JREActionTest.java @@ -12,9 +12,8 @@ package org.eclipse.equinox.p2.tests.publisher.actions; import static org.easymock.EasyMock.expect; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.io.*; import java.util.*; @@ -22,14 +21,14 @@ import java.util.zip.ZipInputStream; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.publisher.IPublisherInfo; import org.eclipse.equinox.p2.publisher.IPublisherResult; import org.eclipse.equinox.p2.publisher.actions.JREAction; import org.eclipse.equinox.p2.tests.*; import org.eclipse.equinox.p2.tests.publisher.TestArtifactRepository; -@SuppressWarnings( {"unchecked"}) +@SuppressWarnings({"unchecked"}) public class JREActionTest extends ActionTest { private File J14 = new File(TestActivator.getTestDataFolder(), "JREActionTest/1.4/"); //$NON-NLS-1$ @@ -47,28 +46,28 @@ public class JREActionTest extends ActionTest { public void test14() throws Exception { testAction = new JREAction(J14); testAction.perform(publisherInfo, publisherResult, new NullProgressMonitor()); - verifyResults("a.jre.j2se", 92, new Version("1.4.0"), true); //$NON-NLS-1$ + verifyResults("a.jre.j2se", 92, Version.create("1.4.0"), true); //$NON-NLS-1$ verifyArtifactRepository(ArtifactKey.parse("binary,a.jre.j2se,1.4.0"), J14, "J2SE-1.4.profile"); //$NON-NLS-1$ //$NON-NLS-2$ } public void test15() throws Exception { testAction = new JREAction(J15); testAction.perform(publisherInfo, publisherResult, new NullProgressMonitor()); - verifyResults("a.jre.j2se", 119, new Version("1.5.0"), true); //$NON-NLS-1$ + verifyResults("a.jre.j2se", 119, Version.create("1.5.0"), true); //$NON-NLS-1$ verifyArtifactRepository(ArtifactKey.parse("binary,a.jre.j2se,1.5.0"), J15, "J2SE-1.5.profile"); //$NON-NLS-1$ //$NON-NLS-2$ } public void test16() throws Exception { testAction = new JREAction(J16); testAction.perform(publisherInfo, publisherResult, new NullProgressMonitor()); - verifyResults("a.jre.javase", 117, new Version("1.6.0"), true); //$NON-NLS-1$ + verifyResults("a.jre.javase", 117, Version.create("1.6.0"), true); //$NON-NLS-1$ verifyArtifactRepository(ArtifactKey.parse("binary,a.jre.javase,1.6.0"), J16, "JavaSE-1.6.profile"); //$NON-NLS-1$//$NON-NLS-2$ } public void testOSGiMin() throws Exception { testAction = new JREAction("OSGi/Minimum-1.2"); testAction.perform(publisherInfo, publisherResult, new NullProgressMonitor()); - verifyResults("a.jre.osgi.minimum", 2, new Version("1.2.0"), false); //$NON-NLS-1$ + verifyResults("a.jre.osgi.minimum", 2, Version.create("1.2.0"), false); //$NON-NLS-1$ } private void verifyResults(String id, int numProvidedCapabilities, Version JREVersion, boolean testInstructions) { @@ -81,28 +80,28 @@ public class JREActionTest extends ActionTest { // check touchpointType assertTrue(foo.getTouchpointType().getId().equalsIgnoreCase("org.eclipse.equinox.p2.native")); //$NON-NLS-1$ - assertTrue(foo.getTouchpointType().getVersion().equals(new Version("1.0.0"))); //$NON-NLS-1$ + assertTrue(foo.getTouchpointType().getVersion().equals(Version.create("1.0.0"))); //$NON-NLS-1$ // check provided capabilities - IProvidedCapability[] fooProvidedCapabilities = foo.getProvidedCapabilities(); - assertTrue(fooProvidedCapabilities.length == numProvidedCapabilities); + Collection fooProvidedCapabilities = foo.getProvidedCapabilities(); + assertTrue(fooProvidedCapabilities.size() == numProvidedCapabilities); ArrayList barIUs = new ArrayList(publisherResult.getIUs("config." + id, IPublisherResult.ROOT)); //$NON-NLS-1$ assertTrue(barIUs.size() == 1); IInstallableUnit bar = (IInstallableUnit) barIUs.get(0); if (testInstructions) { - Map instructions = bar.getTouchpointData()[0].getInstructions(); + Map instructions = bar.getTouchpointData().get(0).getInstructions(); assertTrue(((ITouchpointInstruction) instructions.get("install")).getBody().equals("unzip(source:@artifact, target:${installFolder});")); //$NON-NLS-1$//$NON-NLS-2$ assertTrue(((ITouchpointInstruction) instructions.get("uninstall")).getBody().equals("cleanupzip(source:@artifact, target:${installFolder});")); //$NON-NLS-1$ //$NON-NLS-2$ } - IRequiredCapability[] requiredCapability = bar.getRequiredCapabilities(); - verifyRequiredCapability(requiredCapability, IInstallableUnit.NAMESPACE_IU_ID, id, new VersionRange(JREVersion, true, new Version(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE), true)); //$NON-NLS-1$ - assertTrue(requiredCapability.length == 1); + Collection requiredCapability = bar.getRequiredCapabilities(); + verifyRequiredCapability(requiredCapability, IInstallableUnit.NAMESPACE_IU_ID, id, new VersionRange(JREVersion, true, Version.MAX_VERSION, true)); //$NON-NLS-1$ + assertTrue(requiredCapability.size() == 1); - IProvidedCapability[] providedCapability = bar.getProvidedCapabilities(); + Collection providedCapability = bar.getProvidedCapabilities(); verifyProvidedCapability(providedCapability, IInstallableUnit.NAMESPACE_IU_ID, "config." + id, JREVersion); //$NON-NLS-1$ - assertTrue(providedCapability.length == 1); + assertTrue(providedCapability.size() == 1); assertTrue(bar.getProperty("org.eclipse.equinox.p2.type.fragment").equals("true")); //$NON-NLS-1$//$NON-NLS-2$ assertTrue(bar.getVersion().equals(JREVersion)); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/LocalUpdateSiteActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/LocalUpdateSiteActionTest.java index 88b7a3664..98c428271 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/LocalUpdateSiteActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/LocalUpdateSiteActionTest.java @@ -11,15 +11,14 @@ package org.eclipse.equinox.p2.tests.publisher.actions; import static org.easymock.EasyMock.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; - +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import java.util.*; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.updatesite.LocalUpdateSiteAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.ITouchpointData; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.ITouchpointData; import org.eclipse.equinox.p2.publisher.IPublisherInfo; import org.eclipse.equinox.p2.tests.TestData; import org.eclipse.equinox.p2.tests.publisher.TestArtifactRepository; @@ -60,9 +59,9 @@ public class LocalUpdateSiteActionTest extends ActionTest { Collection ius = publisherResult.getIUs("test.feature.feature.jar", null); assertEquals("1.0", 1, ius.size()); IInstallableUnit iu = (IInstallableUnit) ius.iterator().next(); - ITouchpointData[] touchpointData = iu.getTouchpointData(); - assertEquals("1.1", 1, touchpointData.length); - Map instructions = touchpointData[0].getInstructions(); + List touchpointData = iu.getTouchpointData(); + assertEquals("1.1", 1, touchpointData.size()); + Map instructions = touchpointData.get(0).getInstructions(); Set keys = instructions.keySet(); assertEquals("1.2", 1, keys.size()); String unzip = (String) keys.iterator().next(); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/LocalizationTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/LocalizationTests.java index cc86e8512..5a69e5c5a 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/LocalizationTests.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/LocalizationTests.java @@ -16,15 +16,15 @@ import java.util.Locale; import junit.framework.TestCase; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.metadata.TranslationSupport; import org.eclipse.equinox.internal.p2.updatesite.SiteXMLAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.publisher.PublisherInfo; import org.eclipse.equinox.p2.publisher.PublisherResult; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; import org.eclipse.equinox.p2.publisher.eclipse.FeaturesAction; -import org.eclipse.equinox.p2.tests.IUPropertyUtils; +import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.equinox.p2.tests.TestData; /** @@ -33,8 +33,14 @@ import org.eclipse.equinox.p2.tests.TestData; public class LocalizationTests extends TestCase { private PublisherInfo info; - private PublisherResult results; private IProgressMonitor monitor; + private PublisherResult results; + + private TranslationSupport getTranslationSupport() { + TranslationSupport utils = new TranslationSupport(); + utils.setTranslationSource(results.query(new InstallableUnitQuery((String) null), monitor)); + return utils; + } /* (non-Javadoc) * @see junit.framework.TestCase#setUp() @@ -46,132 +52,87 @@ public class LocalizationTests extends TestCase { monitor = new NullProgressMonitor(); } - public void testFeatureLocalizationDefault() throws IOException { - File file = TestData.getFile("localizationtests/foofeature", ""); - FeaturesAction featuresAction = new FeaturesAction(new File[] {file}); - featuresAction.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("fooFeature.feature.group"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "Foo English Feature", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME)); - assertEquals("1.1", "Foo English Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER)); - assertEquals("1.3", "Foo English Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION)); - assertEquals("1.4", "Foo English Copyright", utils.getCopyright(iu).getBody()); - assertEquals("1.5", "Foo English License", utils.getLicense(iu).getBody()); + public void testBundleLocalizationDE() throws IOException { + File file = TestData.getFile("localizationtests/foobundle", ""); + BundlesAction action = new BundlesAction(new File[] {file}); + action.perform(info, results, monitor); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("foobundle"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "Foo German Bundle", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN.toString())); + assertEquals("1.1", "Foo German Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.GERMAN.toString())); } - public void testFeatureLocalizationEN() throws IOException { - File file = TestData.getFile("localizationtests/foofeature", ""); - FeaturesAction featuresAction = new FeaturesAction(new File[] {file}); - featuresAction.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("fooFeature.feature.group"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "Foo English Feature", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH)); - assertEquals("1.1", "Foo English Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.ENGLISH)); - assertEquals("1.3", "Foo English Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION, Locale.ENGLISH)); - assertEquals("1.4", "Foo English Copyright", utils.getCopyright(iu, Locale.ENGLISH).getBody()); - assertEquals("1.5", "Foo English License", utils.getLicense(iu, Locale.ENGLISH).getBody()); + public void testBundleLocalizationDE_alternatePropFile() throws IOException { + File file = TestData.getFile("localizationtests/barbundle", ""); + BundlesAction action = new BundlesAction(new File[] {file}); + action.perform(info, results, monitor); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("barbundle"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "Bar German Bundle", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN.toString())); + assertEquals("1.1", "Bar German Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.GERMAN.toString())); } - public void testFeatureLocalizatioDE() throws IOException { - File file = TestData.getFile("localizationtests/foofeature", ""); - FeaturesAction featuresAction = new FeaturesAction(new File[] {file}); - featuresAction.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("fooFeature.feature.group"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "Foo German Feature", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN)); - assertEquals("1.1", "Foo German Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.GERMAN)); - assertEquals("1.3", "Foo German Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION, Locale.GERMAN)); - assertEquals("1.4", "Foo German Copyright", utils.getCopyright(iu, Locale.GERMAN).getBody()); - assertEquals("1.5", "Foo German License", utils.getLicense(iu, Locale.GERMAN).getBody()); - } + public void testBundleLocalizationDE_alternatePropFile_fragment() throws IOException { + File bundle = TestData.getFile("localizationtests/barbundle2", ""); + File fragment = TestData.getFile("localizationtests/barfragment2", ""); + BundlesAction action = new BundlesAction(new File[] {bundle, fragment}); + action.perform(info, results, monitor); - public void testFeatureJarLocalizationDefault() throws IOException { - File file = TestData.getFile("localizationtests/foofeature", ""); - FeaturesAction featuresAction = new FeaturesAction(new File[] {file}); - featuresAction.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("fooFeature.feature.jar"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "Foo English Feature", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME)); - assertEquals("1.1", "Foo English Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER)); - assertEquals("1.3", "Foo English Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION)); - assertEquals("1.4", "Foo English Copyright", utils.getCopyright(iu).getBody()); - assertEquals("1.5", "Foo English License", utils.getLicense(iu).getBody()); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("barbundle2"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "Bar German Bundle - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN.toString())); + assertEquals("1.1", "Bar German Provider - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.GERMAN.toString())); } - public void testFeatureJarLocalizationEN() throws IOException { - File file = TestData.getFile("localizationtests/foofeature", ""); - FeaturesAction featuresAction = new FeaturesAction(new File[] {file}); - featuresAction.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("fooFeature.feature.jar"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "Foo English Feature", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH)); - assertEquals("1.1", "Foo English Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.ENGLISH)); - assertEquals("1.3", "Foo English Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION, Locale.ENGLISH)); - assertEquals("1.4", "Foo English Copyright", utils.getCopyright(iu, Locale.ENGLISH).getBody()); - assertEquals("1.5", "Foo English License", utils.getLicense(iu, Locale.ENGLISH).getBody()); - } + public void testBundleLocalizationDE_fragment() throws IOException { + File bundle = TestData.getFile("localizationtests/foobundle2", ""); + File fragment = TestData.getFile("localizationtests/foofragment2", ""); + BundlesAction action = new BundlesAction(new File[] {bundle, fragment}); + action.perform(info, results, monitor); - public void testFeatureJarLocalizatioDE() throws IOException { - File file = TestData.getFile("localizationtests/foofeature", ""); - FeaturesAction featuresAction = new FeaturesAction(new File[] {file}); - featuresAction.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("fooFeature.feature.jar"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "Foo German Feature", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN)); - assertEquals("1.1", "Foo German Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.GERMAN)); - assertEquals("1.3", "Foo German Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION, Locale.GERMAN)); - assertEquals("1.4", "Foo German Copyright", utils.getCopyright(iu, Locale.GERMAN).getBody()); - assertEquals("1.5", "Foo German License", utils.getLicense(iu, Locale.GERMAN).getBody()); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("foobundle2"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "Foo German Bundle - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN.toString())); + assertEquals("1.1", "Foo German Provider - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.GERMAN.toString())); } public void testBundleLocalizationEN() throws IOException { File file = TestData.getFile("localizationtests/foobundle", ""); BundlesAction action = new BundlesAction(new File[] {file}); action.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("foobundle"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "Foo English Bundle", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH)); - assertEquals("1.1", "Foo English Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.ENGLISH)); - } - - public void testBundleLocalizationDE() throws IOException { - File file = TestData.getFile("localizationtests/foobundle", ""); - BundlesAction action = new BundlesAction(new File[] {file}); - action.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("foobundle"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "Foo German Bundle", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN)); - assertEquals("1.1", "Foo German Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.GERMAN)); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("foobundle"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "Foo English Bundle", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH.toString())); + assertEquals("1.1", "Foo English Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.ENGLISH.toString())); } public void testBundleLocalizationEN_alternatePropFile() throws IOException { File file = TestData.getFile("localizationtests/barbundle", ""); BundlesAction action = new BundlesAction(new File[] {file}); action.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("barbundle"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "Bar English Bundle", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH)); - assertEquals("1.1", "Bar English Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.ENGLISH)); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("barbundle"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "Bar English Bundle", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH.toString())); + assertEquals("1.1", "Bar English Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.ENGLISH.toString())); } - public void testBundleLocalizationDE_alternatePropFile() throws IOException { - File file = TestData.getFile("localizationtests/barbundle", ""); - BundlesAction action = new BundlesAction(new File[] {file}); + public void testBundleLocalizationEN_alternatePropFile_fragment() throws IOException { + File bundle = TestData.getFile("localizationtests/barbundle2", ""); + File fragment = TestData.getFile("localizationtests/barfragment2", ""); + BundlesAction action = new BundlesAction(new File[] {bundle, fragment}); action.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("barbundle"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "Bar German Bundle", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN)); - assertEquals("1.1", "Bar German Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.GERMAN)); + + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("barbundle2"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "Bar English Bundle - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH.toString())); + assertEquals("1.1", "Bar English Provider - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.ENGLISH.toString())); } public void testBundleLocalizationEN_fragment() throws IOException { @@ -180,79 +141,124 @@ public class LocalizationTests extends TestCase { BundlesAction action = new BundlesAction(new File[] {bundle, fragment}); action.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("foobundle2"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "Foo English Bundle - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH)); - assertEquals("1.1", "Foo English Provider - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.ENGLISH)); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("foobundle2"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "Foo English Bundle - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH.toString())); + assertEquals("1.1", "Foo English Provider - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.ENGLISH.toString())); } - public void testBundleLocalizationDE_fragment() throws IOException { - File bundle = TestData.getFile("localizationtests/foobundle2", ""); - File fragment = TestData.getFile("localizationtests/foofragment2", ""); - BundlesAction action = new BundlesAction(new File[] {bundle, fragment}); - action.perform(info, results, monitor); + public void testFeatureJarLocalizatioDE() throws IOException { + File file = TestData.getFile("localizationtests/foofeature", ""); + FeaturesAction featuresAction = new FeaturesAction(new File[] {file}); + featuresAction.perform(info, results, monitor); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("fooFeature.feature.jar"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "Foo German Feature", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN.toString())); + assertEquals("1.1", "Foo German Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.GERMAN.toString())); + assertEquals("1.3", "Foo German Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION, Locale.GERMAN.toString())); + assertEquals("1.4", "Foo German Copyright", utils.getCopyright(iu, Locale.GERMAN.toString()).getBody()); + assertEquals("1.5", "Foo German License", utils.getLicenses(iu, Locale.GERMAN.toString())[0].getBody()); + } - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("foobundle2"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "Foo German Bundle - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN)); - assertEquals("1.1", "Foo German Provider - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.GERMAN)); + public void testFeatureJarLocalizationDefault() throws IOException { + File file = TestData.getFile("localizationtests/foofeature", ""); + FeaturesAction featuresAction = new FeaturesAction(new File[] {file}); + featuresAction.perform(info, results, monitor); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("fooFeature.feature.jar"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "Foo English Feature", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME)); + assertEquals("1.1", "Foo English Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER)); + assertEquals("1.3", "Foo English Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION)); + assertEquals("1.4", "Foo English Copyright", utils.getCopyright(iu, null).getBody()); + assertEquals("1.5", "Foo English License", utils.getLicenses(iu, null)[0].getBody()); } - public void testBundleLocalizationEN_alternatePropFile_fragment() throws IOException { - File bundle = TestData.getFile("localizationtests/barbundle2", ""); - File fragment = TestData.getFile("localizationtests/barfragment2", ""); - BundlesAction action = new BundlesAction(new File[] {bundle, fragment}); - action.perform(info, results, monitor); + public void testFeatureJarLocalizationEN() throws IOException { + File file = TestData.getFile("localizationtests/foofeature", ""); + FeaturesAction featuresAction = new FeaturesAction(new File[] {file}); + featuresAction.perform(info, results, monitor); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("fooFeature.feature.jar"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "Foo English Feature", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH.toString())); + assertEquals("1.1", "Foo English Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.ENGLISH.toString())); + assertEquals("1.3", "Foo English Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION, Locale.ENGLISH.toString())); + assertEquals("1.4", "Foo English Copyright", utils.getCopyright(iu, Locale.ENGLISH.toString()).getBody()); + assertEquals("1.5", "Foo English License", utils.getLicenses(iu, Locale.ENGLISH.toString())[0].getBody()); + } - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("barbundle2"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "Bar English Bundle - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH)); - assertEquals("1.1", "Bar English Provider - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.ENGLISH)); + public void testFeatureLocalizatioDE() throws IOException { + File file = TestData.getFile("localizationtests/foofeature", ""); + FeaturesAction featuresAction = new FeaturesAction(new File[] {file}); + featuresAction.perform(info, results, monitor); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("fooFeature.feature.group"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "Foo German Feature", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN.toString())); + assertEquals("1.1", "Foo German Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.GERMAN.toString())); + assertEquals("1.3", "Foo German Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION, Locale.GERMAN.toString())); + assertEquals("1.4", "Foo German Copyright", utils.getCopyright(iu, Locale.GERMAN.toString()).getBody()); + assertEquals("1.5", "Foo German License", utils.getLicenses(iu, Locale.GERMAN.toString())[0].getBody()); } - public void testBundleLocalizationDE_alternatePropFile_fragment() throws IOException { - File bundle = TestData.getFile("localizationtests/barbundle2", ""); - File fragment = TestData.getFile("localizationtests/barfragment2", ""); - BundlesAction action = new BundlesAction(new File[] {bundle, fragment}); - action.perform(info, results, monitor); + public void testFeatureLocalizationDefault() throws IOException { + File file = TestData.getFile("localizationtests/foofeature", ""); + FeaturesAction featuresAction = new FeaturesAction(new File[] {file}); + featuresAction.perform(info, results, monitor); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("fooFeature.feature.group"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "Foo English Feature", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME)); + assertEquals("1.1", "Foo English Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER)); + assertEquals("1.3", "Foo English Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION)); + assertEquals("1.4", "Foo English Copyright", utils.getCopyright(iu, null).getBody()); + assertEquals("1.5", "Foo English License", utils.getLicenses(iu, null)[0].getBody()); + } - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("barbundle2"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "Bar German Bundle - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN)); - assertEquals("1.1", "Bar German Provider - Translated in the Fragment", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.GERMAN)); + public void testFeatureLocalizationEN() throws IOException { + File file = TestData.getFile("localizationtests/foofeature", ""); + FeaturesAction featuresAction = new FeaturesAction(new File[] {file}); + featuresAction.perform(info, results, monitor); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("fooFeature.feature.group"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "Foo English Feature", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH.toString())); + assertEquals("1.1", "Foo English Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.ENGLISH.toString())); + assertEquals("1.3", "Foo English Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION, Locale.ENGLISH.toString())); + assertEquals("1.4", "Foo English Copyright", utils.getCopyright(iu, Locale.ENGLISH.toString()).getBody()); + assertEquals("1.5", "Foo English License", utils.getLicenses(iu, Locale.ENGLISH.toString())[0].getBody()); } - public void testFragmentTranslation_EN() throws IOException { + public void testFragmentTranslation_DE() throws IOException { File bundle = TestData.getFile("localizationtests/barbundle2", ""); File fragment = TestData.getFile("localizationtests/barfragment2", ""); BundlesAction action = new BundlesAction(new File[] {bundle, fragment}); action.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("barfragment2"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "English Fragment Name", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH)); - assertEquals("1.1", "English Fragment Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.ENGLISH)); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("barfragment2"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "German Fragment Name", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN.toString())); + assertEquals("1.1", "German Fragment Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.GERMAN.toString())); } - public void testFragmentTranslation_DE() throws IOException { + public void testFragmentTranslation_EN() throws IOException { File bundle = TestData.getFile("localizationtests/barbundle2", ""); File fragment = TestData.getFile("localizationtests/barfragment2", ""); BundlesAction action = new BundlesAction(new File[] {bundle, fragment}); action.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("barfragment2"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "German Fragment Name", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN)); - assertEquals("1.1", "German Fragment Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.GERMAN)); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("barfragment2"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "English Fragment Name", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH.toString())); + assertEquals("1.1", "English Fragment Provider", utils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER, Locale.ENGLISH.toString())); } - public void testSite_EN() throws IOException { + public void testSite_DE() throws IOException { File feature = TestData.getFile("localizationtests/foofeature", ""); URI site = TestData.getFile("localizationtests/site", "").toURI(); @@ -261,15 +267,15 @@ public class LocalizationTests extends TestCase { action.perform(info, results, monitor); siteAction.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("foo.new_category_1"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "English Category Name", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH)); - assertEquals("1.1", "English Category Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION, Locale.ENGLISH)); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("foo.new_category_1"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "German Category Name", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN.toString())); + assertEquals("1.1", "German Category Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION, Locale.GERMAN.toString())); } - public void testSite_DE() throws IOException { + public void testSite_EN() throws IOException { File feature = TestData.getFile("localizationtests/foofeature", ""); URI site = TestData.getFile("localizationtests/site", "").toURI(); @@ -278,11 +284,11 @@ public class LocalizationTests extends TestCase { action.perform(info, results, monitor); siteAction.perform(info, results, monitor); - IUPropertyUtils utils = new IUPropertyUtils(results.query(new InstallableUnitQuery((String) null), new Collector(), monitor)); - Collector collector = results.query(new InstallableUnitQuery("foo.new_category_1"), new Collector(), monitor); - IInstallableUnit iu = (IInstallableUnit) collector.iterator().next(); - assertEquals("1.0", "German Category Name", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.GERMAN)); - assertEquals("1.1", "German Category Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION, Locale.GERMAN)); + TranslationSupport utils = getTranslationSupport(); + IQueryResult queryResult = results.query(new InstallableUnitQuery("foo.new_category_1"), monitor); + IInstallableUnit iu = (IInstallableUnit) queryResult.iterator().next(); + assertEquals("1.0", "English Category Name", utils.getIUProperty(iu, IInstallableUnit.PROP_NAME, Locale.ENGLISH.toString())); + assertEquals("1.1", "English Category Description", utils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION, Locale.ENGLISH.toString())); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/MD5GenerationTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/MD5GenerationTest.java index f16856573..e4b41a024 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/MD5GenerationTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/MD5GenerationTest.java @@ -10,41 +10,41 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.publisher.actions; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; public class MD5GenerationTest extends AbstractProvisioningTest { public void testGenerationFile() { - IArtifactDescriptor ad = PublisherHelper.createArtifactDescriptor(new ArtifactKey("classifierTest", "idTest", new Version(1, 0, 0)), getTestData("Artifact to generate from", "testData/artifactRepo/simpleWithMD5/plugins/aaPlugin_1.0.0.jar")); + IArtifactDescriptor ad = PublisherHelper.createArtifactDescriptor(new ArtifactKey("classifierTest", "idTest", Version.createOSGi(1, 0, 0)), getTestData("Artifact to generate from", "testData/artifactRepo/simpleWithMD5/plugins/aaPlugin_1.0.0.jar")); assertEquals("50d4ea58b02706ab373a908338877e02", ad.getProperty(IArtifactDescriptor.DOWNLOAD_MD5)); } public void testGenerationFile2() { - IArtifactDescriptor ad = PublisherHelper.createArtifactDescriptor(new ArtifactKey("classifierTest", "idTest", new Version(1, 0, 0)), getTestData("Artifact to generate from", "testData/artifactRepo/simpleWithMD5/plugins/aaPlugin_1.0.0.jar")); + IArtifactDescriptor ad = PublisherHelper.createArtifactDescriptor(new ArtifactKey("classifierTest", "idTest", Version.createOSGi(1, 0, 0)), getTestData("Artifact to generate from", "testData/artifactRepo/simpleWithMD5/plugins/aaPlugin_1.0.0.jar")); assertEquals("50d4ea58b02706ab373a908338877e02", ad.getProperty(IArtifactDescriptor.DOWNLOAD_MD5)); } public void testGenerationFolder() { - IArtifactDescriptor ad = PublisherHelper.createArtifactDescriptor(new ArtifactKey("classifierTest", "idTest", new Version(1, 0, 0)), getTestData("Artifact to generate from", "testData/artifactRepo/simpleWithMD5/plugins/")); + IArtifactDescriptor ad = PublisherHelper.createArtifactDescriptor(new ArtifactKey("classifierTest", "idTest", Version.createOSGi(1, 0, 0)), getTestData("Artifact to generate from", "testData/artifactRepo/simpleWithMD5/plugins/")); assertNull(ad.getProperty(IArtifactDescriptor.DOWNLOAD_MD5)); } public void testGenerationFolder2() { - IArtifactDescriptor ad = PublisherHelper.createArtifactDescriptor(new ArtifactKey("classifierTest", "idTest", new Version(1, 0, 0)), getTestData("Artifact to generate from", "testData/artifactRepo/simpleWithMD5/plugins/")); + IArtifactDescriptor ad = PublisherHelper.createArtifactDescriptor(new ArtifactKey("classifierTest", "idTest", Version.createOSGi(1, 0, 0)), getTestData("Artifact to generate from", "testData/artifactRepo/simpleWithMD5/plugins/")); assertNull(ad.getProperty(IArtifactDescriptor.DOWNLOAD_MD5)); } public void testGenerationNoFolder() { - IArtifactDescriptor ad = PublisherHelper.createArtifactDescriptor(new ArtifactKey("classifierTest", "idTest", new Version(1, 0, 0)), null); + IArtifactDescriptor ad = PublisherHelper.createArtifactDescriptor(new ArtifactKey("classifierTest", "idTest", Version.createOSGi(1, 0, 0)), null); assertNull(ad.getProperty(IArtifactDescriptor.DOWNLOAD_MD5)); } public void testGenerationNoFolder2() { - IArtifactDescriptor ad = PublisherHelper.createArtifactDescriptor(new ArtifactKey("classifierTest", "idTest", new Version(1, 0, 0)), null); + IArtifactDescriptor ad = PublisherHelper.createArtifactDescriptor(new ArtifactKey("classifierTest", "idTest", Version.createOSGi(1, 0, 0)), null); assertNull(ad.getProperty(IArtifactDescriptor.DOWNLOAD_MD5)); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductActionTest.java index 964725793..3900d2b3e 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductActionTest.java @@ -12,9 +12,6 @@ package org.eclipse.equinox.p2.tests.publisher.actions; import static org.easymock.EasyMock.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; - - import java.io.File; import java.io.IOException; import java.util.Collection; @@ -22,19 +19,21 @@ import java.util.Collections; import org.easymock.Capture; import org.easymock.EasyMock; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.metadata.RequiredCapability; import org.eclipse.equinox.internal.p2.publisher.eclipse.ProductFile; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.publisher.*; import org.eclipse.equinox.p2.publisher.actions.RootIUAdvice; import org.eclipse.equinox.p2.publisher.eclipse.*; +import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.equinox.p2.tests.TestData; import org.eclipse.equinox.p2.tests.publisher.TestArtifactRepository; -@SuppressWarnings( {"unchecked"}) +@SuppressWarnings({"unchecked"}) public class ProductActionTest extends ActionTest { private String winFitler = "(& (osgi.ws=win32)(osgi.os=win32)(osgi.arch=x86))"; @@ -93,8 +92,8 @@ public class ProductActionTest extends ActionTest { Collection ius = publisherResult.getIUs("licenseIU.product", IPublisherResult.NON_ROOT); assertEquals("1.0", 1, ius.size()); IInstallableUnit iu = (IInstallableUnit) ius.iterator().next(); - assertEquals("1.1", "http://www.example.com", iu.getLicense().getLocation().toString()); - assertEquals("1.2", "This is the liCenSE.", iu.getLicense().getBody().trim()); + assertEquals("1.1", "http://www.example.com", iu.getLicenses().iterator().next().getLocation().toString()); + assertEquals("1.2", "This is the liCenSE.", iu.getLicenses().iterator().next().getBody().trim()); } public void testLicenseNoURL() throws Exception { @@ -106,8 +105,8 @@ public class ProductActionTest extends ActionTest { Collection ius = publisherResult.getIUs("licenseIU.product", IPublisherResult.NON_ROOT); assertEquals("1.0", 1, ius.size()); IInstallableUnit iu = (IInstallableUnit) ius.iterator().next(); - assertEquals("1.1", "", iu.getLicense().getLocation().toString()); - assertEquals("1.2", "This is the liCenSE.", iu.getLicense().getBody().trim()); + assertEquals("1.1", "", iu.getLicenses().iterator().next().getLocation().toString()); + assertEquals("1.2", "This is the liCenSE.", iu.getLicenses().iterator().next().getBody().trim()); } public void testLicenseNoText() throws Exception { @@ -119,8 +118,8 @@ public class ProductActionTest extends ActionTest { Collection ius = publisherResult.getIUs("licenseIU.product", IPublisherResult.NON_ROOT); assertEquals("1.0", 1, ius.size()); IInstallableUnit iu = (IInstallableUnit) ius.iterator().next(); - assertEquals("1.1", "http://www.example.com", iu.getLicense().getLocation().toString()); - assertEquals("1.2", "", iu.getLicense().getBody().trim()); + assertEquals("1.1", "http://www.example.com", iu.getLicenses().iterator().next().getLocation().toString()); + assertEquals("1.2", "", iu.getLicenses().iterator().next().getBody().trim()); } public void testMissingLicense() throws Exception { @@ -132,7 +131,7 @@ public class ProductActionTest extends ActionTest { Collection ius = publisherResult.getIUs("licenseIU.product", IPublisherResult.NON_ROOT); assertEquals("1.0", 1, ius.size()); IInstallableUnit iu = (IInstallableUnit) ius.iterator().next(); - assertNull("1.1", iu.getLicense()); + assertEquals(0, iu.getLicenses().size()); } /** @@ -179,8 +178,8 @@ public class ProductActionTest extends ActionTest { results.addIU(iu, IPublisherResult.NON_ROOT); action2.perform(info, results, new NullProgressMonitor()); - Collector collector = results.query(new InstallableUnitQuery(flavorArg + configSpec + "org.eclipse.core.runtime"), new Collector(), new NullProgressMonitor()); - assertEquals("1.0", 1, collector.size()); + IQueryResult queryResult = results.query(new InstallableUnitQuery(flavorArg + configSpec + "org.eclipse.core.runtime"), new NullProgressMonitor()); + assertEquals("1.0", 1, queryResultSize(queryResult)); } public void testMultiPlatformCUs_DifferentPlatforms() throws Exception { @@ -202,11 +201,11 @@ public class ProductActionTest extends ActionTest { action.perform(info, results, new NullProgressMonitor()); - Collector collector = results.query(new InstallableUnitQuery(flavorArg + linuxConfigSpec + "org.eclipse.core.runtime"), new Collector(), new NullProgressMonitor()); - assertEquals("1.0", 0, collector.size()); + IQueryResult queryResult = results.query(new InstallableUnitQuery(flavorArg + linuxConfigSpec + "org.eclipse.core.runtime"), new NullProgressMonitor()); + assertEquals("1.0", 0, queryResultSize(queryResult)); - collector = results.query(new InstallableUnitQuery(flavorArg + windowsConfigSpec + "org.eclipse.core.runtime"), new Collector(), new NullProgressMonitor()); - assertEquals("2.0", 0, collector.size()); + queryResult = results.query(new InstallableUnitQuery(flavorArg + windowsConfigSpec + "org.eclipse.core.runtime"), new NullProgressMonitor()); + assertEquals("2.0", 0, queryResultSize(queryResult)); } public void testMultiPlatformCUs_SamePlatforms() throws Exception { @@ -228,11 +227,11 @@ public class ProductActionTest extends ActionTest { action.perform(info, results, new NullProgressMonitor()); - Collector collector = results.query(new InstallableUnitQuery(flavorArg + linuxConfigSpec + "org.eclipse.core.runtime"), new Collector(), new NullProgressMonitor()); - assertEquals("1.0", 1, collector.size()); + IQueryResult queryResult = results.query(new InstallableUnitQuery(flavorArg + linuxConfigSpec + "org.eclipse.core.runtime"), new NullProgressMonitor()); + assertEquals("1.0", 1, queryResultSize(queryResult)); - collector = results.query(new InstallableUnitQuery(flavorArg + windowsConfigSpec + "org.eclipse.core.runtime"), new Collector(), new NullProgressMonitor()); - assertEquals("2.0", 0, collector.size()); + queryResult = results.query(new InstallableUnitQuery(flavorArg + windowsConfigSpec + "org.eclipse.core.runtime"), new NullProgressMonitor()); + assertEquals("2.0", 0, queryResultSize(queryResult)); } public void testMultiPlatformCUs_SamePlatforms_NoVersion() throws Exception { @@ -253,11 +252,11 @@ public class ProductActionTest extends ActionTest { action.perform(info, results, new NullProgressMonitor()); - Collector collector = results.query(new InstallableUnitQuery(flavorArg + linuxConfigSpec + "org.eclipse.core.runtime"), new Collector(), new NullProgressMonitor()); - assertEquals("1.0", 1, collector.size()); + IQueryResult queryResult = results.query(new InstallableUnitQuery(flavorArg + linuxConfigSpec + "org.eclipse.core.runtime"), new NullProgressMonitor()); + assertEquals("1.0", 1, queryResultSize(queryResult)); - collector = results.query(new InstallableUnitQuery(flavorArg + windowsConfigSpec + "org.eclipse.core.runtime"), new Collector(), new NullProgressMonitor()); - assertEquals("2.0", 0, collector.size()); + queryResult = results.query(new InstallableUnitQuery(flavorArg + windowsConfigSpec + "org.eclipse.core.runtime"), new NullProgressMonitor()); + assertEquals("2.0", 0, queryResultSize(queryResult)); } public void testMultiPlatformCUs_SamePlatforms_BoundedVersions() throws Exception { @@ -279,11 +278,11 @@ public class ProductActionTest extends ActionTest { action.perform(info, results, new NullProgressMonitor()); - Collector collector = results.query(new InstallableUnitQuery(flavorArg + linuxConfigSpec + "org.eclipse.core.runtime"), new Collector(), new NullProgressMonitor()); - assertEquals("1.0", 1, collector.size()); + IQueryResult queryResult = results.query(new InstallableUnitQuery(flavorArg + linuxConfigSpec + "org.eclipse.core.runtime"), new NullProgressMonitor()); + assertEquals("1.0", 1, queryResultSize(queryResult)); - collector = results.query(new InstallableUnitQuery(flavorArg + windowsConfigSpec + "org.eclipse.core.runtime"), new Collector(), new NullProgressMonitor()); - assertEquals("2.0", 0, collector.size()); + queryResult = results.query(new InstallableUnitQuery(flavorArg + windowsConfigSpec + "org.eclipse.core.runtime"), new NullProgressMonitor()); + assertEquals("2.0", 0, queryResultSize(queryResult)); } public void testCUsHost() throws Exception { @@ -304,11 +303,11 @@ public class ProductActionTest extends ActionTest { action.perform(info, results, new NullProgressMonitor()); - Collector collector = results.query(new InstallableUnitQuery(flavorArg + linuxConfigSpec + "org.eclipse.core.runtime"), new Collector(), new NullProgressMonitor()); - assertEquals("1.0", 1, collector.size()); - IInstallableUnitFragment fragment = (IInstallableUnitFragment) collector.iterator().next(); - assertEquals("1.1", "org.eclipse.core.runtime", fragment.getHost()[0].getName()); - assertEquals("1.2", Version.create("4.0.0"), fragment.getHost()[0].getRange().getMinimum()); + IQueryResult queryResult = results.query(new InstallableUnitQuery(flavorArg + linuxConfigSpec + "org.eclipse.core.runtime"), new NullProgressMonitor()); + assertEquals("1.0", 1, queryResultSize(queryResult)); + IInstallableUnitFragment fragment = (IInstallableUnitFragment) queryResult.iterator().next(); + assertEquals("1.1", "org.eclipse.core.runtime", RequiredCapability.extractName(fragment.getHost()[0].getMatches())); + assertEquals("1.2", Version.create("4.0.0"), RequiredCapability.extractRange(fragment.getHost()[0].getMatches()).getMinimum()); assertEquals("1.3", Version.create("1.0.0"), fragment.getVersion()); } @@ -325,11 +324,11 @@ public class ProductActionTest extends ActionTest { action.perform(info, results, new NullProgressMonitor()); - Collector collector = results.query(new InstallableUnitQuery(flavorArg + linuxConfigSpec + "org.eclipse.core.runtime"), new Collector(), new NullProgressMonitor()); - assertEquals("1.0", 0, collector.size()); + IQueryResult queryResult = results.query(new InstallableUnitQuery(flavorArg + linuxConfigSpec + "org.eclipse.core.runtime"), new NullProgressMonitor()); + assertEquals("1.0", 0, queryResultSize(queryResult)); - collector = results.query(new InstallableUnitQuery(flavorArg + windowsConfigSpec + "org.eclipse.core.runtime"), new Collector(), new NullProgressMonitor()); - assertEquals("2.0", 0, collector.size()); + queryResult = results.query(new InstallableUnitQuery(flavorArg + windowsConfigSpec + "org.eclipse.core.runtime"), new NullProgressMonitor()); + assertEquals("2.0", 0, queryResultSize(queryResult)); } public void testMultiConfigspecProductPublishing() throws IOException, Exception { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductActionTestMac.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductActionTestMac.java index b435c9e34..fbe719c61 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductActionTestMac.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductActionTestMac.java @@ -12,8 +12,7 @@ package org.eclipse.equinox.p2.tests.publisher.actions; import static org.easymock.EasyMock.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; - +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import java.util.Collections; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductActionWithAdviceFileTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductActionWithAdviceFileTest.java index f29b6d99e..a30a3d39f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductActionWithAdviceFileTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductActionWithAdviceFileTest.java @@ -10,26 +10,28 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.publisher.actions; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.io.File; import java.net.URI; -import java.util.Collection; +import java.util.*; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.p2.publisher.eclipse.ProductFile; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.MatchQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.publisher.IPublisherResult; import org.eclipse.equinox.p2.publisher.PublisherInfo; import org.eclipse.equinox.p2.publisher.actions.QueryableFilterAdvice; import org.eclipse.equinox.p2.publisher.eclipse.ProductAction; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.query.MatchQuery; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.TestData; -@SuppressWarnings( {"unchecked"}) +@SuppressWarnings({"unchecked"}) /** * Tests the product action when run on a product file that has a corresponding * advice file (p2.inf). @@ -78,19 +80,21 @@ public class ProductActionWithAdviceFileTest extends ActionTest { info.addAdvice(new QueryableFilterAdvice(info.getContextMetadataRepository())); testAction.perform(info, publisherResult, null); - Collector results = publisherResult.query(new IUQuery("org.eclipse.platform.ide", new Version("3.5.0.I20081118")), new Collector(), null); - assertEquals("1.0", 1, results.size()); + IQueryResult results = publisherResult.query(new IUQuery("org.eclipse.platform.ide", Version.create("3.5.0.I20081118")), null); + assertEquals("1.0", 1, queryResultSize(results)); IInstallableUnit unit = (IInstallableUnit) results.iterator().next(); - IRequiredCapability[] requiredCapabilities = unit.getRequiredCapabilities(); + Collection requiredCapabilities = unit.getRequiredCapabilities(); IRequiredCapability capability = null; - for (int i = 0; i < requiredCapabilities.length; i++) - if (requiredCapabilities[i].getName().equals("org.eclipse.equinox.p2.user.ui.feature.group")) { - capability = requiredCapabilities[i]; + for (Iterator iterator = requiredCapabilities.iterator(); iterator.hasNext();) { + IRequiredCapability req = (IRequiredCapability) iterator.next(); + if (req.getName().equals("org.eclipse.equinox.p2.user.ui.feature.group")) { + capability = req; break; } + } assertTrue("1.1", capability != null); - assertEquals("1.2", "(org.eclipse.update.install.features=true)", capability.getFilter()); + assertEquals("1.2", "(org.eclipse.update.install.features=true)", capability.getFilter().toString()); } /** @@ -104,9 +108,9 @@ public class ProductActionWithAdviceFileTest extends ActionTest { Collection productIUs = publisherResult.getIUs("productWithAdvice.product", IPublisherResult.NON_ROOT); assertEquals("1.0", 1, productIUs.size()); IInstallableUnit product = (IInstallableUnit) productIUs.iterator().next(); - ITouchpointData[] data = product.getTouchpointData(); - assertEquals("1.1", 1, data.length); - String configure = data[0].getInstruction("configure").getBody(); + List data = product.getTouchpointData(); + assertEquals("1.1", 1, data.size()); + String configure = data.get(0).getInstruction("configure").getBody(); assertEquals("1.2", "addRepository(type:0,location:http${#58}//download.eclipse.org/releases/fred);addRepository(type:1,location:http${#58}//download.eclipse.org/releases/fred);", configure); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductFileAdviceTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductFileAdviceTest.java index 1558ca18a..f1434b554 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductFileAdviceTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductFileAdviceTest.java @@ -11,6 +11,7 @@ package org.eclipse.equinox.p2.tests.publisher.actions; import java.io.File; +import java.util.Map; import java.util.Properties; import org.eclipse.equinox.internal.p2.publisher.eclipse.ProductFile; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; @@ -149,7 +150,7 @@ public class ProductFileAdviceTest extends AbstractProvisioningTest { * Test method for {@link org.eclipse.equinox.p2.publisher.eclipse.ProductFileAdvice#getProperties()}. */ public void testGetProperties() { - Properties properties = productFileAdviceWin32.getProperties(); + Map properties = productFileAdviceWin32.getProperties(); assertEquals("1.0", 7, properties.size()); assertEquals("1.2", "bar", properties.get("foo")); assertEquals("1.3", "", properties.get("foo1")); @@ -253,7 +254,7 @@ public class ProductFileAdviceTest extends AbstractProvisioningTest { BundleInfo[] bundles = advice.getBundles(); assertEquals("bundlers length", 2, bundles.length); - Properties adviceProperties = advice.getProperties(); + Map adviceProperties = advice.getProperties(); assertEquals("instance.area.default", "@user.home/workspace", adviceProperties.get("osgi.instance.area.default")); assertEquals("eclipse.application", "test.application", adviceProperties.get("eclipse.application")); assertEquals("eclipse.product", "test.product", adviceProperties.get("eclipse.product")); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductFileTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductFileTest.java index 190362468..683589f92 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductFileTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/ProductFileTest.java @@ -9,15 +9,14 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.publisher.actions; -import org.eclipse.equinox.internal.provisional.p2.metadata.IVersionedId; - -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.util.List; -import java.util.Properties; +import java.util.Map; import junit.framework.TestCase; import org.eclipse.equinox.internal.p2.publisher.eclipse.ProductFile; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; +import org.eclipse.equinox.p2.metadata.IVersionedId; import org.eclipse.equinox.p2.tests.TestData; /** @@ -57,7 +56,7 @@ public class ProductFileTest extends TestCase { * Test method for {@link org.eclipse.equinox.internal.p2.publisher.eclipse.ProductFile#getProperties()}. */ public void testGetConfigurationProperties() { - Properties properties = productFile.getConfigurationProperties(); + Map properties = productFile.getConfigurationProperties(); assertEquals("1.0", 4, properties.size()); assertEquals("1.1", "bar", properties.get("foo")); assertEquals("1.2", "", properties.get("foo1")); @@ -72,7 +71,7 @@ public class ProductFileTest extends TestCase { List bundles = productFile.getBundles(false); assertEquals("1.0", 1, bundles.size()); assertEquals("1.1", "org.eclipse.core.runtime", ((IVersionedId) bundles.get(0)).getId()); - assertEquals("1.2", new Version(1, 0, 4), ((IVersionedId) bundles.get(0)).getVersion()); + assertEquals("1.2", Version.createOSGi(1, 0, 4), ((IVersionedId) bundles.get(0)).getVersion()); bundles = productFile.getBundles(true); assertEquals("1.3", 2, bundles.size()); } @@ -105,7 +104,7 @@ public class ProductFileTest extends TestCase { List features = productFile.getFeatures(); assertEquals("1.0", 1, features.size()); assertEquals("1.1", "org.eclipse.rcp", ((IVersionedId) features.get(0)).getId()); - assertEquals("1.2", new Version("3.5.0.v20081110-9C9tEvNEla71LZ2jFz-RFB-t"), ((IVersionedId) features.get(0)).getVersion()); + assertEquals("1.2", Version.create("3.5.0.v20081110-9C9tEvNEla71LZ2jFz-RFB-t"), ((IVersionedId) features.get(0)).getVersion()); } /** @@ -175,7 +174,7 @@ public class ProductFileTest extends TestCase { */ public void testGetVersion() { String version = productFile.getVersion(); - assertEquals("1.0", new Version("1"), new Version(version)); + assertEquals("1.0", Version.create("1"), Version.create(version)); } /** diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/RootFilesActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/RootFilesActionTest.java index 57ffaf89e..7e5e88fab 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/RootFilesActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/RootFilesActionTest.java @@ -12,8 +12,7 @@ package org.eclipse.equinox.p2.tests.publisher.actions; import static org.easymock.EasyMock.expect; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; - +import org.eclipse.equinox.p2.metadata.Version; import java.io.*; import java.util.*; @@ -21,16 +20,16 @@ import java.util.zip.ZipInputStream; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.FileUtils; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; import org.eclipse.equinox.p2.publisher.AbstractPublisherAction; import org.eclipse.equinox.p2.publisher.IPublisherInfo; import org.eclipse.equinox.p2.publisher.actions.*; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; import org.eclipse.equinox.p2.tests.TestActivator; import org.eclipse.equinox.p2.tests.TestData; import org.eclipse.equinox.p2.tests.publisher.TestArtifactRepository; -@SuppressWarnings( {"restriction", "unchecked"}) +@SuppressWarnings({"unchecked"}) public class RootFilesActionTest extends ActionTest { private static final int INCLUDES_ROOT = 1; private static final int ARTIFACT_REPO = 2; @@ -43,11 +42,11 @@ public class RootFilesActionTest extends ActionTest { protected String rootExclusions = null; protected IArtifactRepository artifactRepository; protected String idArg = "sdk"; //$NON-NLS-1$ - protected Version versionArg = new Version("3.4.0.i0305"); //$NON-NLS-1$ + protected Version versionArg = Version.create("3.4.0.i0305"); //$NON-NLS-1$ private File root = new File(TestActivator.getTestDataFolder(), "RootFilesActionTest/eclipse"); //$NON-NLS-1$ private File[] includedFiles; private File[] excludedFiles; - private Collection adviceCollection; + private Collection adviceCollection; private String FILE1 = "level1/level2/file1.jar"; //$NON-NLS-1$ private String FILE2 = "level1/level2/level3/file1.jar"; //$NON-NLS-1$ private int testArg; @@ -68,6 +67,7 @@ public class RootFilesActionTest extends ActionTest { expect(publisherInfo.getArtifactRepository()).andReturn(artifactRepository).anyTimes(); expect(publisherInfo.getArtifactOptions()).andReturn(IPublisherInfo.A_INDEX | IPublisherInfo.A_OVERWRITE | IPublisherInfo.A_PUBLISH).anyTimes(); expect(publisherInfo.getAdvice(configSpec, true, null, null, IRootFilesAdvice.class)).andReturn(adviceCollection).anyTimes(); + expect(publisherInfo.getAdvice(configSpec, false, flavorArg + topArg, versionArg, ITouchpointAdvice.class)).andReturn(null).anyTimes(); } private void setupTestCase(int testArg) throws Exception { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/RootIUActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/RootIUActionTest.java index 9636dff0f..e1e4deaca 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/RootIUActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/RootIUActionTest.java @@ -12,23 +12,22 @@ package org.eclipse.equinox.p2.tests.publisher.actions; import static org.easymock.EasyMock.expect; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; - -import java.util.ArrayList; -import java.util.Collection; +import java.util.*; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.MatchQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; import org.eclipse.equinox.p2.publisher.IPublisherResult; import org.eclipse.equinox.p2.publisher.actions.*; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.MatchQuery; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.TestMetadataRepository; -@SuppressWarnings( {"restriction", "unchecked"}) +@SuppressWarnings({"restriction", "unchecked"}) public class RootIUActionTest extends ActionTest { private static final int CONTAINS_A = 1; private static final int CONTAINS_B = 2; @@ -42,7 +41,7 @@ public class RootIUActionTest extends ActionTest { private IMetadataRepository metadataRepository; private String rootIU = "sdk"; //$NON-NLS-1$ - private Version versionArg = new Version("3.4.0.i0305"); //$NON-NLS-1$ + private Version versionArg = Version.create("3.4.0.i0305"); //$NON-NLS-1$ private Collection rootIUAdviceCollection; public void testNullAdvice() throws Exception { @@ -230,7 +229,7 @@ public class RootIUActionTest extends ActionTest { } private void setupFilterAdvice(int testSpec) { - Query query = null; + IQuery query = null; rootIUAdviceCollection = new ArrayList(); if ((testSpec & CONTAINS_A) > 0) { query = new MatchQuery() { @@ -272,9 +271,9 @@ public class RootIUActionTest extends ActionTest { IInstallableUnit iu = (IInstallableUnit) ius.get(0); assertTrue(iu != null); assertTrue(iu.getVersion().equals(versionArg)); - IRequiredCapability[] required = iu.getRequiredCapabilities(); + Collection required = iu.getRequiredCapabilities(); if ((testSpec & EMPTY) > 0) - assertEquals(required.length, 0); + assertEquals(required.size(), 0); String confirmedIUs = ""; //$NON-NLS-1$ int numConfirmed = 0; @@ -288,7 +287,7 @@ public class RootIUActionTest extends ActionTest { confirmedIUs += iu_B; numConfirmed++; } - if (numConfirmed != required.length) { + if (numConfirmed != required.size()) { debug("Not all required ius present / accounted for."); //$NON-NLS-1$ fail(); } @@ -298,10 +297,12 @@ public class RootIUActionTest extends ActionTest { debug("Confirmed \t\t Empty"); //$NON-NLS-1$ } - private boolean contains(IRequiredCapability[] required, String iu) { - for (int i = 0; i < required.length; i++) - if (required[i].getName().equalsIgnoreCase(iu)) + private boolean contains(Collection required, String iu) { + for (Iterator iterator = required.iterator(); iterator.hasNext();) { + IRequiredCapability req = (IRequiredCapability) iterator.next(); + if (req.getName().equalsIgnoreCase(iu)) return true; + } return false; } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/VersionAdviceTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/VersionAdviceTest.java index 07b986cb4..579fb145e 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/VersionAdviceTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/publisher/actions/VersionAdviceTest.java @@ -9,7 +9,7 @@ ******************************************************************************/ package org.eclipse.equinox.p2.tests.publisher.actions; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import junit.framework.TestCase; import org.eclipse.equinox.p2.publisher.actions.VersionAdvice; @@ -29,18 +29,18 @@ public class VersionAdviceTest extends TestCase { String versionAdviceFoo = TestData.getFile("publisher", "versionadvicefoo.prop").toString(); VersionAdvice versionAdvice = new VersionAdvice(); versionAdvice.load(null, versionAdviceFoo); - assertEquals("1.0", new Version("1.6.4.thisisastring"), versionAdvice.getVersion("foo", "org.apache.http")); - assertEquals("2.0", new Version("1.3.1"), versionAdvice.getVersion("null", "org.eclipse.cdt")); - assertEquals("3.0", new Version("1.4.0"), versionAdvice.getVersion(null, "org.eclipse.tptp")); + assertEquals("1.0", Version.create("1.6.4.thisisastring"), versionAdvice.getVersion("foo", "org.apache.http")); + assertEquals("2.0", Version.create("1.3.1"), versionAdvice.getVersion("null", "org.eclipse.cdt")); + assertEquals("3.0", Version.create("1.4.0"), versionAdvice.getVersion(null, "org.eclipse.tptp")); } public void testLoadNullVersionAdvice2() throws Exception { String versionAdviceFoo = TestData.getFile("publisher", "versionadvicefoo.prop").toString(); VersionAdvice versionAdvice = new VersionAdvice(); versionAdvice.load("null", versionAdviceFoo); - assertEquals("1.0", new Version("1.6.4.thisisastring"), versionAdvice.getVersion("foo", "org.apache.http")); - assertEquals("2.0", new Version("1.3.1"), versionAdvice.getVersion("null", "org.eclipse.cdt")); - assertEquals("3.0", new Version("1.4.0"), versionAdvice.getVersion(null, "org.eclipse.tptp")); + assertEquals("1.0", Version.create("1.6.4.thisisastring"), versionAdvice.getVersion("foo", "org.apache.http")); + assertEquals("2.0", Version.create("1.3.1"), versionAdvice.getVersion("null", "org.eclipse.cdt")); + assertEquals("3.0", Version.create("1.4.0"), versionAdvice.getVersion(null, "org.eclipse.tptp")); } public void testOverloadNull() throws Exception { @@ -49,19 +49,19 @@ public class VersionAdviceTest extends TestCase { VersionAdvice versionAdvice = new VersionAdvice(); versionAdvice.load(null, versionAdviceFoo); versionAdvice.load(null, versionAdviceBar); - assertEquals("1.0", new Version("1.6.4.thisisastring"), versionAdvice.getVersion("foo", "org.apache.http")); - assertEquals("1.0", new Version("1.6.4.thisisastring"), versionAdvice.getVersion("foo", "org.apache.commons")); - assertEquals("2.0", new Version("2.3.1"), versionAdvice.getVersion("null", "org.eclipse.cdt")); - assertEquals("3.0", new Version("1.5.0"), versionAdvice.getVersion(null, "org.eclipse.tptp")); + assertEquals("1.0", Version.create("1.6.4.thisisastring"), versionAdvice.getVersion("foo", "org.apache.http")); + assertEquals("1.0", Version.create("1.6.4.thisisastring"), versionAdvice.getVersion("foo", "org.apache.commons")); + assertEquals("2.0", Version.create("2.3.1"), versionAdvice.getVersion("null", "org.eclipse.cdt")); + assertEquals("3.0", Version.create("1.5.0"), versionAdvice.getVersion(null, "org.eclipse.tptp")); } public void testLoadVersionAdviceFoo() throws Exception { String versionAdviceFoo = TestData.getFile("publisher", "versionadvicefoo.prop").toString(); VersionAdvice versionAdvice = new VersionAdvice(); versionAdvice.load("foo", versionAdviceFoo); - assertEquals("1.0", new Version("1.6.4.thisisastring"), versionAdvice.getVersion("foo", "org.apache.http")); - assertEquals("2.0", new Version("1.3.1"), versionAdvice.getVersion("foo", "org.eclipse.cdt")); - assertEquals("3.0", new Version("1.4.0"), versionAdvice.getVersion("foo", "org.eclipse.tptp")); + assertEquals("1.0", Version.create("1.6.4.thisisastring"), versionAdvice.getVersion("foo", "org.apache.http")); + assertEquals("2.0", Version.create("1.3.1"), versionAdvice.getVersion("foo", "org.eclipse.cdt")); + assertEquals("3.0", Version.create("1.4.0"), versionAdvice.getVersion("foo", "org.eclipse.tptp")); assertEquals("4.0", null, versionAdvice.getVersion(null, "org.eclipse.tptp")); } @@ -70,9 +70,9 @@ public class VersionAdviceTest extends TestCase { VersionAdvice versionAdvice = new VersionAdvice(); versionAdvice.load("bar", versionAdviceBar); assertEquals("1.0", null, versionAdvice.getVersion("bar", "org.apache.http")); - assertEquals("2.0", new Version("1.6.4.thisisastring"), versionAdvice.getVersion("bar", "org.apache.commons")); - assertEquals("3.0", new Version("2.3.1"), versionAdvice.getVersion("bar", "org.eclipse.cdt")); - assertEquals("4.0", new Version("1.5.0"), versionAdvice.getVersion("bar", "org.eclipse.tptp")); + assertEquals("2.0", Version.create("1.6.4.thisisastring"), versionAdvice.getVersion("bar", "org.apache.commons")); + assertEquals("3.0", Version.create("2.3.1"), versionAdvice.getVersion("bar", "org.eclipse.cdt")); + assertEquals("4.0", Version.create("1.5.0"), versionAdvice.getVersion("bar", "org.eclipse.tptp")); } public void testLoadVersionAdviceFooBar() throws Exception { @@ -81,13 +81,13 @@ public class VersionAdviceTest extends TestCase { VersionAdvice versionAdvice = new VersionAdvice(); versionAdvice.load("foo", versionAdviceFoo); versionAdvice.load("bar", versionAdviceBar); - assertEquals("1.0", new Version("1.6.4.thisisastring"), versionAdvice.getVersion("foo", "org.apache.http")); - assertEquals("2.0", new Version("1.3.1"), versionAdvice.getVersion("foo", "org.eclipse.cdt")); - assertEquals("3.0", new Version("1.4.0"), versionAdvice.getVersion("foo", "org.eclipse.tptp")); + assertEquals("1.0", Version.create("1.6.4.thisisastring"), versionAdvice.getVersion("foo", "org.apache.http")); + assertEquals("2.0", Version.create("1.3.1"), versionAdvice.getVersion("foo", "org.eclipse.cdt")); + assertEquals("3.0", Version.create("1.4.0"), versionAdvice.getVersion("foo", "org.eclipse.tptp")); assertEquals("4.0", null, versionAdvice.getVersion("bar", "org.apache.http")); - assertEquals("5.0", new Version("1.6.4.thisisastring"), versionAdvice.getVersion("bar", "org.apache.commons")); - assertEquals("6.0", new Version("2.3.1"), versionAdvice.getVersion("bar", "org.eclipse.cdt")); - assertEquals("7.0", new Version("1.5.0"), versionAdvice.getVersion("bar", "org.eclipse.tptp")); + assertEquals("5.0", Version.create("1.6.4.thisisastring"), versionAdvice.getVersion("bar", "org.apache.commons")); + assertEquals("6.0", Version.create("2.3.1"), versionAdvice.getVersion("bar", "org.eclipse.cdt")); + assertEquals("7.0", Version.create("1.5.0"), versionAdvice.getVersion("bar", "org.eclipse.tptp")); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/AllTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/AllTests.java new file mode 100644 index 000000000..78b7fb83d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/AllTests.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.tests.ql; + +import junit.framework.*; + +/** + * Performs all automated director tests. + */ +public class AllTests extends TestCase { + + public static Test suite() { + TestSuite suite = new TestSuite(AllTests.class.getName()); + suite.addTestSuite(EvaluatorTest.class); + suite.addTestSuite(PerformanceTest.class); + suite.addTestSuite(TestQueryReimplementation.class); + return suite; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/EvaluatorTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/EvaluatorTest.java new file mode 100644 index 000000000..facafa400 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/EvaluatorTest.java @@ -0,0 +1,338 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.tests.ql; + +import java.io.File; +import java.net.URI; +import java.util.*; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.internal.p2.director.QueryableArray; +import org.eclipse.equinox.internal.p2.director.app.Activator; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.expression.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.publisher.PublisherInfo; +import org.eclipse.equinox.p2.publisher.PublisherResult; +import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.ql.*; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.query.MatchQuery; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; +import org.eclipse.equinox.p2.tests.TestActivator; +import org.osgi.framework.Filter; + +public class EvaluatorTest extends AbstractProvisioningTest { + private static final IQLParser parser = QL.newParser(); + private static final IQLFactory factory = QL.getFactory(); + + public void testArguments() throws Exception { + IExpression expr = parser.parse("'a' == $0 && 'b' == $1 && 'c' == $2"); + assertEquals(Boolean.TRUE, expr.evaluate(factory.createContext("a", "b", "c"))); + } + + public void testAnonymousMember() throws Exception { + IExpression expr = parser.parse("$0.class == $1"); + assertEquals(Boolean.TRUE, expr.evaluate(factory.createContext("a", String.class))); + } + + public void testInstanceOf() throws Exception { + // Explicit instanceof when rhs is a class + IExpression expr = parser.parse("$0 ~= $1"); + assertEquals(Boolean.TRUE, expr.evaluate(factory.createContext(new Integer(4), Number.class))); + } + + public void testArray() throws Exception { + IExpression expr = parser.parse("['a', 'b', 'c'].exists(x | x == 'b') && ['a', 'b', 'c'].all(x | 'd' > x)"); + IEvaluationContext ctx = factory.createContext(); + assertEquals(Boolean.TRUE, expr.evaluate(ctx)); + expr = parser.parse("['d', 'e', 'f'].exists(x | ['a', 'b', 'c'].exists(y | x > y))"); + assertEquals(Boolean.TRUE, expr.evaluate(ctx)); + expr = parser.parse("[['d', 'e', 'f'], ['h', 'i', 'j']].exists(x | x.all(y | ['a', 'b', 'c'].all(z | y > z)))"); + assertEquals(Boolean.TRUE, expr.evaluate(ctx)); + expr = parser.parse("[['d', 'e', 'f'], ['h', '3', 'j']].exists(x | x.all(y | ['a', 'b', 'c'].exists(z | y > z)))"); + assertEquals(Boolean.TRUE, expr.evaluate(ctx)); + expr = parser.parse("[['d', 'e', 'f'], ['h', 'i', 'j']].all(x | x.all(y | ['a', 'b', 'c'].all(z | y > z)))"); + assertEquals(Boolean.TRUE, expr.evaluate(ctx)); + expr = parser.parse("[['d', 'e', 'f'], ['h', '3', 'j']].all(x | x.all(y | ['a', 'b', 'c'].all(z | y > z)))"); + assertEquals(Boolean.FALSE, expr.evaluate(ctx)); // 3 < 'b' + } + + public void testLatest() throws Exception { + IMetadataRepository repo = getMDR("/testData/metadataRepo/multipleversions1"); + IQueryResult result = repo.query(new QLContextQuery(IInstallableUnit.class, "latest(x | x.id == $0)", "test.bundle"), new NullProgressMonitor()); + assertTrue(queryResultSize(result) == 1); + } + + public void testRange() throws Exception { + IMetadataRepository repo = getMDR("/testData/metadataRepo/multipleversions1"); + IQueryResult result = repo.query(new QLMatchQuery(IInstallableUnit.class, "version ~= $0", new VersionRange("2.0.0")), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 2); + } + + public void testProperty() throws Exception { + IMetadataRepository repo = getMDR("/testData/metadataRepo/multipleversions1"); + + IQueryResult result = repo.query(new QLMatchQuery(IInstallableUnit.class, "properties.exists(p | boolean(p.value))"), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 3); + + result = repo.query(new QLMatchQuery(IInstallableUnit.class, "boolean(properties['org.eclipse.equinox.p2.type.group'])"), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 3); + + Filter filter = TestActivator.context.createFilter("(org.eclipse.equinox.p2.type.group=true)"); + result = repo.query(new QLMatchQuery(IInstallableUnit.class, "properties ~= $0", filter), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 3); + } + + public void testToString() throws Exception { + String exprString = "select(x | x.id == $0 && (x.version == $1 || x.version == $2)).traverse(set(), _, {requirementsCache, parent | select(" + // + "parent.requiredCapabilities.unique(requirementsCache).select(rc | rc.filter == null || $2 ~= filter(rc.filter)), _, " + // + "{rcs, child | rcs.exists(rc | child ~= rc)})}).limit(10)"; + + IContextExpression expr = factory.contextExpression(IInstallableUnit.class, parser.parseQuery(exprString)); + System.out.println(expr.toString()); + assertEquals(exprString, expr.toString()); + } + + public void testSomeAPI() throws Exception { + // Create some expressions. Note the use of identifiers instead of + // indexes for the parameters + + IExpression item = factory.variable("item"); + IExpression cmp1 = factory.equals(factory.member(item, "id"), factory.indexedParameter(0)); + IExpression cmp2 = factory.equals(factory.at(factory.member(item, "properties"), factory.indexedParameter(1)), factory.indexedParameter(2)); + + IExpression lambda = factory.lambda(item, factory.and(cmp1, cmp2)); + IExpression latest = factory.latest(factory.select(factory.variable("everything"), lambda)); + + // Create the query + IContextExpression e3 = factory.contextExpression(IInstallableUnit.class, latest, "test.bundle", "org.eclipse.equinox.p2.type.group", "true"); + IMetadataRepository repo = getMDR("/testData/metadataRepo/multipleversions1"); + IQueryResult result = repo.query(new QLContextQuery(e3), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 1); + } + + public void testMember() throws Exception { + IMetadataRepository repo = getMDR("/testData/metadataRepo/wsdlTestRepo"); + IProvidedCapability pc = MetadataFactory.createProvidedCapability("org.eclipse.equinox.p2.eclipse.type", "source", null); + IQueryResult result = repo.query(new QLMatchQuery(IInstallableUnitFragment.class, "host.exists(h | $0.name == h.name && $0.namespace == h.namespace)", new Object[] {pc}), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 1); + } + + public void testPatch() throws Exception { + IRequiredCapability[][] applicability = new IRequiredCapability[2][2]; + applicability[0][0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "javax.wsdl", null, null, false, false); + applicability[0][1] = MetadataFactory.createRequiredCapability("org.eclipse.equinox.p2.eclipse.type", "bundle", null, null, false, false); + applicability[1][0] = MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, "tooling.source.default", null, null, false, false); + applicability[1][1] = MetadataFactory.createRequiredCapability("org.eclipse.equinox.p2.flavor", "tooling", null, null, false, false); + + IMetadataRepository repo = getMDR("/testData/metadataRepo/wsdlTestRepo"); + IQueryResult result = repo.query(new QLMatchQuery(IInstallableUnit.class, "$0.exists(rcs | rcs.all(rc | this ~= rc))", (Object) applicability), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 3); + } + + public void testPattern() throws Exception { + IProvidedCapability pc = MetadataFactory.createProvidedCapability("org.eclipse.equinox.p2.eclipse.type", "source", null); + IMetadataRepository repo = getMDR("/testData/metadataRepo/wsdlTestRepo"); + IQueryResult result = repo.query(new QLMatchQuery(IInstallableUnit.class, "id ~= /tooling.*.default/", pc), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 3); + } + + public void testLimit() throws Exception { + IMetadataRepository repo = getMDR("/testData/metadataRepo/wsdlTestRepo"); + IQueryResult result = repo.query(new QLContextQuery(IInstallableUnit.class, "select(x | x.id ~= /tooling.*/).limit(1)"), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 1); + + result = repo.query(new QLContextQuery(IInstallableUnit.class, "select(x | x.id ~= /tooling.*/).limit($0)", new Integer(2)), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 2); + } + + public void testNot() throws Exception { + IMetadataRepository repo = getMDR("/testData/metadataRepo/wsdlTestRepo"); + IQueryResult result = repo.query(new QLMatchQuery(IInstallableUnit.class, "!(id ~= /tooling.*/)"), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 4); + } + + public void testArtifactQuery() throws Exception { + URI artifactRepo = getTestData("1.1", "/testData/artifactRepo/simple").toURI(); + + IArtifactRepositoryManager artifactManager = getArtifactRepositoryManager(); + assertNotNull(artifactManager); + + IArtifactRepository repo = artifactManager.loadRepository(artifactRepo, new NullProgressMonitor()); + IQueryResult result = repo.query(new QLMatchQuery(IArtifactKey.class, "classifier ~= /*/"), new NullProgressMonitor()); + assertTrue(queryResultSize(result) > 1); + Iterator itor = result.iterator(); + while (itor.hasNext()) + assertTrue(itor.next() instanceof IArtifactKey); + + result = repo.descriptorQueryable().query(new QLMatchQuery(IArtifactDescriptor.class, "artifactKey.classifier ~= /*/"), new NullProgressMonitor()); + assertTrue(queryResultSize(result) > 1); + itor = result.iterator(); + while (itor.hasNext()) + assertTrue(itor.next() instanceof IArtifactDescriptor); + } + + public void testClassConstructor() throws Exception { + IMetadataRepository repo = getMDR("/testData/metadataRepo/wsdlTestRepo"); + IQueryResult result = repo.query(new QLContextQuery(IInstallableUnit.class, // + "select(x | x ~= class('org.eclipse.equinox.p2.metadata.IInstallableUnitFragment'))"), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 4); + repo = getMDR("/testData/galileoM7"); + } + + public void testTraverseWithoutIndex() throws Exception { + IMetadataRepository repo = getMDR("/testData/galileoM7"); + IQueryResult result = repo.query(new QLContextQuery(IInstallableUnit.class, // + "select(x | x.id == $0 && x.version == $1).traverse(parent | select(" + // + "child | parent.requiredCapabilities.exists(rc | child ~= rc)))", // + "org.eclipse.sdk.feature.group", Version.create("3.5.0.v20090423-7Q7bA7DPR-wM38__Q4iRsmx9z0KOjbpx3AbyvXd-Uq7J2")), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 463); + } + + public void testTraverseWithIndex() throws Exception { + IMetadataRepository repo = getMDR("/testData/galileoM7"); + IQueryResult result = repo.query(// + new QLContextQuery(IInstallableUnit.class, "" + // + "select(x | x.id == $0 && x.version == $1).traverse(capabilityIndex(everything), _, { index, parent |" + // + "index.satisfiesAny(parent.requiredCapabilities)})", // + "org.eclipse.sdk.feature.group",// + Version.create("3.5.0.v20090423-7Q7bA7DPR-wM38__Q4iRsmx9z0KOjbpx3AbyvXd-Uq7J2")),// + new NullProgressMonitor()); + assertEquals(queryResultSize(result), 463); + } + + public void testTraverseWithIndexAndFilter() throws Exception { + // Add some filtering of requirements + Map env = new Hashtable(); + env.put("osgi.os", "linux"); + env.put("osgi.ws", "gtk"); + env.put("osgi.arch", "x86"); + + IContextExpression expr = factory.contextExpression(IInstallableUnit.class, parser.parseQuery("" + // + "select(x | x.id == $0 && x.version == $1).traverse(capabilityIndex(everything), _, { index, parent |" + // + "index.satisfiesAny(parent.requiredCapabilities.select(rc | rc.filter == null || $2 ~= rc.filter))})"), "org.eclipse.sdk.feature.group", Version.create("3.5.0.v20090423-7Q7bA7DPR-wM38__Q4iRsmx9z0KOjbpx3AbyvXd-Uq7J2"), env); + + QLContextQuery query = new QLContextQuery(expr); + IMetadataRepository repo = getMDR("/testData/galileoM7"); + IQueryResult result = repo.query(query, new NullProgressMonitor()); + assertEquals(queryResultSize(result), 411); + } + + public void testCommonRequirements() throws Exception { + // Add some filtering of requirements + + IMetadataRepository repo = getMDR("/testData/galileoM7"); + QLContextQuery indexQuery = new QLContextQuery(IInstallableUnit.class, "capabilityIndex(everything)"); + Object index = indexQuery.query(QL.newQueryContext(repo)); + + Map env = new Hashtable(); + env.put("osgi.os", "linux"); + env.put("osgi.ws", "gtk"); + env.put("osgi.arch", "x86"); + + IContextExpression expr = factory.contextExpression(IInstallableUnit.class, parser.parseQuery("" + // + "select(x | x.id == $0 && x.version == $1).traverse(parent |" + // + "$5.satisfiesAny(parent.requiredCapabilities.select(rc | rc.filter == null || $4 ~= rc.filter))).intersect(" + // + "select(x | x.id == $2 && x.version == $3).traverse(parent |" + // + "$5.satisfiesAny(parent.requiredCapabilities.select(rc | rc.filter == null || $4 ~= rc.filter))))"), // + "org.eclipse.pde.feature.group", // + Version.create("3.5.0.v20090123-7Z7YF8NFE-z0VXhWU26Hu8gY"), // + "org.eclipse.gmf.feature.group", // + Version.create("1.1.1.v20090114-0940-7d8B0FXwkKwFanGNHeHHq8ymBgZ"), // + env,// + index); + + QLContextQuery query = new QLContextQuery(expr); + IQueryResult result = repo.query(query, new NullProgressMonitor()); + assertEquals(queryResultSize(result), 184); + } + + public void testMatchQueryInjectionInPredicate() throws Exception { + IMetadataRepository repo = getMDR("/testData/galileoM7"); + IMatchExpression expr = factory.matchExpression(parser.parse("iquery($0) || iquery($1)"), new MatchQuery() { + @Override + public boolean isMatch(Object candidate) { + return "true".equals(((IInstallableUnit) candidate).getProperty("org.eclipse.equinox.p2.type.category")); + } + }, new MatchQuery() { + @Override + public boolean isMatch(Object candidate) { + return "true".equals(((IInstallableUnit) candidate).getProperty("org.eclipse.equinox.p2.type.group")); + } + }); + IQueryResult result = repo.query(new QLMatchQuery(IInstallableUnit.class, expr), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 497); + } + + public void testMatchQueryInjectionInContext() throws Exception { + IMetadataRepository repo = getMDR("/testData/galileoM7"); + IContextExpression expr = factory.contextExpression(IInstallableUnit.class, parser.parseQuery("select(x | iquery($0, x) || iquery($1, x)).latest()"), new MatchQuery() { + @Override + public boolean isMatch(Object candidate) { + return "true".equals(((IInstallableUnit) candidate).getProperty("org.eclipse.equinox.p2.type.category")); + } + }, new MatchQuery() { + @Override + public boolean isMatch(Object candidate) { + return "true".equals(((IInstallableUnit) candidate).getProperty("org.eclipse.equinox.p2.type.group")); + } + }); + IQueryResult result = repo.query(new QLContextQuery(expr), new NullProgressMonitor()); + assertEquals(queryResultSize(result), 497); + } + + public void testTranslations() { + File foo_fragment = new File(TestActivator.getTestDataFolder(), "FragmentPublisherTest/foo.fragment");//$NON-NLS-1$ + File foo = new File(TestActivator.getTestDataFolder(), "FragmentPublisherTest/foo");//$NON-NLS-1$ + BundlesAction bundlesAction = new BundlesAction(new File[] {foo_fragment}); + PublisherInfo info = new PublisherInfo(); + PublisherResult results = new PublisherResult(); + + bundlesAction.perform(info, results, new NullProgressMonitor()); + Collection ius = results.getIUs(null, null); + assertEquals("1.0", 1, ius.size()); + + info = new PublisherInfo(); + results = new PublisherResult(); + bundlesAction = new BundlesAction(new File[] {foo}); + bundlesAction.perform(info, results, new NullProgressMonitor()); + + bundlesAction = new BundlesAction(new File[] {foo_fragment}); + bundlesAction.perform(info, results, new NullProgressMonitor()); + ius = results.getIUs(null, null); + assertEquals("2.0", 3, ius.size()); + QueryableArray queryableArray = new QueryableArray((IInstallableUnit[]) ius.toArray(new IInstallableUnit[ius.size()])); + IQueryResult result = queryableArray.query(new InstallableUnitQuery("foo"), null); + assertEquals("2.1", 1, queryResultSize(result)); + + QLMatchQuery lq = new QLMatchQuery(IInstallableUnit.class, "translations['org.eclipse.equinox.p2.name'] ~= /German*/"); + lq.setLocale(Locale.GERMAN); + Iterator itr = queryableArray.query(lq, new NullProgressMonitor()).iterator(); + assertTrue(itr.hasNext()); + assertEquals("2.8", "foo", ((IInstallableUnit) itr.next()).getId()); + assertFalse(itr.hasNext()); + } + + private IMetadataRepository getMDR(String uri) throws Exception { + URI metadataRepo = getTestData("1.1", uri).toURI(); + + IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); + assertNotNull(metadataManager); + + return metadataManager.loadRepository(metadataRepo, new NullProgressMonitor()); + } +} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/PerformanceTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/PerformanceTest.java new file mode 100644 index 000000000..bcc264b43 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/PerformanceTest.java @@ -0,0 +1,187 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.tests.ql; + +import java.net.URI; +import java.util.*; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.internal.p2.director.QueryableArray; +import org.eclipse.equinox.internal.p2.director.Slicer; +import org.eclipse.equinox.internal.p2.director.app.Activator; +import org.eclipse.equinox.internal.p2.metadata.query.IUPropertyQuery; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.ExpressionQuery; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.ql.*; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; + +public class PerformanceTest extends AbstractProvisioningTest { + public void testCapabilityQueryPerformance() throws Exception { + + IMetadataRepository repo = getMDR("/testData/galileoM7"); + + IRequirement capability = MetadataFactory.createRequiredCapability("org.eclipse.equinox.p2.eclipse.type", "feature", new VersionRange("[1.0.0,2.0.0)"), null, false, false); + QLMatchQuery predicateQuery = new QLMatchQuery(IInstallableUnit.class, "this ~= $0", capability); + IQuery capabilityQuery = new ExpressionQuery(IInstallableUnit.class, capability.getMatches()); + IQueryResult result; + long tradQueryMS = 0; + long exprQueryMS = 0; + + for (int i = 0; i < 5; ++i) { + long start = System.currentTimeMillis(); + for (int idx = 0; idx < 80; ++idx) { + result = repo.query(capabilityQuery, new NullProgressMonitor()); + assertEquals(queryResultSize(result), 487); + } + tradQueryMS += (System.currentTimeMillis() - start); + + start = System.currentTimeMillis(); + for (int idx = 0; idx < 80; ++idx) { + result = repo.query(predicateQuery, new NullProgressMonitor()); + assertEquals(queryResultSize(result), 487); + } + exprQueryMS += (System.currentTimeMillis() - start); + } + System.out.println("CapabilityQuery took: " + tradQueryMS + " milliseconds"); + System.out.println("PredicateQuery took: " + exprQueryMS + " milliseconds"); + System.out.println(); + } + + public void testCapabilityQueryPerformance2() throws Exception { + + IMetadataRepository repo = getMDR("/testData/galileoM7"); + IQueryable qaRepo = new QueryableArray(gatherAvailableInstallableUnits(repo)); + + IRequirement capability = MetadataFactory.createRequiredCapability("org.eclipse.equinox.p2.eclipse.type", "feature", new VersionRange("[1.0.0,2.0.0)"), null, false, false); + QLContextQuery exprQuery = new QLContextQuery(IInstallableUnit.class, "capabilityIndex(everything)"); + IQuery capabilityQuery = new ExpressionQuery(IInstallableUnit.class, capability.getMatches()); + exprQuery = new QLContextQuery(IInstallableUnit.class, "$0.satisfiesAny([$1])", exprQuery.query(QL.newQueryContext(qaRepo)), capability); + IQueryResult result; + long tradQueryMS = 0; + long exprQueryMS = 0; + + for (int i = 0; i < 5; ++i) { + long start = System.currentTimeMillis(); + for (int idx = 0; idx < 80; ++idx) { + result = qaRepo.query(capabilityQuery, new NullProgressMonitor()); + assertEquals(queryResultSize(result), 487); + } + tradQueryMS += (System.currentTimeMillis() - start); + + start = System.currentTimeMillis(); + for (int idx = 0; idx < 80; ++idx) { + result = qaRepo.query(exprQuery, new NullProgressMonitor()); + assertEquals(queryResultSize(result), 487); + } + exprQueryMS += (System.currentTimeMillis() - start); + } + System.out.println("CapabilityQuery took: " + tradQueryMS + " milliseconds"); + System.out.println("PredicateQuery took: " + exprQueryMS + " milliseconds"); + System.out.println(); + } + + public void testIUPropertyQueryPerformance() throws Exception { + + IMetadataRepository repo = getMDR("/testData/galileoM7"); + + IUPropertyQuery propertyQuery = new IUPropertyQuery("df_LT.providerName", "Eclipse.org"); + QLMatchQuery predicateQuery = new QLMatchQuery(IInstallableUnit.class, "properties[$0] == $1", "df_LT.providerName", "Eclipse.org"); + IQueryResult result; + long tradQueryMS = 0; + long exprQueryMS = 0; + + for (int i = 0; i < 5; ++i) { + long start = System.currentTimeMillis(); + for (int idx = 0; idx < 80; ++idx) { + result = repo.query(propertyQuery, new NullProgressMonitor()); + assertEquals(queryResultSize(result), 965); + } + tradQueryMS += (System.currentTimeMillis() - start); + + start = System.currentTimeMillis(); + for (int idx = 0; idx < 80; ++idx) { + result = repo.query(predicateQuery, new NullProgressMonitor()); + assertEquals(queryResultSize(result), 965); + } + exprQueryMS += (System.currentTimeMillis() - start); + } + System.out.println("IUPropertyQuery took: " + tradQueryMS + " milliseconds"); + System.out.println("PredicateQuery took: " + exprQueryMS + " milliseconds"); + System.out.println(); + } + + public void testSlicerPerformance() throws Exception { + Hashtable env = new Hashtable(); + env.put("osgi.os", "linux"); + env.put("osgi.ws", "gtk"); + env.put("osgi.arch", "x86"); + + IMetadataRepository repo = getMDR("/testData/galileoM7"); + IQueryResult r = repo.query(new InstallableUnitQuery("org.eclipse.sdk.feature.group", Version.create("3.5.0.v20090423-7Q7bA7DPR-wM38__Q4iRsmx9z0KOjbpx3AbyvXd-Uq7J2")), new NullProgressMonitor()); + Iterator itor = r.iterator(); + assertTrue(itor.hasNext()); + IInstallableUnit[] roots = new IInstallableUnit[] {(IInstallableUnit) itor.next()}; + + IQuery query = new QLContextQuery(IInstallableUnit.class, "" + // + "$0.traverse(set(), capabilityIndex(everything), _, {rqCache, index, parent | " + // + "index.satisfiesAny(parent.requiredCapabilities.unique(rqCache).select(rc | rc.filter == null || $1 ~= rc.filter))})", roots, env); + + long sliceTime = 0; + long traverseTime = 0; + IQueryable slice = null; + for (int idx = 0; idx < 100; ++idx) { + long startTime = System.currentTimeMillis(); + r = repo.query(query, new NullProgressMonitor()); + traverseTime += (System.currentTimeMillis() - startTime); + assertEquals(queryResultSize(r), 411); + + startTime = System.currentTimeMillis(); + Slicer slicer = new Slicer(new QueryableArray(gatherAvailableInstallableUnits(repo)), env, false); + slice = slicer.slice(roots, new NullProgressMonitor()); + sliceTime += (System.currentTimeMillis() - startTime); + } + // Check the size of the last slice to verify that it's the same as the traverse size + r = slice.query(new MatchQuery() { + public boolean isMatch(Object value) { + return true; + } + }, new NullProgressMonitor()); + assertEquals(queryResultSize(r), 411); + + System.out.print("100 * Slicing took: "); + System.out.println(sliceTime); + System.out.print("100 * Indexed Traverse expression took: "); + System.out.println(traverseTime); + System.out.println(); + } + + private IMetadataRepository getMDR(String uri) throws Exception { + URI metadataRepo = getTestData("1.1", uri).toURI(); + + IMetadataRepositoryManager metadataManager = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); + assertNotNull(metadataManager); + + return metadataManager.loadRepository(metadataRepo, new NullProgressMonitor()); + } + + private IInstallableUnit[] gatherAvailableInstallableUnits(IQueryable queryable) { + ArrayList list = new ArrayList(); + IQueryResult matches = queryable.query(InstallableUnitQuery.ANY, null); + for (Iterator it = matches.iterator(); it.hasNext();) + list.add(it.next()); + return (IInstallableUnit[]) list.toArray(new IInstallableUnit[list.size()]); + } +} diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/TestQueryReimplementation.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/TestQueryReimplementation.java new file mode 100644 index 000000000..9a51eda88 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/ql/TestQueryReimplementation.java @@ -0,0 +1,146 @@ +/******************************************************************************* + * Copyright (c) 2009 Cloudsmith Inc. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Cloudsmith Inc. - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.tests.ql; + +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.expression.IExpression; +import org.eclipse.equinox.p2.metadata.expression.IExpressionParser; +import org.eclipse.equinox.p2.ql.*; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; + +public class TestQueryReimplementation extends AbstractProvisioningTest { + + public static class UpdateQuery extends QLMatchQuery { + private static final IExpression expr1; + private static final IExpression expr2; + + static { + IQLParser parser = QL.newParser(); + + // This expression is used in case the updateFrom is an IInstallableUnitPatch + // + expr1 = parser.parse("$0 ~= updateDescriptor && ($0.id != id || $0.version < version)"); + + // When updateFrom is not an IInstallableUnitPatch, we need to do one of two things depending + // on if the current item is an InstallableUnitPatch or not. + // + expr2 = parser.parse("this ~= class('org.eclipse.equinox.p2.metadata.IInstallableUnitPatch')" + // + "? $0 ~= lifeCycle" + // + ": $0 ~= updateDescriptor && ($0.id != id || $0.version < version)"); + } + + public UpdateQuery(IInstallableUnit updateFrom) { + super(IInstallableUnit.class, QL.getFactory().matchExpression(updateFrom instanceof IInstallableUnitPatch ? expr1 : expr2, updateFrom, IInstallableUnitPatch.class)); + } + } + + public static class IUPropertyQuery extends QLMatchQuery { + private static final IExpression expr = QL.newParser().parse("properties[$0] == $1"); + + public IUPropertyQuery(String propertyName, String propertyValue) { + super(IInstallableUnit.class, QL.getFactory().matchExpression(expr, propertyName, propertyValue)); + } + } + + public static class InstallableUnitQuery extends QLMatchQuery { + /** + * A convenience query that will match any {@link IInstallableUnit} + * it encounters. + */ + public static final QLMatchQuery ANY = new QLMatchQuery(IInstallableUnit.class, ""); + + private static final IExpression idVersionQuery; + private static final IExpression idRangeQuery; + + static { + IExpressionParser parser = QL.newParser(); + idVersionQuery = parser.parse("($0 == null || $0 == id) && ($1 == null || $1 == version)"); + idRangeQuery = parser.parse("($0 == null || $0 == id) && ($1 == null || version ~= $1)"); + } + + /** + * Creates a query that will match any {@link IInstallableUnit} with the given + * id, regardless of version. + * + * @param id The installable unit id to match, or null to match any id + */ + public InstallableUnitQuery(String id) { + this(id, (Version) null); + } + + /** + * Creates a query that will match any {@link IInstallableUnit} with the given + * id, and whose version falls in the provided range. + * + * @param id The installable unit id to match, or null to match any id + * @param range The version range to match + */ + public InstallableUnitQuery(String id, VersionRange range) { + super(IInstallableUnit.class, QL.getFactory().matchExpression(idRangeQuery, id, range)); + } + + /** + * Creates a query that will match any {@link IInstallableUnit} with the given + * id and version. + * + * @param id The installable unit id to match, or null to match any id + * @param version The precise version that a matching unit must have + */ + public InstallableUnitQuery(String id, Version version) { + super(IInstallableUnit.class, QL.getFactory().matchExpression(idVersionQuery, id, version)); + } + + /** + * Creates a query that will match any {@link IInstallableUnit} with the given + * id and version. + * + * @param versionedId The precise id/version combination that a matching unit must have + */ + public InstallableUnitQuery(IVersionedId versionedId) { + this(versionedId.getId(), versionedId.getVersion()); + } + } + + private IInstallableUnit a1; + private IInstallableUnit updateOfA; + private IInstallableUnit a11; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + a1 = createIU("A", Version.create("2.0.0")); + IUpdateDescriptor update = MetadataFactory.createUpdateDescriptor("A", new VersionRange("[2.0.0, 2.0.0]"), 0, "update description"); + updateOfA = createIU("UpdateA", Version.createOSGi(1, 0, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, null, NO_TP_DATA, false, update, NO_REQUIRES); + a11 = createIUUpdate(); + } + + public void testUpdateWithDifferentId() { + IMetadataRepository repo = createTestMetdataRepository(new IInstallableUnit[] {a1, updateOfA}); + IQueryResult c = repo.query(new UpdateQuery(a1), null); + assertEquals(1, queryResultSize(c)); + assertEquals(updateOfA, c.iterator().next()); + } + + public void testWithSuperiorVersion() { + IMetadataRepository repo2 = createTestMetdataRepository(new IInstallableUnit[] {a11, a1}); + IQueryResult c2 = repo2.query(new UpdateQuery(a1), null); + assertEquals(1, queryResultSize(c2)); + assertEquals(a11, c2.iterator().next()); + } + + private IInstallableUnit createIUUpdate() { + return createIU("A", Version.create("2.1.0"), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, false, MetadataFactory.createUpdateDescriptor("A", new VersionRange("[2.0.0, 2.1.0]"), 0, "update description"), null); + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AbstractReconcilerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AbstractReconcilerTest.java index d81126d8e..1305a11f0 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AbstractReconcilerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/AbstractReconcilerTest.java @@ -10,6 +10,8 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.reconciler.dropins; +import org.eclipse.equinox.p2.metadata.Version; + import java.io.*; import java.net.MalformedURLException; import java.net.URL; @@ -20,12 +22,11 @@ import org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry; import org.eclipse.equinox.internal.p2.engine.SurrogateProfileHandler; import org.eclipse.equinox.internal.p2.update.*; import org.eclipse.equinox.internal.p2.updatesite.Activator; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.eclipse.osgi.service.datalocation.Location; @@ -164,7 +165,7 @@ public class AbstractReconcilerTest extends AbstractProvisioningTest { File file = null; if (propertyToPlatformArchive != null) { property = getValueFor(propertyToPlatformArchive); - String message = "Need to set the " + "\"" + property + "\" system property with a valid path to the platform binary drop or copy the archive to be a sibling of the install folder."; + String message = "Need to set the " + "\"" + propertyToPlatformArchive + "\" system property with a valid path to the platform binary drop or copy the archive to be a sibling of the install folder."; if (property == null) { fail(message); } @@ -528,8 +529,8 @@ public class AbstractReconcilerTest extends AbstractProvisioningTest { SimpleProfileRegistry registry = new SimpleProfileRegistry(location, new SurrogateProfileHandler(), false); IProfile[] profiles = registry.getProfiles(); assertEquals("1.0 Should only be one profile in registry.", 1, profiles.length); - Collector collector = profiles[0].query(new InstallableUnitQuery(id, new Version(version)), new Collector(), null); - return !collector.isEmpty(); + IQueryResult queryResult = profiles[0].query(new InstallableUnitQuery(id, Version.create(version)), null); + return !queryResult.isEmpty(); } public IInstallableUnit getRemoteIU(String id, String version) { @@ -537,9 +538,9 @@ public class AbstractReconcilerTest extends AbstractProvisioningTest { SimpleProfileRegistry registry = new SimpleProfileRegistry(location, new SurrogateProfileHandler(), false); IProfile[] profiles = registry.getProfiles(); assertEquals("1.0 Should only be one profile in registry.", 1, profiles.length); - Collector collector = profiles[0].query(new InstallableUnitQuery(id, new Version(version)), new Collector(), null); - assertEquals("1.1 Should not have more than one IU wth the same ID and version.", 1, collector.size()); - return (IInstallableUnit) collector.iterator().next(); + IQueryResult queryResult = profiles[0].query(new InstallableUnitQuery(id, Version.create(version)), null); + assertEquals("1.1 Should not have more than one IU wth the same ID and version.", 1, queryResultSize(queryResult)); + return (IInstallableUnit) queryResult.iterator().next(); } public int runInitialize(String message) { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/BasicTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/BasicTests.java index 9e9f316b8..a1e8785f2 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/BasicTests.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/BasicTests.java @@ -13,7 +13,7 @@ package org.eclipse.equinox.p2.tests.reconciler.dropins; import java.io.File; import junit.framework.Test; import junit.framework.TestSuite; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; //- add new //- remove only diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/ConfigurationTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/ConfigurationTests.java index 71d8dcecd..bf1cbfd0c 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/ConfigurationTests.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/reconciler/dropins/ConfigurationTests.java @@ -15,7 +15,7 @@ import java.util.Iterator; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.equinox.internal.p2.update.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; /* * Tests related to the platform configuration before and after reconciliation. diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/NTLMTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/NTLMTest.java index e6f1d4227..de683f732 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/NTLMTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/NTLMTest.java @@ -11,8 +11,8 @@ package org.eclipse.equinox.p2.tests.repository; import java.net.URI; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.equinox.p2.tests.TestActivator; import org.eclipse.equinox.p2.tests.testserver.helper.AbstractTestServerClientCase; import org.osgi.framework.ServiceReference; @@ -27,7 +27,7 @@ public class NTLMTest extends AbstractTestServerClientCase { public void setUp() throws Exception { super.setUp(); - ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.class.getName()); + ServiceReference sr2 = TestActivator.context.getServiceReference(IMetadataRepositoryManager.SERVICE_NAME); mgr = (IMetadataRepositoryManager) TestActivator.context.getService(sr2); if (mgr == null) { throw new RuntimeException("Repository manager could not be loaded"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/TimeoutTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/TimeoutTest.java index b7a98d8bf..dacbeb2af 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/TimeoutTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/TimeoutTest.java @@ -14,7 +14,7 @@ import java.security.cert.Certificate; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.repository.RepositoryTransport; import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.core.ProvisionException; import org.eclipse.equinox.p2.tests.metadata.repository.AllServerTests; import org.eclipse.equinox.p2.tests.testserver.helper.AbstractTestServerClientCase; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddJVMArgumentActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddJVMArgumentActionTest.java index 4b620deaa..6e51a033a 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddJVMArgumentActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddJVMArgumentActionTest.java @@ -15,8 +15,8 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstant import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.AddJVMArgumentAction; import org.eclipse.equinox.internal.provisional.frameworkadmin.LauncherData; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class AddJVMArgumentActionTest extends AbstractProvisioningTest { @@ -39,10 +39,11 @@ public class AddJVMArgumentActionTest extends AbstractProvisioningTest { tempDir.mkdirs(); parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); Properties profileProperties = new Properties(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, getTempFolder().toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); InstallableUnitOperand operand = new InstallableUnitOperand(null, createIU("test")); touchpoint.initializePhase(null, profile, "test", parameters); parameters.put("iu", operand.second()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddProgramArgumentActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddProgramArgumentActionTest.java index 3653f7553..e3d0d6465 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddProgramArgumentActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddProgramArgumentActionTest.java @@ -17,13 +17,13 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.AddProgramArgumentAction; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -40,10 +40,11 @@ public class AddProgramArgumentActionTest extends AbstractProvisioningTest { public void testExecuteUndo() { Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); Properties profileProperties = new Properties(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, getTempFolder().toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); InstallableUnitOperand operand = new InstallableUnitOperand(null, createIU("test")); touchpoint.initializePhase(null, profile, "test", parameters); parameters.put("iu", operand.second()); @@ -68,9 +69,9 @@ public class AddProgramArgumentActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -84,6 +85,7 @@ public class AddProgramArgumentActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); @@ -120,9 +122,9 @@ public class AddProgramArgumentActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -136,6 +138,7 @@ public class AddProgramArgumentActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); @@ -178,9 +181,9 @@ public class AddProgramArgumentActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -194,6 +197,7 @@ public class AddProgramArgumentActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); @@ -230,9 +234,9 @@ public class AddProgramArgumentActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -246,6 +250,7 @@ public class AddProgramArgumentActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddRepositoryActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddRepositoryActionTest.java index 4a663fc7a..70ffe003e 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddRepositoryActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddRepositoryActionTest.java @@ -10,31 +10,29 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.touchpoint.eclipse; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.preferences.IPreferencesService; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.metadata.TouchpointInstruction; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; +import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.AddRepositoryAction; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.ITouchpointData; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; -import org.eclipse.equinox.p2.tests.TestActivator; import org.osgi.service.prefs.Preferences; /** @@ -73,6 +71,7 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { public void testInvalidEnablement() { Map args = getValidArguments(); + addAgent(args); args.put("enabled", "bogus enablement"); IStatus result = action.execute(args); //Any value other than "true" for enablement results in a disabled repository @@ -80,8 +79,13 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { assertTrue("1.1", !getArtifactRepositoryManager().isEnabled(locationURI)); } + private void addAgent(Map args) { + args.put(ActionConstants.PARM_AGENT, getAgent()); + } + public void testInvalidLocation() { Map args = getValidArguments(); + addAgent(args); args.put("location", "bogus location"); IStatus result = action.execute(args); assertTrue("1.0", !result.isOK()); @@ -89,6 +93,7 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { public void testInvalidType() { Map args = getValidArguments(); + addAgent(args); args.put("type", "bogus type"); IStatus result = action.execute(args); assertTrue("1.0", !result.isOK()); @@ -97,6 +102,7 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { public void testMissingEnablement() { //note enablement is optional, defaults to true Map args = getValidArguments(); + addAgent(args); args.remove("enabled"); IStatus result = action.execute(args); assertTrue("1.0", result.isOK()); @@ -104,6 +110,7 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { public void testMissingType() { Map args = getValidArguments(); + addAgent(args); args.remove("type"); IStatus result = action.execute(args); assertTrue("1.0", !result.isOK()); @@ -116,6 +123,7 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { public void testUndo() { Map args = getValidArguments(); + addAgent(args); IStatus result = action.execute(args); assertTrue("1.0", result.isOK()); @@ -125,6 +133,7 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { public void testMultipleActionAdd() { Map args = getValidArguments(); + addAgent(args); IStatus result = action.execute(args); assertTrue("1.0", result.isOK()); @@ -146,6 +155,7 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { } Map args = getValidArguments(); + addAgent(args); IStatus result = action.execute(args); assertTrue("1.0", result.isOK()); @@ -160,7 +170,7 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { */ public void testFullInstall() { String id = "AddRepositoryActionTest.testFullInstall"; - Version version = new Version(1, 0, 0); + Version version = Version.createOSGi(1, 0, 0); Map instructions = new HashMap(); instructions.put("configure", TouchpointInstruction.encodeAction("addRepository", getValidArguments())); ITouchpointData tpData = MetadataFactory.createTouchpointData(instructions); @@ -177,10 +187,8 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { //check that profile property is set profile = getProfile(id); // Get Preference node associated with the profile - IPreferencesService prefService = (IPreferencesService) ServiceHelper.getService(TestActivator.getContext(), IPreferencesService.class.getName()); - Preferences pref = prefService.getRootNode().node("/profile/" + profile.getProfileId() + "/org.eclipse.equinox.p2.artifact.repository/repositories/" + getKey(TEST_LOCATION)); //$NON-NLS-1$ //$NON-NLS-2$ + Preferences pref = new ProfileScope(getAgentLocation(), profile.getProfileId()).getNode("org.eclipse.equinox.p2.artifact.repository/repositories/" + getKey(TEST_LOCATION)); String value = pref.get(KEY_URI, null); - assertEquals("2.0", value, TEST_LOCATION); } @@ -195,7 +203,7 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { //install the old IU String id = "AddRepositoryActionTest.testUpdate"; - Version version = new Version(1, 0, 0); + Version version = Version.createOSGi(1, 0, 0); IInstallableUnit oldIU = createIU(id, version); IProfile profile = createProfile(id); ProfileChangeRequest request = new ProfileChangeRequest(profile); @@ -207,7 +215,7 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { assertTrue("1.1", !getArtifactRepositoryManager().contains(locationURI)); //define new IU - version = new Version(1, 1, 0); + version = Version.createOSGi(1, 1, 0); Map instructions = new HashMap(); instructions.put("configure", TouchpointInstruction.encodeAction("addRepository", getValidArguments())); ITouchpointData tpData = MetadataFactory.createTouchpointData(instructions); @@ -215,7 +223,7 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { //perform the update and install an ordinary bundle IMetadataRepository repo = getMetadataRepositoryManager().loadRepository(site, getMonitor()); - IInstallableUnit bundle = (IInstallableUnit) repo.query(new InstallableUnitQuery("aBundle"), new Collector(), getMonitor()).iterator().next(); + IInstallableUnit bundle = (IInstallableUnit) repo.query(new InstallableUnitQuery("aBundle"), getMonitor()).iterator().next(); request = new ProfileChangeRequest(profile); final IInstallableUnit[] newIUs = new IInstallableUnit[] {newIU, bundle}; request.addInstallableUnits(newIUs); @@ -227,14 +235,13 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { //check that the artifact is still there profile = getProfile(id); - IArtifactRepository artifacts = getArtifactRepositoryManager().loadRepository(Util.getBundlePoolLocation(profile), getMonitor()); - assertEquals("3.0", 1, artifacts.getArtifactKeys().length); + IArtifactRepository artifacts = getArtifactRepositoryManager().loadRepository(Util.getBundlePoolLocation(getAgent(), profile), getMonitor()); + assertEquals("3.0", 1, getArtifactKeyCount(artifacts)); //check that profile property is set assertProfileContains("3.1", profile, newIUs); // Get Preference node associated with the profile - IPreferencesService prefService = (IPreferencesService) ServiceHelper.getService(TestActivator.getContext(), IPreferencesService.class.getName()); - Preferences pref = prefService.getRootNode().node("/profile/" + profile.getProfileId() + "/org.eclipse.equinox.p2.artifact.repository/repositories/" + getKey(TEST_LOCATION)); //$NON-NLS-1$ //$NON-NLS-2$ + Preferences pref = new ProfileScope(getAgentLocation(), profile.getProfileId()).getNode("org.eclipse.equinox.p2.artifact.repository/repositories/" + getKey(TEST_LOCATION)); String value = pref.get(KEY_URI, null); assertEquals("3.2", value, TEST_LOCATION); @@ -252,12 +259,8 @@ public class AddRepositoryActionTest extends AbstractProvisioningTest { } private boolean locationExists(IProfile profile, String location) { - IPreferencesService prefService = (IPreferencesService) ServiceHelper.getService(TestActivator.getContext(), IPreferencesService.class.getName()); - Preferences pref; - if (profile != null) - pref = prefService.getRootNode().node("/profile/" + profile.getProfileId() + "/org.eclipse.equinox.p2.artifactRepositories/repositories/" + getKey(location)); - else - pref = prefService.getRootNode().node("/profile/_SELF_/org.eclipse.equinox.p2.artifact.repository/repositories/" + getKey(location)); + final String profileId = profile != null ? profile.getProfileId() : IProfileRegistry.SELF; + Preferences pref = new ProfileScope(getAgentLocation(), profileId).getNode("org.eclipse.equinox.p2.artifact.repository/repositories/" + getKey(location)); if (location.equals(pref.get(KEY_URI, null))) return true; return false; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddSourceBundleActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddSourceBundleActionTest.java index 45915d137..98b36bbe5 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddSourceBundleActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AddSourceBundleActionTest.java @@ -18,13 +18,13 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.*; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.AddSourceBundleAction; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -44,9 +44,9 @@ public class AddSourceBundleActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi.source_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -60,6 +60,7 @@ public class AddSourceBundleActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AllTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AllTests.java index a963f6db9..c2edb992d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AllTests.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/AllTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008-2009 IBM Corporation and others. + * Copyright (c) 2008, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,7 +13,7 @@ package org.eclipse.equinox.p2.tests.touchpoint.eclipse; import junit.framework.*; /** - * Performs all automated director tests. + * Performs all automated touchpoint tests. */ public class AllTests extends TestCase { diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/CheckTrustActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/CheckTrustActionTest.java index 2047afed0..a34899291 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/CheckTrustActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/CheckTrustActionTest.java @@ -12,18 +12,18 @@ package org.eclipse.equinox.p2.tests.touchpoint.eclipse; import java.io.File; import java.util.*; +import org.eclipse.equinox.internal.p2.engine.phases.CheckTrust; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.CheckTrustAction; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.engine.phases.CheckTrust; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -43,9 +43,9 @@ public class CheckTrustActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -59,6 +59,7 @@ public class CheckTrustActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); parameters.put(CheckTrust.PARM_ARTIFACT_FILES, new ArrayList()); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/ChmodActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/ChmodActionTest.java index 2674d9c46..e2473ff4e 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/ChmodActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/ChmodActionTest.java @@ -18,13 +18,13 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ChmodAction; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -43,7 +43,7 @@ public class ChmodActionTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); - IProfile profile = createProfile("testExecuteUndo", null, profileProperties); + IProfile profile = createProfile("testExecuteUndo", profileProperties); File zipSource = getTestData("1.0", "/testData/nativeTouchpoint/a.zip"); File zipTarget = new File(installFolder, "a.zip"); @@ -54,6 +54,7 @@ public class ChmodActionTest extends AbstractProvisioningTest { copy("3.0", zipSource, zipTarget2); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "testExecuteUndo", parameters); @@ -108,9 +109,9 @@ public class ChmodActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File dirBundleSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/directoryBased_1.0.0"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -124,6 +125,7 @@ public class ChmodActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); @@ -185,9 +187,9 @@ public class ChmodActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File dirBundleSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/directoryBased_1.0.0"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -201,6 +203,7 @@ public class ChmodActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/CollectActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/CollectActionTest.java index 46ff1201b..858b53db7 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/CollectActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/CollectActionTest.java @@ -12,17 +12,17 @@ package org.eclipse.equinox.p2.tests.touchpoint.eclipse; import java.io.File; import java.util.*; +import org.eclipse.equinox.internal.p2.engine.phases.Collect; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.CollectAction; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.engine.phases.Collect; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRequest; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -41,10 +41,10 @@ public class CollectActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); // still want side-effect - Util.getBundlePoolRepository(profile); + Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); @@ -60,8 +60,9 @@ public class CollectActionTest extends AbstractProvisioningTest { IInstallableUnit iu = createBundleIU(bundleDescription, osgiTarget.isDirectory(), key); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); - parameters.put(Collect.PARM_ARTIFACT_REQUESTS, new ArrayList()); + parameters.put(Collect.PARM_ARTIFACT_REQUESTS, new ArrayList()); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); InstallableUnitOperand operand = new InstallableUnitOperand(null, iu); @@ -70,7 +71,7 @@ public class CollectActionTest extends AbstractProvisioningTest { parameters.put(ActionConstants.PARM_OPERAND, operand); parameters = Collections.unmodifiableMap(parameters); - List requests = (List) parameters.get(Collect.PARM_ARTIFACT_REQUESTS); + List requests = (List) parameters.get(Collect.PARM_ARTIFACT_REQUESTS); assertFalse(hasRequest(requests, key)); CollectAction action = new CollectAction(); action.execute(parameters); @@ -80,9 +81,8 @@ public class CollectActionTest extends AbstractProvisioningTest { assertTrue(hasRequest(requests, key)); } - private boolean hasRequest(List requests, IArtifactKey key) { - for (Iterator iterator = requests.iterator(); iterator.hasNext();) { - IArtifactRequest[] request = (IArtifactRequest[]) iterator.next(); + private boolean hasRequest(List requests, IArtifactKey key) { + for (IArtifactRequest[] request : requests) { for (int i = 0; i < request.length; i++) { if (key.equals(request[i].getArtifactKey())) return true; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/EclipseTouchpointTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/EclipseTouchpointTest.java index ee708dac8..a2ea89d1d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/EclipseTouchpointTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/EclipseTouchpointTest.java @@ -16,17 +16,18 @@ import java.util.*; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; +import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; +import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; @@ -48,6 +49,7 @@ public class EclipseTouchpointTest extends AbstractProvisioningTest { Map parameters = new HashMap(); IProfile profile = createProfile("test"); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); touchpoint.initializePhase(null, profile, "test", parameters); Object manipulator = parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); @@ -58,6 +60,7 @@ public class EclipseTouchpointTest extends AbstractProvisioningTest { // checking that the manipulator is carried from phases to phase parameters.clear(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); touchpoint.initializePhase(null, profile, "test2", parameters); Object testManipulator = parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); assertEquals(manipulator, testManipulator); @@ -66,6 +69,7 @@ public class EclipseTouchpointTest extends AbstractProvisioningTest { // re: "uninstall" this is necessary for now for coverage until we have formal commit and rollback events // this test should be revisited then parameters.clear(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); touchpoint.initializePhase(null, profile, "uninstall", parameters); testManipulator = parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); assertEquals(manipulator, testManipulator); @@ -96,8 +100,8 @@ public class EclipseTouchpointTest extends AbstractProvisioningTest { URL location = site.toURL(); properties.put("org.eclipse.equinox.p2.cache.extensions", location.toString() + "|" + spacesLocation.toString()); - IProfile profile = createProfile("testBug262073", null, properties); - AggregatedBundleRepository repo = (AggregatedBundleRepository) Util.getAggregatedBundleRepository(profile); + IProfile profile = createProfile("testBug262073", properties); + AggregatedBundleRepository repo = (AggregatedBundleRepository) Util.getAggregatedBundleRepository(getAgent(), profile); Collection repos = repo.testGetBundleRepositories(); assertEquals("1.0", 3, repos.size()); } @@ -118,9 +122,9 @@ public class EclipseTouchpointTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -132,7 +136,7 @@ public class EclipseTouchpointTest extends AbstractProvisioningTest { IArtifactDescriptor descriptor = PublisherHelper.createArtifactDescriptor(key, osgiTarget); bundlePool.addDescriptor(descriptor); - Properties extraProperties = new Properties(); + Map extraProperties = new HashMap(); extraProperties.put(IInstallableUnit.PROP_PARTIAL_IU, Boolean.TRUE.toString()); Dictionary mockManifest = new Properties(); @@ -147,7 +151,7 @@ public class EclipseTouchpointTest extends AbstractProvisioningTest { IInstallableUnit iu = bundleIUs[0]; assertTrue(Boolean.valueOf(iu.getProperty(IInstallableUnit.PROP_PARTIAL_IU)).booleanValue()); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); - IInstallableUnit fullIU = touchpoint.prepareIU(iu, key, profile); + IInstallableUnit fullIU = touchpoint.prepareIU(getAgent(), profile, iu, key); assertFalse(Boolean.valueOf(fullIU.getProperty(IInstallableUnit.PROP_PARTIAL_IU)).booleanValue()); } @@ -156,9 +160,9 @@ public class EclipseTouchpointTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -170,7 +174,7 @@ public class EclipseTouchpointTest extends AbstractProvisioningTest { IArtifactDescriptor descriptor = PublisherHelper.createArtifactDescriptor(key, osgiTarget); bundlePool.addDescriptor(descriptor); - Properties extraProperties = new Properties(); + Map extraProperties = new HashMap(); extraProperties.put(IInstallableUnit.PROP_PARTIAL_IU, Boolean.TRUE.toString()); Dictionary mockManifest = new Properties(); @@ -185,22 +189,20 @@ public class EclipseTouchpointTest extends AbstractProvisioningTest { IInstallableUnit iu = bundleIUs[0]; assertTrue(Boolean.valueOf(iu.getProperty(IInstallableUnit.PROP_PARTIAL_IU)).booleanValue()); - Iterator iterator = profile.query(new InstallableUnitQuery(iu.getId()), new Collector(), null).iterator(); + Iterator iterator = profile.query(new InstallableUnitQuery(iu.getId()), null).iterator(); assertFalse(iterator.hasNext()); - PhaseSet phaseSet = new DefaultPhaseSet(); - InstallableUnitOperand op = new InstallableUnitOperand(null, iu); InstallableUnitOperand[] operands = new InstallableUnitOperand[] {op}; ServiceReference engineRef = TestActivator.getContext().getServiceReference(IEngine.SERVICE_NAME); IEngine engine = (IEngine) TestActivator.getContext().getService(engineRef); - IStatus result = engine.perform(profile, phaseSet, operands, null, new NullProgressMonitor()); + IStatus result = engine.perform(engine.createCustomPlan(profile, operands, null), new NullProgressMonitor()); assertTrue(result.isOK()); engine = null; TestActivator.getContext().ungetService(engineRef); - iterator = profile.query(new InstallableUnitQuery(iu.getId()), new Collector(), null).iterator(); + iterator = profile.query(new InstallableUnitQuery(iu.getId()), null).iterator(); assertTrue(iterator.hasNext()); IInstallableUnit installedIU = (IInstallableUnit) iterator.next(); assertTrue(installedIU.getId().equals(iu.getId())); @@ -213,25 +215,25 @@ public class EclipseTouchpointTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); URI site = getTestData("0.1", "/testData/updatesite/site").toURI(); getMetadataRepositoryManager().addRepository(site); getArtifactRepositoryManager().addRepository(site); IMetadataRepository repo = getMetadataRepositoryManager().loadRepository(site, getMonitor()); - IInstallableUnit iu = (IInstallableUnit) repo.query(new InstallableUnitQuery("test.bundle"), new Collector(), getMonitor()).iterator().next(); + IInstallableUnit iu = (IInstallableUnit) repo.query(new InstallableUnitQuery("test.bundle"), getMonitor()).iterator().next(); assertNotNull(iu); - profile = createProfile("test", null, profileProperties); + profile = createProfile("test", profileProperties); ProfileChangeRequest request = new ProfileChangeRequest(profile); final IInstallableUnit[] newIUs = new IInstallableUnit[] {iu}; request.addInstallableUnits(newIUs); IPlanner planner = createPlanner(); - ProvisioningPlan plan = planner.getProvisioningPlan(request, new ProvisioningContext(), new NullProgressMonitor()); + IProvisioningPlan plan = planner.getProvisioningPlan(request, new ProvisioningContext(), new NullProgressMonitor()); assertTrue("1.0", plan.getStatus().isOK()); - IStatus result = createEngine().perform(profile, new DefaultPhaseSet(), plan.getOperands(), new ProvisioningContext(), getMonitor()); + IStatus result = createEngine().perform(plan, getMonitor()); assertFalse("2.0", result.isOK()); } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/InstallBundleActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/InstallBundleActionTest.java index 4feb061ce..82039e1be 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/InstallBundleActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/InstallBundleActionTest.java @@ -19,13 +19,13 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstant import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.InstallBundleAction; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -45,9 +45,9 @@ public class InstallBundleActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -61,6 +61,7 @@ public class InstallBundleActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/InstallFeatureActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/InstallFeatureActionTest.java index 3e3a7725a..9e8df53c8 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/InstallFeatureActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/InstallFeatureActionTest.java @@ -12,18 +12,20 @@ import java.io.File; import java.net.URI; import java.util.*; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactDescriptor; import org.eclipse.equinox.internal.p2.publisher.eclipse.FeatureParser; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.*; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.InstallFeatureAction; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.PublisherInfo; import org.eclipse.equinox.p2.publisher.eclipse.Feature; import org.eclipse.equinox.p2.publisher.eclipse.FeaturesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; @@ -42,9 +44,9 @@ public class InstallFeatureActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File featureSource = getTestData("1.0", "/testData/eclipseTouchpoint/features/org.eclipse.rcp_3.3.0.v20070607-8y8eE8NEbsN3X_fjWS8HPNG"); File targetPlugins = new File(installFolder, "features"); assertTrue(targetPlugins.mkdir()); @@ -55,13 +57,14 @@ public class InstallFeatureActionTest extends AbstractProvisioningTest { Feature feature = parser.parse(featureTarget); IArtifactKey key = FeaturesAction.createFeatureArtifactKey(feature.getId(), feature.getVersion()); - IArtifactDescriptor descriptor = PublisherHelper.createArtifactDescriptor(key, featureTarget); - ((ArtifactDescriptor) descriptor).setRepositoryProperty("artifact.folder", Boolean.TRUE.toString()); + IArtifactDescriptor descriptor = PublisherHelper.createArtifactDescriptor(bundlePool, key, featureTarget); + ((SimpleArtifactDescriptor) descriptor).setRepositoryProperty("artifact.folder", Boolean.TRUE.toString()); IInstallableUnit iu = FeaturesAction.createFeatureJarIU(feature, new PublisherInfo()); bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); @@ -92,9 +95,9 @@ public class InstallFeatureActionTest extends AbstractProvisioningTest { File installFolder = new File(getTempFolder(), "with space"); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File featureSource = getTestData("1.0", "/testData/eclipseTouchpoint/features/org.eclipse.rcp_3.3.0.v20070607-8y8eE8NEbsN3X_fjWS8HPNG"); File targetPlugins = new File(installFolder, "features"); assertTrue(targetPlugins.mkdir()); @@ -105,13 +108,14 @@ public class InstallFeatureActionTest extends AbstractProvisioningTest { Feature feature = parser.parse(featureTarget); IArtifactKey key = FeaturesAction.createFeatureArtifactKey(feature.getId(), feature.getVersion()); - IArtifactDescriptor descriptor = PublisherHelper.createArtifactDescriptor(key, featureTarget); - ((ArtifactDescriptor) descriptor).setRepositoryProperty("artifact.folder", Boolean.TRUE.toString()); + IArtifactDescriptor descriptor = PublisherHelper.createArtifactDescriptor(bundlePool, key, featureTarget); + ((SimpleArtifactDescriptor) descriptor).setRepositoryProperty("artifact.folder", Boolean.TRUE.toString()); IInstallableUnit iu = FeaturesAction.createFeatureJarIU(feature, new PublisherInfo()); bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/JVMArgumentActionLogicTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/JVMArgumentActionLogicTest.java index 0128758d4..570d3c646 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/JVMArgumentActionLogicTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/JVMArgumentActionLogicTest.java @@ -17,8 +17,8 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.*; import org.eclipse.equinox.internal.provisional.frameworkadmin.LauncherData; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class JVMArgumentActionLogicTest extends AbstractProvisioningTest { @@ -33,10 +33,11 @@ public class JVMArgumentActionLogicTest extends AbstractProvisioningTest { tempDir.mkdirs(); parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); Properties profileProperties = new Properties(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, getTempFolder().toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); InstallableUnitOperand operand = new InstallableUnitOperand(null, createIU("test")); touchpoint.initializePhase(null, profile, "test", parameters); parameters.put("iu", operand.second()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/LinkActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/LinkActionTest.java index a500d0949..374def60f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/LinkActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/LinkActionTest.java @@ -16,13 +16,13 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.LinkAction; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.ArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -41,13 +41,14 @@ public class LinkActionTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); File zipSource = getTestData("1.0", "/testData/nativeTouchpoint/a.zip"); File zipTarget = new File(installFolder, "a.zip"); copy("2.0", zipSource, zipTarget); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); @@ -71,9 +72,9 @@ public class LinkActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File dirBundleSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/directoryBased_1.0.0"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -88,6 +89,7 @@ public class LinkActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); @@ -115,9 +117,9 @@ public class LinkActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File dirBundleSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/directoryBased_1.0.0"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -132,6 +134,7 @@ public class LinkActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/MarkStartedActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/MarkStartedActionTest.java index 3e9393493..01affcd21 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/MarkStartedActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/MarkStartedActionTest.java @@ -19,13 +19,13 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstant import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.MarkStartedAction; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -45,9 +45,9 @@ public class MarkStartedActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -61,6 +61,7 @@ public class MarkStartedActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); @@ -90,9 +91,9 @@ public class MarkStartedActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -106,6 +107,7 @@ public class MarkStartedActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); @@ -138,9 +140,9 @@ public class MarkStartedActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi.fragment_1.0.0.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -154,6 +156,7 @@ public class MarkStartedActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveJVMArgumentActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveJVMArgumentActionTest.java index b6fc1813d..b4ade84a9 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveJVMArgumentActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveJVMArgumentActionTest.java @@ -13,8 +13,8 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.RemoveJVMArgumentAction; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class RemoveJVMArgumentActionTest extends AbstractProvisioningTest { @@ -29,10 +29,11 @@ public class RemoveJVMArgumentActionTest extends AbstractProvisioningTest { public void testExecuteUndo() { Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); Properties profileProperties = new Properties(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, getTempFolder().toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); InstallableUnitOperand operand = new InstallableUnitOperand(null, createIU("test")); touchpoint.initializePhase(null, profile, "test", parameters); parameters.put("iu", operand.second()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveProgramArgumentActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveProgramArgumentActionTest.java index 61fe448be..d8741c2ec 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveProgramArgumentActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveProgramArgumentActionTest.java @@ -17,13 +17,13 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.RemoveProgramArgumentAction; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -40,10 +40,11 @@ public class RemoveProgramArgumentActionTest extends AbstractProvisioningTest { public void testExecuteUndo() { Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); Properties profileProperties = new Properties(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, getTempFolder().toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); InstallableUnitOperand operand = new InstallableUnitOperand(null, createIU("test")); touchpoint.initializePhase(null, profile, "test", parameters); parameters.put("iu", operand.second()); @@ -70,9 +71,9 @@ public class RemoveProgramArgumentActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -86,6 +87,7 @@ public class RemoveProgramArgumentActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); @@ -119,15 +121,15 @@ public class RemoveProgramArgumentActionTest extends AbstractProvisioningTest { keyAction.undo(keyParameters); assertTrue(Arrays.asList(manipulator.getLauncherData().getProgramArgs()).contains(resolvedArtifact)); } - + public void testExecuteUndoWithArtifactLocation() { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -141,6 +143,7 @@ public class RemoveProgramArgumentActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveRepositoryActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveRepositoryActionTest.java index 47be8b652..bf11c9bde 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveRepositoryActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveRepositoryActionTest.java @@ -14,8 +14,9 @@ import java.net.URI; import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.RemoveRepositoryAction; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** @@ -31,6 +32,7 @@ public class RemoveRepositoryActionTest extends AbstractProvisioningTest { */ private Map getValidArguments() { Map args = new HashMap(); + args.put(ActionConstants.PARM_AGENT, getAgent()); args.put("location", TEST_LOCATION); args.put("type", Integer.toString(IRepository.TYPE_ARTIFACT)); args.put("enabled", "true"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveSourceBundleActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveSourceBundleActionTest.java index c21322a94..e62dde8cb 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveSourceBundleActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/RemoveSourceBundleActionTest.java @@ -18,13 +18,13 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.*; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.RemoveSourceBundleAction; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -44,9 +44,9 @@ public class RemoveSourceBundleActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi.source_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -60,6 +60,7 @@ public class RemoveSourceBundleActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetFrameworkDependentPropertyActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetFrameworkDependentPropertyActionTest.java index bb6413cc4..fd3f3a0ef 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetFrameworkDependentPropertyActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetFrameworkDependentPropertyActionTest.java @@ -15,8 +15,8 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.SetProgramPropertyAction; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SetFrameworkDependentPropertyActionTest extends AbstractProvisioningTest { @@ -31,10 +31,11 @@ public class SetFrameworkDependentPropertyActionTest extends AbstractProvisionin public void testExecuteUndo() { Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); Properties profileProperties = new Properties(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, getTempFolder().toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); InstallableUnitOperand operand = new InstallableUnitOperand(null, createIU("test")); touchpoint.initializePhase(null, profile, "test", parameters); parameters.put("iu", operand.second()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetFrameworkIndependentPropertyActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetFrameworkIndependentPropertyActionTest.java index 0e6035650..81def3ffa 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetFrameworkIndependentPropertyActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetFrameworkIndependentPropertyActionTest.java @@ -15,8 +15,8 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.SetProgramPropertyAction; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SetFrameworkIndependentPropertyActionTest extends AbstractProvisioningTest { @@ -31,10 +31,11 @@ public class SetFrameworkIndependentPropertyActionTest extends AbstractProvision public void testExecuteUndo() { Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); Properties profileProperties = new Properties(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, getTempFolder().toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); InstallableUnitOperand operand = new InstallableUnitOperand(null, createIU("test")); touchpoint.initializePhase(null, profile, "test", parameters); parameters.put("iu", operand.second()); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetLauncherNameActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetLauncherNameActionTest.java index e441465cb..8e7c5622d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetLauncherNameActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetLauncherNameActionTest.java @@ -15,8 +15,8 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstant import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.SetLauncherNameAction; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class SetLauncherNameActionTest extends AbstractProvisioningTest { @@ -31,10 +31,11 @@ public class SetLauncherNameActionTest extends AbstractProvisioningTest { public void testExecuteUndo() { Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); Properties profileProperties = new Properties(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, getTempFolder().toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); InstallableUnitOperand operand = new InstallableUnitOperand(null, createIU("test")); touchpoint.initializePhase(null, profile, "test", parameters); parameters.put(ActionConstants.PARM_PROFILE, profile); @@ -57,13 +58,14 @@ public class SetLauncherNameActionTest extends AbstractProvisioningTest { public void testEmptyName() { Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); File tempFolder = getTempFolder(); Properties profileProperties = new Properties(); profileProperties.put(IProfile.PROP_INSTALL_FOLDER, tempFolder.toString()); profileProperties.put(IProfile.PROP_ENVIRONMENTS, "osgi.ws=cocoa,osgi.os=macosx,osgi.arch=x86"); - IProfile profile = createProfile("launcherNameProfile", null, profileProperties); + IProfile profile = createProfile("launcherNameProfile", profileProperties); InstallableUnitOperand operand = new InstallableUnitOperand(null, createIU("test")); touchpoint.initializePhase(null, profile, "test", parameters); @@ -87,7 +89,7 @@ public class SetLauncherNameActionTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); profileProperties.put(IProfile.PROP_INSTALL_FOLDER, tempFolder.toString()); profileProperties.put(IProfile.PROP_ENVIRONMENTS, "osgi.ws=win32,osgi.os=win32,osgi.arch=x86"); - IProfile profile = createProfile("changeNameProfile", null, profileProperties); + IProfile profile = createProfile("changeNameProfile", profileProperties); //profile will start using "eclipse" by default, give it some content and see if it //survives a name change. @@ -98,6 +100,7 @@ public class SetLauncherNameActionTest extends AbstractProvisioningTest { writeBuffer(eclipseIni, ini); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); InstallableUnitOperand operand = new InstallableUnitOperand(null, createIU("test")); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetProgramPropertyActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetProgramPropertyActionTest.java index d8fe777ea..b7b1a7112 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetProgramPropertyActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetProgramPropertyActionTest.java @@ -17,13 +17,13 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.SetProgramPropertyAction; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -40,10 +40,11 @@ public class SetProgramPropertyActionTest extends AbstractProvisioningTest { public void testExecuteUndo() { Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); Properties profileProperties = new Properties(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, getTempFolder().toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); InstallableUnitOperand operand = new InstallableUnitOperand(null, createIU("test")); touchpoint.initializePhase(null, profile, "test", parameters); parameters.put("iu", operand.second()); @@ -70,9 +71,9 @@ public class SetProgramPropertyActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -86,6 +87,7 @@ public class SetProgramPropertyActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); @@ -126,9 +128,9 @@ public class SetProgramPropertyActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -142,6 +144,7 @@ public class SetProgramPropertyActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetStartLevelActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetStartLevelActionTest.java index af5b7f8f5..a86555eb2 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetStartLevelActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/SetStartLevelActionTest.java @@ -19,13 +19,13 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstant import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.SetStartLevelAction; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -45,9 +45,9 @@ public class SetStartLevelActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -61,6 +61,7 @@ public class SetStartLevelActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); @@ -90,9 +91,9 @@ public class SetStartLevelActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -106,6 +107,7 @@ public class SetStartLevelActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); @@ -138,9 +140,9 @@ public class SetStartLevelActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi.fragment_1.0.0.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -154,6 +156,7 @@ public class SetStartLevelActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/UninstallBundleActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/UninstallBundleActionTest.java index 0f1dca7d1..14c380d54 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/UninstallBundleActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/UninstallBundleActionTest.java @@ -19,13 +19,13 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstant import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.UninstallBundleAction; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -45,9 +45,9 @@ public class UninstallBundleActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File osgiSource = getTestData("1.0", "/testData/eclipseTouchpoint/bundles/org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar"); File targetPlugins = new File(installFolder, "plugins"); assertTrue(targetPlugins.mkdir()); @@ -61,6 +61,7 @@ public class UninstallBundleActionTest extends AbstractProvisioningTest { bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/UninstallFeatureActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/UninstallFeatureActionTest.java index 8ba22cc83..51a182a9f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/UninstallFeatureActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/UninstallFeatureActionTest.java @@ -11,19 +11,21 @@ package org.eclipse.equinox.p2.tests.touchpoint.eclipse; import java.io.File; import java.net.URI; import java.util.*; +import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactDescriptor; import org.eclipse.equinox.internal.p2.publisher.eclipse.FeatureParser; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.*; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.UninstallFeatureAction; import org.eclipse.equinox.internal.p2.update.Site; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.PublisherInfo; import org.eclipse.equinox.p2.publisher.eclipse.Feature; import org.eclipse.equinox.p2.publisher.eclipse.FeaturesAction; +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; @@ -46,9 +48,9 @@ public class UninstallFeatureActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); profileProperties.setProperty(IProfile.PROP_CACHE, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(getAgent(), profile); File featureSource = getTestData("1.0", "/testData/eclipseTouchpoint/features/org.eclipse.rcp_3.3.0.v20070607-8y8eE8NEbsN3X_fjWS8HPNG"); File targetPlugins = new File(installFolder, "features"); assertTrue(targetPlugins.mkdir()); @@ -59,13 +61,14 @@ public class UninstallFeatureActionTest extends AbstractProvisioningTest { Feature feature = parser.parse(featureTarget); IArtifactKey key = FeaturesAction.createFeatureArtifactKey(feature.getId(), feature.getVersion()); - IArtifactDescriptor descriptor = PublisherHelper.createArtifactDescriptor(key, featureTarget); - ((ArtifactDescriptor) descriptor).setRepositoryProperty("artifact.folder", Boolean.TRUE.toString()); + IArtifactDescriptor descriptor = PublisherHelper.createArtifactDescriptor(bundlePool, key, featureTarget); + ((SimpleArtifactDescriptor) descriptor).setRepositoryProperty("artifact.folder", Boolean.TRUE.toString()); IInstallableUnit iu = FeaturesAction.createFeatureJarIU(feature, new PublisherInfo()); bundlePool.addDescriptor(descriptor); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); EclipseTouchpoint touchpoint = new EclipseTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/UtilTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/UtilTest.java index e1b3bfe17..1b46c577f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/UtilTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/eclipse/UtilTest.java @@ -12,19 +12,17 @@ package org.eclipse.equinox.p2.tests.touchpoint.eclipse; import java.io.File; import java.net.MalformedURLException; -import java.net.URISyntaxException; import java.util.Collections; import java.util.Properties; import junit.framework.Test; import junit.framework.TestSuite; -import org.eclipse.core.runtime.URIUtil; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Activator; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.ITouchpointData; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.ITouchpointData; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; /** @@ -47,24 +45,20 @@ public class UtilTest extends AbstractProvisioningTest { public void testDefaultBundlePool() { IProfile profile = createProfile("test"); - AgentLocation agentLocation = (AgentLocation) ServiceHelper.getService(Activator.getContext(), AgentLocation.class.getName()); - try { - assertEquals(URIUtil.toURI(agentLocation.getDataArea("org.eclipse.equinox.p2.touchpoint.eclipse")), Util.getBundlePoolLocation(profile)); - } catch (URISyntaxException e) { - fail("0.99", e); - } + IAgentLocation agentLocation = (IAgentLocation) ServiceHelper.getService(Activator.getContext(), IAgentLocation.class.getName()); + assertEquals(agentLocation.getDataArea("org.eclipse.equinox.p2.touchpoint.eclipse"), Util.getBundlePoolLocation(getAgent(), profile)); } public void testExplicitBundlePool() throws MalformedURLException { Properties props = new Properties(); File cacheDir = new File(System.getProperty("java.io.tmpdir"), "cache"); props.put(IProfile.PROP_CACHE, cacheDir.toString()); - IProfile profile = createProfile("test", null, props); - assertEquals(cacheDir.toURL().toExternalForm(), Util.getBundlePoolLocation(profile).toString()); + IProfile profile = createProfile("test", props); + assertEquals(cacheDir.toURL().toExternalForm(), Util.getBundlePoolLocation(getAgent(), profile).toString()); } public void testMissingManifest() { ITouchpointData emptyData = MetadataFactory.createTouchpointData(Collections.EMPTY_MAP); - assertNull(Util.getManifest(new ITouchpointData[] {emptyData})); + assertNull(Util.getManifest(Collections.singletonList(emptyData))); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/ChmodActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/ChmodActionTest.java index a929fbc32..f567c88a3 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/ChmodActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/ChmodActionTest.java @@ -17,7 +17,7 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.touchpoint.natives.NativeTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.ChmodAction; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfile; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class ChmodActionTest extends AbstractProvisioningTest { @@ -34,7 +34,7 @@ public class ChmodActionTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); - IProfile profile = createProfile("testExecuteUndo", null, profileProperties); + IProfile profile = createProfile("testExecuteUndo", profileProperties); File zipSource = getTestData("1.0", "/testData/nativeTouchpoint/a.zip"); File zipTarget = new File(installFolder, "a.zip"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/CleanupzipActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/CleanupzipActionTest.java index 14c1d9400..403013abb 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/CleanupzipActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/CleanupzipActionTest.java @@ -15,10 +15,12 @@ import java.util.*; import org.eclipse.equinox.internal.p2.touchpoint.natives.IBackupStore; import org.eclipse.equinox.internal.p2.touchpoint.natives.NativeTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; @@ -45,7 +47,7 @@ public class CleanupzipActionTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); - IProfile profile = createProfile("testExecuteUndo", null, profileProperties); + IProfile profile = createProfile("testExecuteUndo", profileProperties); File zipSource = getTestData("1.0", "/testData/nativeTouchpoint/a.zip"); File zipTarget = new File(installFolder, "a.zip"); @@ -92,7 +94,7 @@ public class CleanupzipActionTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); - IProfile profile = createProfile("testExecuteUndoWhereInstallFolderIsDifferent", null, profileProperties); + IProfile profile = createProfile("testExecuteUndoWhereInstallFolderIsDifferent", profileProperties); File zipSource = getTestData("1.0", "/testData/nativeTouchpoint/a.zip"); File zipTarget = new File(installFolder, "a.zip"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/CollectActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/CollectActionTest.java index a9c30171f..4adaf372f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/CollectActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/CollectActionTest.java @@ -12,15 +12,17 @@ package org.eclipse.equinox.p2.tests.touchpoint.natives; import java.io.File; import java.util.*; +import org.eclipse.equinox.internal.p2.engine.phases.Collect; import org.eclipse.equinox.internal.p2.touchpoint.natives.NativeTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.CollectAction; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.engine.phases.Collect; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRequest; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; @@ -38,7 +40,7 @@ public class CollectActionTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); // File zipSource = getTestData("1.0", "/testData/nativeTouchpoint/a.zip"); // File zipTarget = new File(installFolder, "a.zip"); @@ -53,8 +55,9 @@ public class CollectActionTest extends AbstractProvisioningTest { IInstallableUnit iu = MetadataFactory.createInstallableUnit(iuDesc); Map parameters = new HashMap(); + parameters.put(ActionConstants.PARM_AGENT, getAgent()); parameters.put(ActionConstants.PARM_PROFILE, profile); - parameters.put(Collect.PARM_ARTIFACT_REQUESTS, new ArrayList()); + parameters.put(Collect.PARM_ARTIFACT_REQUESTS, new ArrayList()); NativeTouchpoint touchpoint = new NativeTouchpoint(); touchpoint.initializePhase(null, profile, "test", parameters); InstallableUnitOperand operand = new InstallableUnitOperand(null, iu); @@ -63,7 +66,7 @@ public class CollectActionTest extends AbstractProvisioningTest { parameters.put(ActionConstants.PARM_OPERAND, operand); parameters = Collections.unmodifiableMap(parameters); - List requests = (List) parameters.get(Collect.PARM_ARTIFACT_REQUESTS); + List requests = (List) parameters.get(Collect.PARM_ARTIFACT_REQUESTS); assertFalse(hasRequest(requests, key)); CollectAction action = new CollectAction(); action.execute(parameters); @@ -73,9 +76,8 @@ public class CollectActionTest extends AbstractProvisioningTest { assertTrue(hasRequest(requests, key)); } - private boolean hasRequest(List requests, IArtifactKey key) { - for (Iterator iterator = requests.iterator(); iterator.hasNext();) { - IArtifactRequest[] request = (IArtifactRequest[]) iterator.next(); + private boolean hasRequest(List requests, IArtifactKey key) { + for (IArtifactRequest[] request : requests) { for (int i = 0; i < request.length; i++) { if (key.equals(request[i].getArtifactKey())) return true; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/CopyActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/CopyActionTest.java index 23b6c3f89..09f20a924 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/CopyActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/CopyActionTest.java @@ -15,10 +15,12 @@ import java.util.*; import org.eclipse.equinox.internal.p2.touchpoint.natives.NativeTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.CopyAction; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; @@ -204,7 +206,7 @@ public class CopyActionTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); File source = getTestData("1.0", sourceName); File target = new File(installFolder, targetName); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/LinkActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/LinkActionTest.java index 65f219657..c194ad143 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/LinkActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/LinkActionTest.java @@ -15,7 +15,7 @@ import java.util.*; import org.eclipse.equinox.internal.p2.touchpoint.natives.NativeTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.LinkAction; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfile; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class LinkActionTest extends AbstractProvisioningTest { @@ -32,7 +32,7 @@ public class LinkActionTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); File zipSource = getTestData("1.0", "/testData/nativeTouchpoint/a.zip"); File zipTarget = new File(installFolder, "a.zip"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/MkdirActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/MkdirActionTest.java index 85a709e3a..f69301c96 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/MkdirActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/MkdirActionTest.java @@ -13,7 +13,7 @@ import java.util.*; import org.eclipse.equinox.internal.p2.touchpoint.natives.NativeTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.MkdirAction; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfile; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class MkdirActionTest extends AbstractProvisioningTest { @@ -30,7 +30,7 @@ public class MkdirActionTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); Map parameters = new HashMap(); parameters.put(ActionConstants.PARM_PROFILE, profile); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/NativeTouchpointTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/NativeTouchpointTest.java index 0247557e1..f91d3571b 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/NativeTouchpointTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/NativeTouchpointTest.java @@ -13,7 +13,7 @@ package org.eclipse.equinox.p2.tests.touchpoint.natives; import java.io.File; import java.util.*; import org.eclipse.equinox.internal.p2.touchpoint.natives.NativeTouchpoint; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfile; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class NativeTouchpointTest extends AbstractProvisioningTest { @@ -39,7 +39,7 @@ public class NativeTouchpointTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); - profile = createProfile("test", null, profileProperties); + profile = createProfile("test", profileProperties); touchpoint.initializePhase(null, profile, "test", parameters); touchpoint.completePhase(null, profile, "test", parameters); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/RemoveActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/RemoveActionTest.java index 1191675e9..b3a96cae9 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/RemoveActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/RemoveActionTest.java @@ -17,7 +17,7 @@ import org.eclipse.equinox.internal.p2.touchpoint.natives.IBackupStore; import org.eclipse.equinox.internal.p2.touchpoint.natives.NativeTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.RemoveAction; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfile; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class RemoveActionTest extends AbstractProvisioningTest { @@ -34,7 +34,7 @@ public class RemoveActionTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); - IProfile profile = createProfile("testExecuteUndo", null, profileProperties); + IProfile profile = createProfile("testExecuteUndo", profileProperties); Map parameters = new HashMap(); parameters.put(ActionConstants.PARM_PROFILE, profile); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/RmdirActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/RmdirActionTest.java index 862fa4ef8..be31d0cb6 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/RmdirActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/RmdirActionTest.java @@ -17,7 +17,7 @@ import org.eclipse.equinox.internal.p2.touchpoint.natives.IBackupStore; import org.eclipse.equinox.internal.p2.touchpoint.natives.NativeTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.RmdirAction; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfile; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class RmdirActionTest extends AbstractProvisioningTest { @@ -34,7 +34,7 @@ public class RmdirActionTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); - IProfile profile = createProfile("testExecuteUndo", null, profileProperties); + IProfile profile = createProfile("testExecuteUndo", profileProperties); Map parameters = new HashMap(); parameters.put(ActionConstants.PARM_PROFILE, profile); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/UnzipActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/UnzipActionTest.java index e5f8c9d1f..4e2411e44 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/UnzipActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/touchpoint/natives/UnzipActionTest.java @@ -14,10 +14,12 @@ import org.eclipse.equinox.internal.p2.touchpoint.natives.IBackupStore; import org.eclipse.equinox.internal.p2.touchpoint.natives.NativeTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.ActionConstants; import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.UnzipAction; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; @@ -44,7 +46,7 @@ public class UnzipActionTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); - IProfile profile = createProfile("test", null, profileProperties); + IProfile profile = createProfile("test", profileProperties); File zipSource = getTestData("1.0", "/testData/nativeTouchpoint/a.zip"); File zipTarget = new File(installFolder, "a.zip"); @@ -86,7 +88,7 @@ public class UnzipActionTest extends AbstractProvisioningTest { Properties profileProperties = new Properties(); File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); - IProfile profile = createProfile("testExecuteUndoBackup", null, profileProperties); + IProfile profile = createProfile("testExecuteUndoBackup", profileProperties); File zipSource = getTestData("1.0", "/testData/nativeTouchpoint/a.zip"); File zipTarget = new File(installFolder, "a.zip"); @@ -147,7 +149,7 @@ public class UnzipActionTest extends AbstractProvisioningTest { File installFolder = getTempFolder(); profileProperties.setProperty(IProfile.PROP_INSTALL_FOLDER, installFolder.toString()); final String profileId = "Test:With\\Sym/bols"; - IProfile profile = createProfile(profileId, null, profileProperties); + IProfile profile = createProfile(profileId, profileProperties); File zipSource = getTestData("1.0", "/testData/nativeTouchpoint/a.zip"); File zipTarget = new File(installFolder, "a.zip"); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatechecker/UpdateCheckerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatechecker/UpdateCheckerTest.java index d59e18846..92bf37739 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatechecker/UpdateCheckerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatechecker/UpdateCheckerTest.java @@ -10,21 +10,20 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.updatechecker; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.publisher.Activator; import org.eclipse.equinox.internal.provisional.p2.director.IDirector; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.internal.provisional.p2.updatechecker.IUpdateChecker; import org.eclipse.equinox.internal.provisional.p2.updatechecker.UpdateEvent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; -import org.osgi.framework.Bundle; /** * Tests for API of {@link IUpdateChecker}. @@ -42,11 +41,11 @@ public class UpdateCheckerTest extends AbstractProvisioningTest { @Override protected void setUp() throws Exception { super.setUp(); - TestActivator.getBundle("org.eclipse.equinox.p2.updatechecker").start(Bundle.START_TRANSIENT); + startBundle(TestActivator.getBundle("org.eclipse.equinox.p2.updatechecker")); String id = "toInstall." + getName(); - toInstallIU = createIU(id, new Version(1, 0, 0)); - IUpdateDescriptor updateDescriptor = createUpdateDescriptor(id, new Version(2, 0, 0)); - update = createIU(id, new Version(2, 0, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, true, updateDescriptor, null); + toInstallIU = createIU(id, Version.createOSGi(1, 0, 0)); + IUpdateDescriptor updateDescriptor = createUpdateDescriptor(id, Version.createOSGi(2, 0, 0)); + update = createIU(id, Version.createOSGi(2, 0, 0), null, NO_REQUIRES, NO_PROVIDES, NO_PROPERTIES, ITouchpointType.NONE, NO_TP_DATA, true, updateDescriptor, null); IInstallableUnit[] allUnits = new IInstallableUnit[] {toInstallIU, update}; IInstallableUnit[] toInstallArray = new IInstallableUnit[] {toInstallIU}; diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/CategoryXMLActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/CategoryXMLActionTest.java index 1ef0aa252..1adb31c54 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/CategoryXMLActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/CategoryXMLActionTest.java @@ -11,14 +11,13 @@ package org.eclipse.equinox.p2.tests.updatesite; import java.io.File; import java.net.URI; -import java.util.Collection; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.updatesite.CategoryXMLAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IUPropertyQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.CategoryQuery; import org.eclipse.equinox.p2.publisher.*; import org.eclipse.equinox.p2.publisher.eclipse.FeaturesAction; +import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.equinox.p2.tests.*; /** @@ -46,11 +45,9 @@ public class CategoryXMLActionTest extends AbstractProvisioningTest { } public void testCategoryCreation() throws Exception { - IUPropertyQuery categoryQuery = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_CATEGORY, Boolean.TRUE.toString()); - Collection result = actionResult.query(categoryQuery, new Collector(), new NullProgressMonitor()).toCollection(); - assertEquals("1.0", 1, result.size()); + IQueryResult result = actionResult.query(new CategoryQuery(), new NullProgressMonitor()); + assertEquals("1.0", 1, queryResultSize(result)); IInstallableUnit iu = (IInstallableUnit) result.iterator().next(); assertEquals("1.1", "Test Category Label", iu.getProperty(IInstallableUnit.PROP_NAME)); } - } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/DoesNotCacheStaleData.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/DoesNotCacheStaleData.java index 7d1dbc9eb..c25f90b1b 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/DoesNotCacheStaleData.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/DoesNotCacheStaleData.java @@ -14,13 +14,13 @@ import java.io.File; import java.net.URI; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.URIUtil; +import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepositoryFactory; +import org.eclipse.equinox.internal.p2.metadata.repository.SimpleMetadataRepositoryFactory; import org.eclipse.equinox.internal.p2.updatesite.artifact.UpdateSiteArtifactRepositoryFactory; import org.eclipse.equinox.internal.p2.updatesite.metadata.UpdateSiteMetadataRepositoryFactory; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.SimpleArtifactRepositoryFactory; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.SimpleMetadataRepositoryFactory; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; public class DoesNotCacheStaleData extends AbstractProvisioningTest { @@ -39,7 +39,9 @@ public class DoesNotCacheStaleData extends AbstractProvisioningTest { assertNotNull(e); assertTrue(new File(URIUtil.toFile(UpdateSiteMetadataRepositoryFactory.getLocalRepositoryLocation(siteURI)), "content.xml").exists()); try { - IMetadataRepository repo = new SimpleMetadataRepositoryFactory().load(f.toURI(), 0, new NullProgressMonitor()); + final SimpleMetadataRepositoryFactory simpleFactory = new SimpleMetadataRepositoryFactory(); + simpleFactory.setAgent(getAgent()); + IMetadataRepository repo = simpleFactory.load(f.toURI(), 0, new NullProgressMonitor()); assertEquals("0", repo.getProperties().get("site.checksum")); } catch (ProvisionException e1) { fail("3.0", e1); @@ -60,7 +62,9 @@ public class DoesNotCacheStaleData extends AbstractProvisioningTest { assertNotNull(e); assertTrue(new File(URIUtil.toFile(UpdateSiteMetadataRepositoryFactory.getLocalRepositoryLocation(siteURI)), "artifacts.xml").exists()); try { - IArtifactRepository repo = new SimpleArtifactRepositoryFactory().load(f.toURI(), 0, new NullProgressMonitor()); + final SimpleArtifactRepositoryFactory simpleFactory = new SimpleArtifactRepositoryFactory(); + simpleFactory.setAgent(getAgent()); + IArtifactRepository repo = simpleFactory.load(f.toURI(), 0, new NullProgressMonitor()); assertEquals("0", repo.getProperties().get("site.checksum")); } catch (ProvisionException e1) { fail("3.0", e1); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/LocalUpdatesiteTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/LocalUpdatesiteTest.java index 0075da28c..ea5a1a9ed 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/LocalUpdatesiteTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/LocalUpdatesiteTest.java @@ -14,10 +14,11 @@ import java.io.IOException; import java.util.Iterator; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.internal.p2.updatesite.UpdateSitePublisherApplication; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.CategoryQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestData; @@ -39,7 +40,6 @@ public class LocalUpdatesiteTest extends AbstractProvisioningTest { } public void testCategoryQualifier() throws IOException, ProvisionException { - Query categoryQuery = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_CATEGORY, Boolean.toString(true)); File siteSource = TestData.getFile("updatesite", "SiteXMLActionTest"); UpdateSitePublisherApplication application = new UpdateSitePublisherApplication(); try { @@ -48,8 +48,8 @@ public class LocalUpdatesiteTest extends AbstractProvisioningTest { fail("0.99"); } IMetadataRepository repository = getMetadataRepositoryManager().loadRepository(repoLocation.toURI(), new NullProgressMonitor()); - Collector results = repository.query(categoryQuery, new Collector(), new NullProgressMonitor()); - assertEquals("1.0", 1, results.size()); + IQueryResult results = repository.query(new CategoryQuery(), new NullProgressMonitor()); + assertEquals("1.0", 1, queryResultSize(results)); Iterator iter = results.iterator(); while (iter.hasNext()) { IInstallableUnit unit = (IInstallableUnit) iter.next(); diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/SiteXMLActionTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/SiteXMLActionTest.java index 71bc55d14..a2249c29d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/SiteXMLActionTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/SiteXMLActionTest.java @@ -17,13 +17,14 @@ import java.util.Iterator; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.URIUtil; import org.eclipse.equinox.internal.p2.updatesite.SiteXMLAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IProvidedCapability; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.RepositoryReference; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IProvidedCapability; +import org.eclipse.equinox.p2.metadata.query.CategoryQuery; import org.eclipse.equinox.p2.publisher.*; import org.eclipse.equinox.p2.publisher.eclipse.FeaturesAction; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.spi.RepositoryReference; import org.eclipse.equinox.p2.tests.*; /** @@ -50,8 +51,7 @@ public class SiteXMLActionTest extends AbstractProvisioningTest { } public void testQualifier() { - Query categoryQuery = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_CATEGORY, Boolean.toString(true)); - Collector results = actionResult.query(categoryQuery, new Collector(), new NullProgressMonitor()); + IQueryResult results = actionResult.query(new CategoryQuery(), new NullProgressMonitor()); Iterator iter = results.iterator(); while (iter.hasNext()) { IInstallableUnit unit = (IInstallableUnit) iter.next(); @@ -59,10 +59,10 @@ public class SiteXMLActionTest extends AbstractProvisioningTest { assertTrue("1.0", unit.getId().startsWith(sitelocation)); assertEquals("2.0", "Test Category Label", unit.getProperty(IInstallableUnit.PROP_NAME)); - IProvidedCapability[] provided = unit.getProvidedCapabilities(); - assertEquals(1, provided.length); - assertTrue(provided[0].getName().startsWith(sitelocation)); - assertEquals(provided[0].getVersion(), unit.getVersion()); + Collection provided = unit.getProvidedCapabilities(); + assertEquals(1, provided.size()); + assertTrue(provided.iterator().next().getName().startsWith(sitelocation)); + assertEquals(provided.iterator().next().getVersion(), unit.getVersion()); } } diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/UpdateSiteTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/UpdateSiteTest.java index c343c09b2..a2d07dd06 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/UpdateSiteTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/updatesite/UpdateSiteTest.java @@ -10,14 +10,14 @@ *******************************************************************************/ package org.eclipse.equinox.p2.tests.updatesite; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.VersionRange; import java.io.*; import java.lang.reflect.Field; import java.net.URI; import java.net.URISyntaxException; -import java.util.Map; +import java.util.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import junit.framework.Test; @@ -28,19 +28,21 @@ import org.eclipse.equinox.internal.p2.artifact.repository.RawMirrorRequest; import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.p2.updatesite.SiteFeature; import org.eclipse.equinox.internal.p2.updatesite.UpdateSite; import org.eclipse.equinox.internal.p2.updatesite.artifact.UpdateSiteArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.spi.p2.repository.AbstractRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.repository.spi.AbstractRepository; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; import org.w3c.dom.*; @@ -575,7 +577,7 @@ public class UpdateSiteTest extends AbstractProvisioningTest { } public void testRepoWithFeatureWithNullUpdateURL() { - IMetadataRepositoryManager repoMan = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager repoMan = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); assertNotNull(repoMan); File site = getTestData("Update site", "/testData/updatesite/missingUpdateURLFeature/"); IMetadataRepository metadataRepo = null; @@ -584,16 +586,16 @@ public class UpdateSiteTest extends AbstractProvisioningTest { } catch (ProvisionException e) { fail("Can't load repository missingUpdateURLFeature"); } - InstallableUnitQuery query = new InstallableUnitQuery("test.featurewithmissingupdateurl.feature.group", new Version("1.0.0")); - Collector result = metadataRepo.query(query, new Collector(), null); - assertEquals("1.0", 1, result.size()); + InstallableUnitQuery query = new InstallableUnitQuery("test.featurewithmissingupdateurl.feature.group", Version.create("1.0.0")); + IQueryResult result = metadataRepo.query(query, null); + assertEquals("1.0", 1, queryResultSize(result)); } /** * Tests that a feature requiring a bundle with no range is converted correctly. */ public void testBug243422() { - IMetadataRepositoryManager repoMan = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager repoMan = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); assertNotNull(repoMan); File site = getTestData("Update site", "/testData/updatesite/UpdateSite243422/"); IMetadataRepository metadataRepo = null; @@ -602,20 +604,21 @@ public class UpdateSiteTest extends AbstractProvisioningTest { } catch (ProvisionException e) { fail("Can't load repository UpdateSite243422"); } - InstallableUnitQuery query = new InstallableUnitQuery("org.eclipse.jdt.astview.feature.feature.group", new Version("1.0.1")); - Collector result = metadataRepo.query(query, new Collector(), null); - assertEquals("1.0", 1, result.size()); + InstallableUnitQuery query = new InstallableUnitQuery("org.eclipse.jdt.astview.feature.feature.group", Version.create("1.0.1")); + IQueryResult result = metadataRepo.query(query, null); + assertEquals("1.0", 1, queryResultSize(result)); IInstallableUnit featureIU = (IInstallableUnit) result.iterator().next(); - IRequiredCapability[] required = featureIU.getRequiredCapabilities(); - for (int i = 0; i < required.length; i++) { - if (required[i].getName().equals("org.eclipse.ui.ide")) { - assertEquals("2.0", VersionRange.emptyRange, required[i].getRange()); + Collection required = featureIU.getRequiredCapabilities(); + for (Iterator iterator = required.iterator(); iterator.hasNext();) { + IRequiredCapability req = (IRequiredCapability) iterator.next(); + if (req.getName().equals("org.eclipse.ui.ide")) { + assertEquals("2.0", VersionRange.emptyRange, req.getRange()); } } } public void testShortenVersionNumberInFeature() { - IArtifactRepositoryManager repoMan = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IArtifactRepositoryManager.class.getName()); + IArtifactRepositoryManager repoMan = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); assertNotNull(repoMan); File site = getTestData("Update site", "/testData/updatesite/240121/UpdateSite240121/"); IArtifactRepository artifactRepo = null; @@ -624,14 +627,12 @@ public class UpdateSiteTest extends AbstractProvisioningTest { } catch (ProvisionException e) { fail("Can't load repository UpdateSite240121"); } - IArtifactKey[] keys = artifactRepo.getArtifactKeys(); - for (int i = 0; i < keys.length; i++) { - if (keys[i].getId().equals("Plugin240121")) { - IStatus status = artifactRepo.getArtifact(artifactRepo.getArtifactDescriptors(keys[i])[0], new ByteArrayOutputStream(500), new NullProgressMonitor()); - if (!status.isOK()) - fail("Can't get the expected artifact:" + keys[i]); - } - } + IQueryResult keys = artifactRepo.query(new ArtifactKeyQuery(null, "Plugin240121", null), null); + assertEquals(1, queryResultSize(keys)); + IArtifactKey key = (IArtifactKey) keys.iterator().next(); + IStatus status = artifactRepo.getArtifact(artifactRepo.getArtifactDescriptors(key)[0], new ByteArrayOutputStream(500), new NullProgressMonitor()); + if (!status.isOK()) + fail("Can't get the expected artifact:" + key); } /** @@ -639,7 +640,7 @@ public class UpdateSiteTest extends AbstractProvisioningTest { * unzipping the feature on install. */ public void testFeatureJarUnzipInstruction() { - IMetadataRepositoryManager repoMan = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager repoMan = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); File site = getTestData("0.1", "/testData/updatesite/site"); URI location = null; location = site.toURI(); @@ -650,12 +651,12 @@ public class UpdateSiteTest extends AbstractProvisioningTest { fail("1.99", e); return; } - Collector result = repository.query(new InstallableUnitQuery("test.feature.feature.jar"), new Collector(), getMonitor()); + IQueryResult result = repository.query(new InstallableUnitQuery("test.feature.feature.jar"), getMonitor()); assertTrue("1.0", !result.isEmpty()); IInstallableUnit unit = (IInstallableUnit) result.iterator().next(); - ITouchpointData[] data = unit.getTouchpointData(); - assertEquals("1.1", 1, data.length); - Map instructions = data[0].getInstructions(); + List data = unit.getTouchpointData(); + assertEquals("1.1", 1, data.size()); + Map instructions = data.get(0).getInstructions(); assertEquals("1.2", 1, instructions.size()); assertEquals("1.3", "true", ((ITouchpointInstruction) instructions.get("zipped")).getBody()); } @@ -669,7 +670,7 @@ public class UpdateSiteTest extends AbstractProvisioningTest { URI testUpdateSite = new URI("http://download.eclipse.org/test/updatesite/"); URI testDiscoverySite = new URI("http://download.eclipse.org/test/discoverysite"); - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); assertNotNull(manager); manager.removeRepository(testUpdateSite); manager.removeRepository(testDiscoverySite); @@ -691,7 +692,7 @@ public class UpdateSiteTest extends AbstractProvisioningTest { File site = getTestData("0.1", "/testData/updatesite/site"); URI siteURI = site.toURI(); - IMetadataRepositoryManager metadataRepoMan = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager metadataRepoMan = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); assertNotNull(metadataRepoMan); URI[] knownRepos = metadataRepoMan.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); @@ -717,7 +718,7 @@ public class UpdateSiteTest extends AbstractProvisioningTest { File site = getTestData("0.1", "/testData/updatesite/site"); URI siteURI = site.toURI(); - IArtifactRepositoryManager artifactRepoMan = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IArtifactRepositoryManager.class.getName()); + IArtifactRepositoryManager artifactRepoMan = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); assertNotNull(artifactRepoMan); URI[] knownRepos = artifactRepoMan.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); @@ -750,12 +751,12 @@ public class UpdateSiteTest extends AbstractProvisioningTest { } catch (ProvisionException e) { fail("0.2", e); } - IArtifactKey key = new ArtifactKey("org.eclipse.update.feature", "test.feature", new Version("1.0.0")); + IArtifactKey key = new ArtifactKey("org.eclipse.update.feature", "test.feature", Version.create("1.0.0")); IArtifactDescriptor[] descriptors = repo.getArtifactDescriptors(key); // Should have a packed & canonical version assertEquals(2, descriptors.length); - IArtifactDescriptor desc = "packed".equals(descriptors[0].getProperty("format")) ? descriptors[0] : descriptors[1]; + IArtifactDescriptor desc = IArtifactDescriptor.FORMAT_PACKED.equals(descriptors[0].getProperty(IArtifactDescriptor.FORMAT)) ? descriptors[0] : descriptors[1]; OutputStream out = null; try { out = new FileOutputStream(output); @@ -783,7 +784,7 @@ public class UpdateSiteTest extends AbstractProvisioningTest { File targetLocation = null; URI siteURI = getTestData("0.1", testDataLocation).toURI(); try { - IArtifactKey key = new ArtifactKey("osgi.bundle", "test.fragment", new Version("1.0.0")); + IArtifactKey key = new ArtifactKey("osgi.bundle", "test.fragment", Version.create("1.0.0")); // Load source repository IArtifactRepository sourceRepo = getArtifactRepositoryManager().loadRepository(siteURI, getMonitor()); @@ -800,7 +801,7 @@ public class UpdateSiteTest extends AbstractProvisioningTest { IArtifactDescriptor[] descriptors = sourceRepo.getArtifactDescriptors(key); IArtifactDescriptor descriptor = null; for (int i = 0; i < descriptors.length && descriptor == null; i++) - if ("packed".equals(descriptors[i].getProperty("format"))) + if (IArtifactDescriptor.FORMAT_PACKED.equals(descriptors[i].getProperty(IArtifactDescriptor.FORMAT))) descriptor = descriptors[i]; if (descriptor == null) diff --git a/bundles/org.eclipse.equinox.p2.tests/testData/ProfilePreferencesTest/with(invalid)chars/org.eclipse.equinox.p2.engine/profileRegistry/TestProfile.profile/.data/.settings/org.eclipse.equinox.p2.ui.sdk.prefs b/bundles/org.eclipse.equinox.p2.tests/testData/ProfilePreferencesTest/with(invalid)chars/org.eclipse.equinox.p2.engine/profileRegistry/TestProfile.profile/.data/.settings/org.eclipse.equinox.p2.ui.sdk.prefs new file mode 100644 index 000000000..06a13d37d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.tests/testData/ProfilePreferencesTest/with(invalid)chars/org.eclipse.equinox.p2.engine/profileRegistry/TestProfile.profile/.data/.settings/org.eclipse.equinox.p2.ui.sdk.prefs @@ -0,0 +1,4 @@ +#Tue Apr 21 09:30:49 EDT 2009 +eclipse.preferences.version=1 +showLatestVersion=false +allowNonOKPlan=always diff --git a/bundles/org.eclipse.equinox.p2.tests/testData/ProfilePreferencesTest/with(invalid)chars/org.eclipse.equinox.p2.engine/profileRegistry/TestProfile.profile/1345.profile.gz b/bundles/org.eclipse.equinox.p2.tests/testData/ProfilePreferencesTest/with(invalid)chars/org.eclipse.equinox.p2.engine/profileRegistry/TestProfile.profile/1345.profile.gz new file mode 100644 index 000000000..e69de29bb diff --git a/bundles/org.eclipse.equinox.p2.tests/testData/ProfilePreferencesTest/with(invalid)chars/p2/org.eclipse.equinox.p2.engine/profileRegistry/TestProfile.profile/1345.profile.gz b/bundles/org.eclipse.equinox.p2.tests/testData/ProfilePreferencesTest/with(invalid)chars/p2/org.eclipse.equinox.p2.engine/profileRegistry/TestProfile.profile/1345.profile.gz new file mode 100644 index 000000000..e69de29bb diff --git a/bundles/org.eclipse.equinox.p2.testserver/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.testserver/META-INF/MANIFEST.MF index 415da60d8..3e35f7599 100644 --- a/bundles/org.eclipse.equinox.p2.testserver/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.testserver/META-INF/MANIFEST.MF @@ -5,7 +5,8 @@ Bundle-SymbolicName: org.eclipse.equinox.p2.testserver;singleton:=true Bundle-Version: 1.0.0 Bundle-Activator: org.eclipse.equinox.p2.testserver.Activator Bundle-Vendor: Eclipse -Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4 Import-Package: org.eclipse.equinox.http, org.osgi.framework;version="1.3.0" Bundle-ActivationPolicy: lazy diff --git a/bundles/org.eclipse.equinox.p2.testserver/src/org/eclipse/equinox/p2/testserver/SecureAction.java b/bundles/org.eclipse.equinox.p2.testserver/src/org/eclipse/equinox/p2/testserver/SecureAction.java index af7142dd0..93a536db0 100755 --- a/bundles/org.eclipse.equinox.p2.testserver/src/org/eclipse/equinox/p2/testserver/SecureAction.java +++ b/bundles/org.eclipse.equinox.p2.testserver/src/org/eclipse/equinox/p2/testserver/SecureAction.java @@ -14,7 +14,11 @@ package org.eclipse.equinox.p2.testserver; import java.io.IOException; import java.net.URL; import java.net.URLConnection; -import java.security.*; +import java.security.AccessControlContext; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; import org.osgi.framework.Bundle; /** diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/.classpath b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/.classpath index 2fbb7a23e..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/.classpath +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/.classpath @@ -1,6 +1,6 @@ - + diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/.settings/org.eclipse.jdt.core.prefs index 2daa5df61..1c4f1002d 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Fri Feb 22 11:24:21 EST 2008 +#Tue Dec 22 18:23:28 CET 2009 eclipse.preferences.version=1 instance/org.eclipse.core.net/org.eclipse.core.net.hasMigrated=true org.eclipse.jdt.core.builder.cleanOutputFolder=clean @@ -8,24 +8,24 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fieldHiding=warning org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning @@ -72,7 +72,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=en org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/META-INF/MANIFEST.MF index 186b3ebca..9238a2a41 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/META-INF/MANIFEST.MF @@ -4,26 +4,30 @@ Bundle-SymbolicName: org.eclipse.equinox.p2.touchpoint.eclipse;singleton:=true Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-Localization: plugin -Bundle-Version: 1.0.200.qualifier +Bundle-Version: 2.0.0.qualifier Import-Package: javax.xml.parsers, org.eclipse.core.runtime.preferences;version="3.2.0", org.eclipse.equinox.internal.p2.core.helpers, org.eclipse.equinox.internal.p2.engine, org.eclipse.equinox.internal.p2.garbagecollector, org.eclipse.equinox.internal.provisional.frameworkadmin, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, org.eclipse.equinox.internal.provisional.p2.core, - org.eclipse.equinox.internal.provisional.p2.core.location, org.eclipse.equinox.internal.provisional.p2.director;resolution:=optional, - org.eclipse.equinox.internal.provisional.p2.engine, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, org.eclipse.equinox.internal.provisional.p2.repository, - org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository, org.eclipse.equinox.internal.simpleconfigurator.manipulator, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.engine.spi, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, org.eclipse.equinox.p2.publisher;resolution:=optional, org.eclipse.equinox.p2.publisher.eclipse;resolution:=optional, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.artifact.spi, + org.eclipse.equinox.p2.repository.metadata, org.eclipse.osgi.service.datalocation;version="1.0.0", org.eclipse.osgi.service.environment;version="1.0.0", org.eclipse.osgi.service.resolver;version="1.2.0";resolution:=optional, @@ -33,10 +37,12 @@ Import-Package: javax.xml.parsers, org.osgi.util.tracker;version="1.3.0", org.w3c.dom, org.xml.sax -Export-Package: org.eclipse.equinox.internal.p2.touchpoint.eclipse;x-friends:="org.eclipse.equinox.p2.reconciler.dropins,org.eclipse.equinox.p2.extensionlocation", - org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions;x-internal:=true, - org.eclipse.equinox.internal.p2.update;x-friends:="org.eclipse.equinox.p2.reconciler.dropins,org.eclipse.equinox.p2.extensionlocation,org.eclipse.equinox.p2.directorywatcher" -Bundle-RequiredExecutionEnvironment: J2SE-1.4, +Export-Package: org.eclipse.equinox.internal.p2.touchpoint.eclipse;version="2.0.0";x-friends:="org.eclipse.equinox.p2.reconciler.dropins,org.eclipse.equinox.p2.extensionlocation", + org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions;version="2.0.0";x-internal:=true, + org.eclipse.equinox.internal.p2.update;version="2.0.0";x-friends:="org.eclipse.equinox.p2.reconciler.dropins,org.eclipse.equinox.p2.extensionlocation,org.eclipse.equinox.p2.directorywatcher", + org.eclipse.equinox.p2.touchpoint.eclipse.query;version="2.0.0" +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, CDC-1.1/Foundation-1.1 Bundle-ActivationPolicy: lazy Bundle-Activator: org.eclipse.equinox.internal.p2.touchpoint.eclipse.Activator diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/build.properties b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/build.properties index 4bbd9bd55..0328daa18 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/build.properties +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/build.properties @@ -16,3 +16,5 @@ bin.includes = META-INF/,\ about.html,\ plugin.properties src.includes = about.html +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/AggregatedBundleRepository.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/AggregatedBundleRepository.java index bdcd73ebc..1d90b8326 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/AggregatedBundleRepository.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/AggregatedBundleRepository.java @@ -15,23 +15,23 @@ import java.io.OutputStream; import java.util.*; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.AbstractArtifactRepository; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.AbstractArtifactRepository; public class AggregatedBundleRepository extends AbstractArtifactRepository implements IFileArtifactRepository { private static final String REPOSITORY_TYPE = AggregatedBundleRepository.class.getName(); - private final Collection bundleRepositories; + private final Collection bundleRepositories; - public AggregatedBundleRepository(Collection bundleRepositories) { + public AggregatedBundleRepository(Collection bundleRepositories) { super(REPOSITORY_TYPE, REPOSITORY_TYPE, "1.0", null, null, null, null); //$NON-NLS-1$ this.bundleRepositories = bundleRepositories; } public File getArtifactFile(IArtifactKey key) { - for (Iterator it = bundleRepositories.iterator(); it.hasNext();) { - IFileArtifactRepository repository = (IFileArtifactRepository) it.next(); + for (IFileArtifactRepository repository : bundleRepositories) { File artifactFile = repository.getArtifactFile(key); if (artifactFile != null) return artifactFile; @@ -40,8 +40,7 @@ public class AggregatedBundleRepository extends AbstractArtifactRepository imple } public File getArtifactFile(IArtifactDescriptor descriptor) { - for (Iterator it = bundleRepositories.iterator(); it.hasNext();) { - IFileArtifactRepository repository = (IFileArtifactRepository) it.next(); + for (IFileArtifactRepository repository : bundleRepositories) { File artifactFile = repository.getArtifactFile(descriptor); if (artifactFile != null) return artifactFile; @@ -50,8 +49,7 @@ public class AggregatedBundleRepository extends AbstractArtifactRepository imple } public boolean contains(IArtifactDescriptor descriptor) { - for (Iterator it = bundleRepositories.iterator(); it.hasNext();) { - IFileArtifactRepository repository = (IFileArtifactRepository) it.next(); + for (IFileArtifactRepository repository : bundleRepositories) { if (repository.contains(descriptor)) return true; } @@ -59,8 +57,7 @@ public class AggregatedBundleRepository extends AbstractArtifactRepository imple } public boolean contains(IArtifactKey key) { - for (Iterator it = bundleRepositories.iterator(); it.hasNext();) { - IFileArtifactRepository repository = (IFileArtifactRepository) it.next(); + for (IFileArtifactRepository repository : bundleRepositories) { if (repository.contains(key)) return true; } @@ -68,25 +65,13 @@ public class AggregatedBundleRepository extends AbstractArtifactRepository imple } public IArtifactDescriptor[] getArtifactDescriptors(IArtifactKey key) { - Set artifactDescriptors = new HashSet(); - for (Iterator it = bundleRepositories.iterator(); it.hasNext();) { - IFileArtifactRepository repository = (IFileArtifactRepository) it.next(); + Set artifactDescriptors = new HashSet(); + for (IFileArtifactRepository repository : bundleRepositories) { IArtifactDescriptor[] descriptors = repository.getArtifactDescriptors(key); if (descriptors != null) artifactDescriptors.addAll(Arrays.asList(descriptors)); } - return (IArtifactDescriptor[]) artifactDescriptors.toArray(new IArtifactDescriptor[artifactDescriptors.size()]); - } - - public IArtifactKey[] getArtifactKeys() { - Set artifactKeys = new HashSet(); - for (Iterator it = bundleRepositories.iterator(); it.hasNext();) { - IFileArtifactRepository repository = (IFileArtifactRepository) it.next(); - IArtifactKey[] keys = repository.getArtifactKeys(); - if (keys != null) - artifactKeys.addAll(Arrays.asList(keys)); - } - return (IArtifactKey[]) artifactKeys.toArray(new IArtifactKey[artifactKeys.size()]); + return artifactDescriptors.toArray(new IArtifactDescriptor[artifactDescriptors.size()]); } public IStatus getArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) { @@ -109,7 +94,21 @@ public class AggregatedBundleRepository extends AbstractArtifactRepository imple * Exposed for testing and debugging purposes. * @noreference This method is not intended to be referenced by clients. */ - public Collection testGetBundleRepositories() { + public Collection testGetBundleRepositories() { return bundleRepositories; } + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + // Query all the all the repositories + CompoundQueryable queryable = new CompoundQueryable(bundleRepositories); + return queryable.query(query, monitor); + } + + public IQueryable descriptorQueryable() { + List> descQueryables = new ArrayList>(bundleRepositories.size()); + for (IFileArtifactRepository repository : bundleRepositories) + descQueryables.add(repository.descriptorQueryable()); + + return new CompoundQueryable(descQueryables); + } } diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/DirectorUtil.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/DirectorUtil.java index 1f280e541..7b0513ceb 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/DirectorUtil.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/DirectorUtil.java @@ -15,15 +15,15 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.ProvisioningContext; public class DirectorUtil { public static IStatus validateProfile(IProfile profile) { ProfileChangeRequest pcr = new ProfileChangeRequest(profile); ProvisioningContext ctx = new ProvisioningContext(new URI[0]); - IPlanner planner = (IPlanner) ServiceHelper.getService(Activator.getContext(), IPlanner.class.getName()); + IPlanner planner = (IPlanner) ServiceHelper.getService(Activator.getContext(), IPlanner.SERVICE_NAME); return planner.getProvisioningPlan(pcr, ctx, null).getStatus(); } } diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseMarkSetProvider.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseMarkSetProvider.java index b6dafaf98..7ce57715b 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseMarkSetProvider.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseMarkSetProvider.java @@ -10,23 +10,22 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.touchpoint.eclipse; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; - import java.io.File; import java.util.*; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; import org.eclipse.equinox.internal.p2.garbagecollector.MarkSet; import org.eclipse.equinox.internal.p2.garbagecollector.MarkSetProvider; import org.eclipse.equinox.internal.p2.update.*; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.artifact.ArtifactKeyQuery; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; import org.osgi.framework.ServiceReference; /** @@ -36,11 +35,11 @@ public class EclipseMarkSetProvider extends MarkSetProvider { private static final String ARTIFACT_CLASSIFIER_OSGI_BUNDLE = "osgi.bundle"; //$NON-NLS-1$ private static final String ARTIFACT_CLASSIFIER_FEATURE = "org.eclipse.update.feature"; //$NON-NLS-1$ - private Collection artifactKeyList = null; + private Collection artifactKeyList = null; - public MarkSet[] getMarkSets(IProfile inProfile) { - artifactKeyList = new HashSet(); - IArtifactRepository repositoryToGC = Util.getBundlePoolRepository(inProfile); + public MarkSet[] getMarkSets(IProvisioningAgent agent, IProfile inProfile) { + artifactKeyList = new HashSet(); + IArtifactRepository repositoryToGC = Util.getBundlePoolRepository(agent, inProfile); if (repositoryToGC == null) return new MarkSet[0]; addArtifactKeys(inProfile); @@ -49,15 +48,14 @@ public class EclipseMarkSetProvider extends MarkSetProvider { addRunningBundles(repositoryToGC); addRunningFeatures(inProfile, repositoryToGC); } - return new MarkSet[] {new MarkSet((IArtifactKey[]) artifactKeyList.toArray(new IArtifactKey[0]), repositoryToGC)}; + return new MarkSet[] {new MarkSet(artifactKeyList.toArray(new IArtifactKey[artifactKeyList.size()]), repositoryToGC)}; } private void addRunningFeatures(IProfile profile, IArtifactRepository repositoryToGC) { try { - List allFeatures = getAllFeatures(Configuration.load(new File(Util.getConfigurationFolder(profile), "org.eclipse.update/platform.xml"), null)); //$NON-NLS-1$ - for (Iterator iterator = allFeatures.iterator(); iterator.hasNext();) { - Feature f = (Feature) iterator.next(); - IArtifactKey match = searchArtifact(f.getId(), new Version(f.getVersion()), ARTIFACT_CLASSIFIER_FEATURE, repositoryToGC); + List allFeatures = getAllFeatures(Configuration.load(new File(Util.getConfigurationFolder(profile), "org.eclipse.update/platform.xml"), null)); //$NON-NLS-1$ + for (Feature f : allFeatures) { + IArtifactKey match = searchArtifact(f.getId(), Version.create(f.getVersion()), ARTIFACT_CLASSIFIER_FEATURE, repositoryToGC); if (match != null) artifactKeyList.add(match); } @@ -66,13 +64,12 @@ public class EclipseMarkSetProvider extends MarkSetProvider { } } - private List getAllFeatures(Configuration cfg) { + private List getAllFeatures(Configuration cfg) { if (cfg == null) - return Collections.EMPTY_LIST; - List sites = cfg.getSites(); - ArrayList result = new ArrayList(); - for (Iterator iterator = sites.iterator(); iterator.hasNext();) { - Site object = (Site) iterator.next(); + return CollectionUtils.emptyList(); + List sites = cfg.getSites(); + ArrayList result = new ArrayList(); + for (Site object : sites) { Feature[] features = object.getFeatures(); for (int i = 0; i < features.length; i++) { result.add(features[i]); @@ -82,7 +79,7 @@ public class EclipseMarkSetProvider extends MarkSetProvider { } private IProfile getCurrentProfile() { - ServiceReference sr = Activator.getContext().getServiceReference(IProfileRegistry.class.getName()); + ServiceReference sr = Activator.getContext().getServiceReference(IProfileRegistry.SERVICE_NAME); if (sr == null) return null; IProfileRegistry pr = (IProfileRegistry) Activator.getContext().getService(sr); @@ -93,19 +90,17 @@ public class EclipseMarkSetProvider extends MarkSetProvider { } private void addArtifactKeys(IProfile aProfile) { - Iterator installableUnits = aProfile.query(InstallableUnitQuery.ANY, new Collector(), null).iterator(); + Iterator installableUnits = aProfile.query(InstallableUnitQuery.ANY, null).iterator(); while (installableUnits.hasNext()) { - IArtifactKey[] keys = ((IInstallableUnit) installableUnits.next()).getArtifacts(); + Collection keys = installableUnits.next().getArtifacts(); if (keys == null) continue; - for (int i = 0; i < keys.length; i++) { - artifactKeyList.add(keys[i]); - } + artifactKeyList.addAll(keys); } } - public IArtifactRepository getRepository(IProfile aProfile) { - return Util.getBundlePoolRepository(aProfile); + public IArtifactRepository getRepository(IProvisioningAgent agent, IProfile aProfile) { + return Util.getBundlePoolRepository(agent, aProfile); } private void addRunningBundles(IArtifactRepository repo) { @@ -114,23 +109,20 @@ public class EclipseMarkSetProvider extends MarkSetProvider { private IArtifactKey searchArtifact(String searchedId, Version searchedVersion, String classifier, IArtifactRepository repo) { //This is somewhat cheating since normally we should get the artifact key from the IUs that were representing the running system (e.g. we could get that info from the rollback repo) - IArtifactKey[] keys = repo.getArtifactKeys(); - for (int i = 0; i < keys.length; i++) { - if (keys[i].getClassifier().equals(classifier)) { - String id = keys[i].getId(); - Version v = keys[i].getVersion(); - if (id != null && id.equals(searchedId) && v != null && v.equals(searchedVersion)) - return keys[i]; - } - } + VersionRange range = searchedVersion != null ? new VersionRange(searchedVersion, true, searchedVersion, true) : null; + ArtifactKeyQuery query = new ArtifactKeyQuery(classifier, searchedId, range); + //TODO short-circuit the query when we find one? + IQueryResult keys = repo.query(query, null); + if (!keys.isEmpty()) + return keys.iterator().next(); return null; } //Find for each bundle info a corresponding artifact in repo - private ArrayList findCorrespondinArtifacts(BundleInfo[] bis, IArtifactRepository repo) { - ArrayList toRetain = new ArrayList(); + private List findCorrespondinArtifacts(BundleInfo[] bis, IArtifactRepository repo) { + ArrayList toRetain = new ArrayList(); for (int i = 0; i < bis.length; i++) { - IArtifactKey match = searchArtifact(bis[i].getSymbolicName(), new Version(bis[i].getVersion()), ARTIFACT_CLASSIFIER_OSGI_BUNDLE, repo); + IArtifactKey match = searchArtifact(bis[i].getSymbolicName(), Version.create(bis[i].getVersion()), ARTIFACT_CLASSIFIER_OSGI_BUNDLE, repo); if (match != null) toRetain.add(match); } diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseTouchpoint.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseTouchpoint.java index 8cf88ba61..0ded00367 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseTouchpoint.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseTouchpoint.java @@ -19,10 +19,13 @@ import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.provisional.frameworkadmin.FrameworkAdminRuntimeException; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.Operand; +import org.eclipse.equinox.p2.engine.spi.Touchpoint; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.osgi.util.NLS; public class EclipseTouchpoint extends Touchpoint { @@ -33,36 +36,37 @@ public class EclipseTouchpoint extends Touchpoint { public static final String PARM_IU = "iu"; //$NON-NLS-1$ public static final String PARM_ARTIFACT = "artifact"; //$NON-NLS-1$ public static final String PARM_ARTIFACT_LOCATION = "artifact.location"; //$NON-NLS-1$ + private static final Object PARM_AGENT = "agent"; //$NON-NLS-1$ private static final String NATIVE_TOUCHPOINT_ID = "org.eclipse.equinox.p2.touchpoint.natives"; //$NON-NLS-1$ - private static List NATIVE_ACTIONS = Arrays.asList(new String[] {"mkdir", "rmdir"}); //$NON-NLS-1$//$NON-NLS-2$ + private static List NATIVE_ACTIONS = Arrays.asList(new String[] {"mkdir", "rmdir"}); //$NON-NLS-1$//$NON-NLS-2$ private static final String VALIDATE_PROFILE = "org.eclipse.equinox.internal.p2.touchpoint.eclipse.validateProfile"; //$NON-NLS-1$ - private static Map manipulators = new WeakHashMap(); - private static Map wrappers = new WeakHashMap(); - private static Map sourceManipulators = new WeakHashMap(); - private static Map preparedIUs = new WeakHashMap(); + private static Map manipulators = new WeakHashMap(); + private static Map wrappers = new WeakHashMap(); + private static Map sourceManipulators = new WeakHashMap(); + private static Map> preparedIUs = new WeakHashMap>(); - private static synchronized LazyManipulator getManipulator(IProfile profile) { - LazyManipulator manipulator = (LazyManipulator) manipulators.get(profile); + private static synchronized LazyManipulator getManipulator(IProvisioningAgent agent, IProfile profile) { + LazyManipulator manipulator = manipulators.get(profile); if (manipulator == null) { - manipulator = new LazyManipulator(profile); + manipulator = new LazyManipulator(agent, profile); manipulators.put(profile, manipulator); } return manipulator; } private static synchronized void saveManipulator(IProfile profile) throws FrameworkAdminRuntimeException, IOException { - LazyManipulator manipulator = (LazyManipulator) manipulators.remove(profile); + LazyManipulator manipulator = manipulators.remove(profile); if (manipulator != null) manipulator.save(false); } - private static synchronized PlatformConfigurationWrapper getPlatformConfigurationWrapper(IProfile profile, LazyManipulator manipulator) { - PlatformConfigurationWrapper wrapper = (PlatformConfigurationWrapper) wrappers.get(profile); + private static synchronized PlatformConfigurationWrapper getPlatformConfigurationWrapper(IProvisioningAgent agent, IProfile profile, LazyManipulator manipulator) { + PlatformConfigurationWrapper wrapper = wrappers.get(profile); if (wrapper == null) { File configLocation = Util.getConfigurationFolder(profile); - URI poolURI = Util.getBundlePoolLocation(profile); + URI poolURI = Util.getBundlePoolLocation(agent, profile); wrapper = new PlatformConfigurationWrapper(configLocation, poolURI, manipulator); wrappers.put(profile, wrapper); } @@ -70,13 +74,13 @@ public class EclipseTouchpoint extends Touchpoint { } private static synchronized void savePlatformConfigurationWrapper(IProfile profile) throws ProvisionException { - PlatformConfigurationWrapper wrapper = (PlatformConfigurationWrapper) wrappers.remove(profile); + PlatformConfigurationWrapper wrapper = wrappers.remove(profile); if (wrapper != null) wrapper.save(); } private static synchronized SourceManipulator getSourceManipulator(IProfile profile) { - SourceManipulator sourceManipulator = (SourceManipulator) sourceManipulators.get(profile); + SourceManipulator sourceManipulator = sourceManipulators.get(profile); if (sourceManipulator == null) { sourceManipulator = new SourceManipulator(profile); sourceManipulators.put(profile, sourceManipulator); @@ -85,23 +89,23 @@ public class EclipseTouchpoint extends Touchpoint { } private static synchronized void saveSourceManipulator(IProfile profile) throws IOException { - SourceManipulator sourceManipulator = (SourceManipulator) sourceManipulators.remove(profile); + SourceManipulator sourceManipulator = sourceManipulators.remove(profile); if (sourceManipulator != null) sourceManipulator.save(); } private static synchronized IInstallableUnit getPreparedIU(IProfile profile, IInstallableUnit iu) { - Map preparedProfileIUs = (Map) preparedIUs.get(profile); + Map preparedProfileIUs = preparedIUs.get(profile); if (preparedProfileIUs == null) return null; - return (IInstallableUnit) preparedProfileIUs.get(iu); + return preparedProfileIUs.get(iu); } private static synchronized void savePreparedIU(IProfile profile, IInstallableUnit iu) { - Map preparedProfileIUs = (Map) preparedIUs.get(profile); + Map preparedProfileIUs = preparedIUs.get(profile); if (preparedProfileIUs == null) { - preparedProfileIUs = new HashMap(); + preparedProfileIUs = new HashMap(); preparedIUs.put(profile, preparedProfileIUs); } preparedProfileIUs.put(iu, iu); @@ -165,19 +169,21 @@ public class EclipseTouchpoint extends Touchpoint { return touchpointQualifier + "." + actionId; //$NON-NLS-1$ } - public IStatus initializePhase(IProgressMonitor monitor, IProfile profile, String phaseId, Map touchpointParameters) { - LazyManipulator manipulator = getManipulator(profile); + public IStatus initializePhase(IProgressMonitor monitor, IProfile profile, String phaseId, Map touchpointParameters) { + IProvisioningAgent agent = (IProvisioningAgent) touchpointParameters.get(PARM_AGENT); + LazyManipulator manipulator = getManipulator(agent, profile); touchpointParameters.put(PARM_MANIPULATOR, manipulator); touchpointParameters.put(PARM_SOURCE_BUNDLES, getSourceManipulator(profile)); - touchpointParameters.put(PARM_PLATFORM_CONFIGURATION, getPlatformConfigurationWrapper(profile, manipulator)); + touchpointParameters.put(PARM_PLATFORM_CONFIGURATION, getPlatformConfigurationWrapper(agent, profile, manipulator)); return null; } - public IStatus initializeOperand(IProfile profile, Operand operand, Map parameters) { + public IStatus initializeOperand(IProfile profile, Operand operand, Map parameters) { IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU); IArtifactKey artifactKey = (IArtifactKey) parameters.get(PARM_ARTIFACT); + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(PARM_AGENT); if (iu != null && Boolean.valueOf(iu.getProperty(IInstallableUnit.PROP_PARTIAL_IU)).booleanValue()) { - IInstallableUnit preparedIU = prepareIU(iu, artifactKey, profile); + IInstallableUnit preparedIU = prepareIU(agent, profile, iu, artifactKey); if (preparedIU == null) return Util.createError(NLS.bind(Messages.failed_prepareIU, iu)); @@ -185,19 +191,19 @@ public class EclipseTouchpoint extends Touchpoint { } if (!parameters.containsKey(PARM_ARTIFACT_LOCATION) && artifactKey != null) { - File fileLocation = Util.getArtifactFile(artifactKey, profile); + File fileLocation = Util.getArtifactFile(agent, artifactKey, profile); if (fileLocation != null && fileLocation.exists()) parameters.put(PARM_ARTIFACT_LOCATION, fileLocation.getAbsolutePath()); } return Status.OK_STATUS; } - public IInstallableUnit prepareIU(IInstallableUnit iu, IArtifactKey artifactKey, IProfile profile) { + public IInstallableUnit prepareIU(IProvisioningAgent agent, IProfile profile, IInstallableUnit iu, IArtifactKey artifactKey) { IInstallableUnit preparedIU = getPreparedIU(profile, iu); if (preparedIU != null) return preparedIU; - Class c = null; + Class c = null; try { c = Class.forName("org.eclipse.equinox.p2.publisher.eclipse.BundlesAction"); //$NON-NLS-1$ if (c != null) @@ -211,7 +217,7 @@ public class EclipseTouchpoint extends Touchpoint { if (artifactKey == null) return iu; - File bundleFile = Util.getArtifactFile(artifactKey, profile); + File bundleFile = Util.getArtifactFile(agent, artifactKey, profile); if (bundleFile == null) { LogHelper.log(Util.createError(NLS.bind(Messages.artifact_file_not_found, artifactKey.toString()))); return null; @@ -234,7 +240,7 @@ public class EclipseTouchpoint extends Touchpoint { if (Boolean.FALSE.toString().equals(profile.getProperty(VALIDATE_PROFILE))) return Status.OK_STATUS; - Class c = null; + Class c = null; try { c = Class.forName("org.eclipse.equinox.internal.provisional.p2.director.IPlanner"); //$NON-NLS-1$ } catch (ClassNotFoundException e) { diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/LazyManipulator.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/LazyManipulator.java index d432a4e6d..6869eb284 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/LazyManipulator.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/LazyManipulator.java @@ -11,11 +11,10 @@ package org.eclipse.equinox.internal.p2.touchpoint.eclipse; import java.io.IOException; -import java.net.URISyntaxException; -import org.eclipse.core.runtime.URIUtil; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.provisional.frameworkadmin.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; import org.osgi.framework.*; import org.osgi.util.tracker.ServiceTracker; @@ -28,9 +27,11 @@ public class LazyManipulator implements Manipulator { private Manipulator manipulator; private final IProfile profile; + private final IProvisioningAgent agent; - public LazyManipulator(IProfile profile) { + public LazyManipulator(IProvisioningAgent agent, IProfile profile) { this.profile = profile; + this.agent = agent; } private void loadDelegate() { @@ -61,12 +62,7 @@ public class LazyManipulator implements Manipulator { } //TODO These values should be inserted by a configuration unit (bug 204124) manipulator.getConfigData().setProperty("eclipse.p2.profile", profile.getProfileId()); //$NON-NLS-1$ - try { - manipulator.getConfigData().setProperty("eclipse.p2.data.area", URIUtil.toURI(Util.getAgentLocation().getURL()).toString()); //$NON-NLS-1$ - } catch (URISyntaxException e) { - LogHelper.log(Util.createError(Messages.error_loading_manipulator, e)); - throw new IllegalStateException(Messages.error_loading_manipulator); - } + manipulator.getConfigData().setProperty("eclipse.p2.data.area", Util.getAgentLocation(agent).getRootLocation().toString()); //$NON-NLS-1$ } public static FrameworkAdmin getFrameworkAdmin() { diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/PlatformConfigurationWrapper.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/PlatformConfigurationWrapper.java index 5dcf1ab92..e09db8851 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/PlatformConfigurationWrapper.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/PlatformConfigurationWrapper.java @@ -12,14 +12,13 @@ package org.eclipse.equinox.internal.p2.touchpoint.eclipse; import java.io.File; import java.net.*; -import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.URLUtil; import org.eclipse.equinox.internal.p2.update.*; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.core.ProvisionException; import org.eclipse.osgi.util.NLS; /** @@ -104,8 +103,7 @@ public class PlatformConfigurationWrapper { * Otherwise the default is USER-EXCLUDE. */ private String getDefaultPolicy() { - for (Iterator iter = configuration.getSites().iterator(); iter.hasNext();) { - Site site = (Site) iter.next(); + for (Site site : configuration.getSites()) { if (Site.POLICY_MANAGED_ONLY.equals(site.getPolicy())) return Site.POLICY_MANAGED_ONLY; } @@ -133,10 +131,9 @@ public class PlatformConfigurationWrapper { * the given URL. Return null if there is no match. */ private Site getSite(URI url) { - List sites = configuration.getSites(); + List sites = configuration.getSites(); File file = URIUtil.toFile(url); - for (Iterator iter = sites.iterator(); iter.hasNext();) { - Site nextSite = (Site) iter.next(); + for (Site nextSite : sites) { try { File nextFile = URLUtil.toFile(new URL(nextSite.getUrl())); if (nextFile == null) @@ -155,9 +152,8 @@ public class PlatformConfigurationWrapper { * with the given identifier and version. Return null if there is none. */ private Site getSite(String id, String version) { - List sites = configuration.getSites(); - for (Iterator iter = sites.iterator(); iter.hasNext();) { - Site site = (Site) iter.next(); + List sites = configuration.getSites(); + for (Site site : sites) { Feature[] features = site.getFeatures(); for (int i = 0; i < features.length; i++) { if (id.equals(features[i].getId()) && version.equals(features[i].getVersion())) diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/PublisherUtil.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/PublisherUtil.java index 881a70927..1f6151b6d 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/PublisherUtil.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/PublisherUtil.java @@ -11,12 +11,9 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.touchpoint.eclipse; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; - import java.io.File; import org.eclipse.core.runtime.Path; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.publisher.PublisherInfo; import org.eclipse.equinox.p2.publisher.eclipse.*; import org.eclipse.osgi.service.resolver.BundleDescription; @@ -32,7 +29,7 @@ public class PublisherUtil { if (bundleDescription == null) return null; PublisherInfo info = new PublisherInfo(); - Version version = new Version(bundleDescription.getVersion().toString()); + Version version = Version.create(bundleDescription.getVersion().toString()); AdviceFileAdvice advice = new AdviceFileAdvice(bundleDescription.getSymbolicName(), version, new Path(bundleFile.getAbsolutePath()), AdviceFileAdvice.BUNDLE_ADVICE_FILE); if (advice.containsAdvice()) info.addAdvice(advice); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/SourceManipulator.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/SourceManipulator.java index 6d6ae8bb2..faab230ac 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/SourceManipulator.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/SourceManipulator.java @@ -8,19 +8,18 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.touchpoint.eclipse; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; - import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.*; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.simpleconfigurator.manipulator.SimpleConfiguratorManipulatorImpl; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.Version; //This class deals with source bundles and how their addition to the source.info public class SourceManipulator { - private List sourceBundles; + private List sourceBundles; private IProfile profile; boolean changed = false; private SimpleConfiguratorManipulatorImpl manipulator; @@ -33,7 +32,7 @@ public class SourceManipulator { public BundleInfo[] getBundles() throws IOException { if (sourceBundles == null) load(); - return (BundleInfo[]) sourceBundles.toArray(new BundleInfo[sourceBundles.size()]); + return sourceBundles.toArray(new BundleInfo[sourceBundles.size()]); } public void addBundle(File bundleFile, String bundleId, Version bundleVersion) throws IOException { @@ -59,14 +58,14 @@ public class SourceManipulator { public void save() throws IOException { if (sourceBundles != null) - manipulator.saveConfiguration((BundleInfo[]) sourceBundles.toArray(new BundleInfo[sourceBundles.size()]), getFileLocation(), getLauncherLocation()); + manipulator.saveConfiguration(sourceBundles.toArray(new BundleInfo[sourceBundles.size()]), getFileLocation(), getLauncherLocation()); } private void load() throws MalformedURLException, IOException { if (getFileLocation().exists()) - sourceBundles = new ArrayList(Arrays.asList(manipulator.loadConfiguration(getFileLocation().toURL(), getLauncherLocation()))); + sourceBundles = new ArrayList(Arrays.asList(manipulator.loadConfiguration(getFileLocation().toURL(), getLauncherLocation()))); else - sourceBundles = new ArrayList(); + sourceBundles = new ArrayList(); } private File getFileLocation() { diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/Util.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/Util.java index 68784218c..47f2d0fda 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/Util.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/Util.java @@ -18,12 +18,11 @@ import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.*; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.*; import org.eclipse.osgi.service.datalocation.Location; import org.eclipse.osgi.service.environment.EnvironmentInfo; import org.eclipse.osgi.util.ManifestElement; @@ -53,35 +52,29 @@ public class Util { */ public static final int AGGREGATE_CACHE_EXTENSIONS = 0x04; - public static AgentLocation getAgentLocation() { - return (AgentLocation) ServiceHelper.getService(Activator.getContext(), AgentLocation.class.getName()); + public static IAgentLocation getAgentLocation(IProvisioningAgent agent) { + return (IAgentLocation) agent.getService(IAgentLocation.class.getName()); } - public static IArtifactRepositoryManager getArtifactRepositoryManager() { - return (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); + public static IArtifactRepositoryManager getArtifactRepositoryManager(IProvisioningAgent agent) { + return (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME); } - public static URI getBundlePoolLocation(IProfile profile) { + public static URI getBundlePoolLocation(IProvisioningAgent agent, IProfile profile) { String path = profile.getProperty(IProfile.PROP_CACHE); if (path != null) return new File(path).toURI(); - AgentLocation location = getAgentLocation(); + IAgentLocation location = getAgentLocation(agent); if (location == null) return null; - try { - return URIUtil.toURI(location.getDataArea(Activator.ID)); - } catch (URISyntaxException e) { - // unexpected, URLs should be pre-checked - LogHelper.log(new Status(IStatus.ERROR, Activator.ID, e.getMessage(), e)); - throw new RuntimeException(e); - } + return location.getDataArea(Activator.ID); } - public static synchronized IFileArtifactRepository getBundlePoolRepository(IProfile profile) { - URI location = getBundlePoolLocation(profile); + public static synchronized IFileArtifactRepository getBundlePoolRepository(IProvisioningAgent agent, IProfile profile) { + URI location = getBundlePoolLocation(agent, profile); if (location == null) return null; - IArtifactRepositoryManager manager = getArtifactRepositoryManager(); + IArtifactRepositoryManager manager = getArtifactRepositoryManager(agent); try { return (IFileArtifactRepository) manager.loadRepository(location, null); } catch (ProvisionException e) { @@ -89,7 +82,7 @@ public class Util { } try { String repositoryName = Messages.BundlePool; - Map properties = new HashMap(1); + Map properties = new HashMap(1); properties.put(IRepository.PROP_SYSTEM, Boolean.TRUE.toString()); return (IFileArtifactRepository) manager.createRepository(location, repositoryName, REPOSITORY_TYPE, properties); } catch (ProvisionException e) { @@ -98,15 +91,15 @@ public class Util { } } - public static IFileArtifactRepository getAggregatedBundleRepository(IProfile profile) { - return getAggregatedBundleRepository(profile, AGGREGATE_CACHE | AGGREGATE_SHARED_CACHE | AGGREGATE_CACHE_EXTENSIONS); + public static IFileArtifactRepository getAggregatedBundleRepository(IProvisioningAgent agent, IProfile profile) { + return getAggregatedBundleRepository(agent, profile, AGGREGATE_CACHE | AGGREGATE_SHARED_CACHE | AGGREGATE_CACHE_EXTENSIONS); } - public static IFileArtifactRepository getAggregatedBundleRepository(IProfile profile, int repoFilter) { - List bundleRepositories = new ArrayList(); + public static IFileArtifactRepository getAggregatedBundleRepository(IProvisioningAgent agent, IProfile profile, int repoFilter) { + List bundleRepositories = new ArrayList(); // we check for a shared bundle pool first as it should be preferred over the user bundle pool in a shared install - IArtifactRepositoryManager manager = getArtifactRepositoryManager(); + IArtifactRepositoryManager manager = getArtifactRepositoryManager(agent); if ((repoFilter & AGGREGATE_SHARED_CACHE) != 0) { String sharedCache = profile.getProperty(IProfile.PROP_SHARED_CACHE); if (sharedCache != null) { @@ -114,7 +107,7 @@ public class Util { URI repoLocation = new File(sharedCache).toURI(); IArtifactRepository repository = manager.loadRepository(repoLocation, null); if (repository != null && repository instanceof IFileArtifactRepository && !bundleRepositories.contains(repository)) - bundleRepositories.add(repository); + bundleRepositories.add((IFileArtifactRepository) repository); } catch (ProvisionException e) { //skip repository if it could not be read } @@ -122,16 +115,15 @@ public class Util { } if ((repoFilter & AGGREGATE_CACHE) != 0) { - IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(agent, profile); if (bundlePool != null) bundleRepositories.add(bundlePool); } if ((repoFilter & AGGREGATE_CACHE_EXTENSIONS) != 0) { - List repos = getListProfileProperty(profile, CACHE_EXTENSIONS); - for (Iterator iterator = repos.iterator(); iterator.hasNext();) { + List repos = getListProfileProperty(profile, CACHE_EXTENSIONS); + for (String repo : repos) { try { - String repo = (String) iterator.next(); URI repoLocation; try { repoLocation = new URI(repo); @@ -141,7 +133,7 @@ public class Util { } IArtifactRepository repository = manager.loadRepository(repoLocation, null); if (repository != null && repository instanceof IFileArtifactRepository && !bundleRepositories.contains(repository)) - bundleRepositories.add(repository); + bundleRepositories.add((IFileArtifactRepository) repository); } catch (ProvisionException e) { //skip repositories that could not be read } catch (URISyntaxException e) { @@ -153,8 +145,8 @@ public class Util { return new AggregatedBundleRepository(bundleRepositories); } - private static List getListProfileProperty(IProfile profile, String key) { - List listProperty = new ArrayList(); + private static List getListProfileProperty(IProfile profile, String key) { + List listProperty = new ArrayList(); String dropinRepositories = profile.getProperty(key); if (dropinRepositories != null) { StringTokenizer tokenizer = new StringTokenizer(dropinRepositories, PIPE); @@ -172,20 +164,21 @@ public class Util { bundleInfo.setManifest(manifest); try { - Map headers = ManifestElement.parseBundleManifest(new ByteArrayInputStream(manifest.getBytes("UTF-8")), new HashMap()); //$NON-NLS-1$ - ManifestElement[] element = ManifestElement.parseHeader("bsn", (String) headers.get(Constants.BUNDLE_SYMBOLICNAME)); //$NON-NLS-1$ + @SuppressWarnings("unchecked") + Map headers = ManifestElement.parseBundleManifest(new ByteArrayInputStream(manifest.getBytes("UTF-8")), new HashMap()); //$NON-NLS-1$ + ManifestElement[] element = ManifestElement.parseHeader("bsn", headers.get(Constants.BUNDLE_SYMBOLICNAME)); //$NON-NLS-1$ if (element == null || element.length == 0) return null; bundleInfo.setSymbolicName(element[0].getValue()); - String version = (String) headers.get(Constants.BUNDLE_VERSION); + String version = headers.get(Constants.BUNDLE_VERSION); if (version == null) return null; // convert to a Version object first to ensure we are consistent with our version number w.r.t. // padding zeros at the end bundleInfo.setVersion(Version.parseVersion(version).toString()); - String fragmentHost = (String) headers.get(Constants.FRAGMENT_HOST); + String fragmentHost = headers.get(Constants.FRAGMENT_HOST); if (fragmentHost != null) bundleInfo.setFragmentHost(fragmentHost.trim()); @@ -201,8 +194,8 @@ public class Util { return bundleInfo; } - public static File getArtifactFile(IArtifactKey artifactKey, IProfile profile) { - IFileArtifactRepository aggregatedView = getAggregatedBundleRepository(profile); + public static File getArtifactFile(IProvisioningAgent agent, IArtifactKey artifactKey, IProfile profile) { + IFileArtifactRepository aggregatedView = getAggregatedBundleRepository(agent, profile); File bundleJar = aggregatedView.getArtifactFile(artifactKey); return bundleJar; } @@ -303,9 +296,9 @@ public class Util { return null; } - public static String getManifest(ITouchpointData[] data) { - for (int i = 0; i < data.length; i++) { - ITouchpointInstruction manifestInstruction = data[i].getInstruction("manifest"); //$NON-NLS-1$ + public static String getManifest(List data) { + for (int i = 0; i < data.size(); i++) { + ITouchpointInstruction manifestInstruction = data.get(i).getInstruction("manifest"); //$NON-NLS-1$ if (manifestInstruction == null) return null; String manifest = manifestInstruction.getBody(); @@ -328,7 +321,7 @@ public class Util { return launcherConfig == null ? null : new File(launcherConfig); } - public static String resolveArtifactParam(Map parameters) throws CoreException { + public static String resolveArtifactParam(Map parameters) throws CoreException { String artifactLocation = (String) parameters.get(EclipseTouchpoint.PARM_ARTIFACT_LOCATION); if (artifactLocation != null) return artifactLocation; diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/ActionConstants.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/ActionConstants.java index 78a56eb6c..1a5c2d1d0 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/ActionConstants.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/ActionConstants.java @@ -10,6 +10,7 @@ package org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions; public class ActionConstants { + public static final String PARM_AGENT = "agent"; //$NON-NLS-1$ public static final String PARM_AT_ARTIFACT = "@artifact"; //$NON-NLS-1$ public static final String PARM_ARTIFACT_FILES = "artifactFiles"; //$NON-NLS-1$ public static final String PARM_ARTIFACT_REQUESTS = "artifactRequests"; //$NON-NLS-1$ diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddJVMArgumentAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddJVMArgumentAction.java index 816b41879..9268549a8 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddJVMArgumentAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddJVMArgumentAction.java @@ -15,7 +15,7 @@ import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.*; import org.eclipse.equinox.internal.provisional.frameworkadmin.LauncherData; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; import org.eclipse.osgi.util.NLS; public class AddJVMArgumentAction extends ProvisioningAction { @@ -27,14 +27,14 @@ public class AddJVMArgumentAction extends ProvisioningAction { protected static final String XX_MAX_PERM_SIZE = "-XX:MaxPermSize="; //$NON-NLS-1$ protected static final String PREFIX_USER_VALUE = "eclipse.userDefined:"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { String jvmArg = (String) parameters.get(ActionConstants.PARM_JVM_ARG); if (jvmArg == null) return Util.createError(NLS.bind(Messages.parameter_not_set, ActionConstants.PARM_JVM_ARG, ID)); return addArg(jvmArg, parameters); } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { String jvmArg = (String) parameters.get(ActionConstants.PARM_JVM_ARG); if (jvmArg == null) return Util.createError(NLS.bind(Messages.parameter_not_set, ActionConstants.PARM_JVM_ARG, ID)); @@ -45,7 +45,7 @@ public class AddJVMArgumentAction extends ProvisioningAction { return storedValues.getProperty(PREFIX_USER_VALUE + flag); } - protected static IStatus addArg(String arg, Map parameters) { + protected static IStatus addArg(String arg, Map parameters) { LauncherData launcherData = ((Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR)).getLauncherData(); File storageArea = (File) parameters.get(ActionConstants.PARM_PROFILE_DATA_DIRECTORY); try { @@ -215,7 +215,7 @@ public class AddJVMArgumentAction extends ProvisioningAction { if (argString == null || argString.length() == 0) return new String[0]; - List list = new ArrayList(); + List list = new ArrayList(); int i = 0; String arg = ""; //$NON-NLS-1$ @@ -230,10 +230,7 @@ public class AddJVMArgumentAction extends ProvisioningAction { } list.add(arg); - String[] argList = new String[list.size()]; - list.toArray(argList); - - return argList; + return list.toArray(new String[list.size()]); } // Store a single user argument, null removes stored values diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddProgramArgumentAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddProgramArgumentAction.java index 7672437dc..b44806f9d 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddProgramArgumentAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddProgramArgumentAction.java @@ -15,13 +15,13 @@ import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; import org.eclipse.osgi.util.NLS; public class AddProgramArgumentAction extends ProvisioningAction { public static final String ID = "addProgramArg"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { Manipulator manipulator = (Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); String programArg = (String) parameters.get(ActionConstants.PARM_PROGRAM_ARG); if (programArg == null) @@ -54,7 +54,7 @@ public class AddProgramArgumentAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { Manipulator manipulator = (Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); String programArg = (String) parameters.get(ActionConstants.PARM_PROGRAM_ARG); if (programArg == null) diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddRepositoryAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddRepositoryAction.java index 71bc26fed..2a05a1c2c 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddRepositoryAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddRepositoryAction.java @@ -14,6 +14,9 @@ import java.util.Map; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.engine.Profile; import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfileRegistry; /** * An action that adds a repository to the list of known repositories. @@ -21,15 +24,18 @@ import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; public class AddRepositoryAction extends RepositoryAction { public static final String ID = "addRepository"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { try { + IProvisioningAgent agent = getAgent(parameters); + IProfileRegistry registry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME); + IAgentLocation agentLocation = (IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME); final RepositoryEvent event = createEvent(parameters); Profile profile = (Profile) parameters.get(ActionConstants.PARM_PROFILE); if (profile != null) - addRepositoryToProfile(profile, event.getRepositoryLocation(), event.getRepositoryNickname(), event.getRepositoryType(), event.isRepositoryEnabled()); + addRepositoryToProfile(agentLocation, profile, event.getRepositoryLocation(), event.getRepositoryNickname(), event.getRepositoryType(), event.isRepositoryEnabled()); //if provisioning into the current profile, broadcast an event to add this repository directly to the current repository managers. - if (isSelfProfile(profile)) - addToSelf(event); + if (isSelfProfile(registry, profile)) + addToSelf(agentLocation, event); return Status.OK_STATUS; } catch (CoreException e) { return e.getStatus(); @@ -40,15 +46,18 @@ public class AddRepositoryAction extends RepositoryAction { return ID; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { try { + IProvisioningAgent agent = getAgent(parameters); + IProfileRegistry registry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME); + IAgentLocation agentLocation = (IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME); final RepositoryEvent event = createEvent(parameters); Profile profile = (Profile) parameters.get(ActionConstants.PARM_PROFILE); if (profile != null) - removeRepositoryFromProfile(profile, event.getRepositoryLocation(), event.getRepositoryType()); + removeRepositoryFromProfile(agentLocation, profile, event.getRepositoryLocation(), event.getRepositoryType()); //if provisioning into the current profile, broadcast an event to add this repository directly to the current repository managers. - if (isSelfProfile(profile)) - removeFromSelf(event); + if (isSelfProfile(registry, profile)) + removeFromSelf(agentLocation, event); return Status.OK_STATUS; } catch (CoreException e) { return e.getStatus(); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddSourceBundleAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddSourceBundleAction.java index 2f90c6aaa..640132ec5 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddSourceBundleAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/AddSourceBundleAction.java @@ -10,28 +10,31 @@ package org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions; import java.io.File; import java.io.IOException; +import java.util.Collection; import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.osgi.util.NLS; public class AddSourceBundleAction extends ProvisioningAction { public static final String ID = "addSourceBundle"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { return AddSourceBundleAction.addSourceBundle(parameters); } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { return RemoveSourceBundleAction.removeSourceBundle(parameters); } - public static IStatus addSourceBundle(Map parameters) { + public static IStatus addSourceBundle(Map parameters) { + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(ActionConstants.PARM_AGENT); IProfile profile = (IProfile) parameters.get(ActionConstants.PARM_PROFILE); IInstallableUnit iu = (IInstallableUnit) parameters.get(EclipseTouchpoint.PARM_IU); SourceManipulator manipulator = (SourceManipulator) parameters.get(EclipseTouchpoint.PARM_SOURCE_BUNDLES); @@ -39,21 +42,21 @@ public class AddSourceBundleAction extends ProvisioningAction { if (bundleId == null) return Util.createError(NLS.bind(Messages.parameter_not_set, ActionConstants.PARM_BUNDLE, ID)); - IArtifactKey[] artifacts = iu.getArtifacts(); - if (artifacts == null || artifacts.length == 0) + Collection artifacts = iu.getArtifacts(); + if (artifacts == null || artifacts.size() == 0) return Util.createError(NLS.bind(Messages.iu_contains_no_arifacts, iu)); IArtifactKey artifactKey = null; - for (int i = 0; i < artifacts.length; i++) { - if (artifacts[i].toString().equals(bundleId)) { - artifactKey = artifacts[i]; + for (IArtifactKey candidate : artifacts) { + if (candidate.toString().equals(bundleId)) { + artifactKey = candidate; break; } } if (artifactKey == null) throw new IllegalArgumentException(NLS.bind(Messages.no_matching_artifact, bundleId)); - File bundleFile = Util.getArtifactFile(artifactKey, profile); + File bundleFile = Util.getArtifactFile(agent, artifactKey, profile); if (bundleFile == null || !bundleFile.exists()) return Util.createError(NLS.bind(Messages.artifact_file_not_found, artifactKey)); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/CheckTrustAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/CheckTrustAction.java index 027ef3d5f..7eb0d940b 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/CheckTrustAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/CheckTrustAction.java @@ -17,12 +17,12 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; /** * This action collects the set of bundle files on which the signature trust check @@ -35,20 +35,22 @@ public class CheckTrustAction extends ProvisioningAction { /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction#execute(java.util.Map) */ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { IInstallableUnit iu = (IInstallableUnit) parameters.get(EclipseTouchpoint.PARM_IU); if (iu == null) return null; + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(ActionConstants.PARM_AGENT); IProfile profile = (IProfile) parameters.get(ActionConstants.PARM_PROFILE); //if the IU is already in the profile there is nothing to do - if (!profile.available(new InstallableUnitQuery(iu), new Collector(), null).isEmpty()) + if (!profile.available(new InstallableUnitQuery(iu), null).isEmpty()) return null; - Collection bundleFiles = (Collection) parameters.get(ActionConstants.PARM_ARTIFACT_FILES); - IArtifactKey[] artifacts = iu.getArtifacts(); + @SuppressWarnings("unchecked") + Collection bundleFiles = (Collection) parameters.get(ActionConstants.PARM_ARTIFACT_FILES); + Collection artifacts = iu.getArtifacts(); if (artifacts == null) return null; - for (int i = 0; i < artifacts.length; i++) { - File bundleFile = Util.getArtifactFile(artifacts[i], profile); + for (IArtifactKey key : artifacts) { + File bundleFile = Util.getArtifactFile(agent, key, profile); if (!bundleFiles.contains(bundleFile)) bundleFiles.add(bundleFile); } @@ -58,7 +60,7 @@ public class CheckTrustAction extends ProvisioningAction { /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction#undo(java.util.Map) */ - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { return Status.OK_STATUS; } } diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/ChmodAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/ChmodAction.java index 0aaeb6717..bc1d51d80 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/ChmodAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/ChmodAction.java @@ -17,7 +17,7 @@ import java.util.ArrayList; import java.util.Map; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; import org.eclipse.osgi.util.NLS; // This basically a copy of the chmod action in the native touchpoint only it provides @artifact support. @@ -25,7 +25,7 @@ import org.eclipse.osgi.util.NLS; public class ChmodAction extends ProvisioningAction { private static final String ACTION_CHMOD = "chmod"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { String targetDir = (String) parameters.get(ActionConstants.PARM_TARGET_DIR); if (targetDir == null) return Util.createError(NLS.bind(Messages.parameter_not_set, ActionConstants.PARM_TARGET_DIR, ACTION_CHMOD)); @@ -57,7 +57,7 @@ public class ChmodAction extends ProvisioningAction { String options[] = null; if (optionsString != null) { - ArrayList collect = new ArrayList(); + ArrayList collect = new ArrayList(); String r = optionsString.trim(); while (r.length() > 0) { int spaceIdx = r.indexOf(' '); @@ -71,8 +71,7 @@ public class ChmodAction extends ProvisioningAction { } } if (collect.size() > 0) { - options = new String[collect.size()]; - collect.toArray(options); + options = collect.toArray(new String[collect.size()]); } } @@ -80,7 +79,7 @@ public class ChmodAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { //TODO: implement undo ?? return Status.OK_STATUS; } diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/CollectAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/CollectAction.java index f1932a576..4ac0e4109 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/CollectAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/CollectAction.java @@ -12,79 +12,83 @@ import java.util.*; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.repository.artifact.*; import org.eclipse.osgi.util.NLS; public class CollectAction extends ProvisioningAction { public static final String ID = "collect"; //$NON-NLS-1$ public static final String ARTIFACT_FOLDER = "artifact.folder"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(ActionConstants.PARM_AGENT); IProfile profile = (IProfile) parameters.get(ActionConstants.PARM_PROFILE); InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(ActionConstants.PARM_OPERAND); IArtifactRequest[] requests; try { - requests = CollectAction.collect(operand.second(), profile); + requests = CollectAction.collect(agent, profile, operand.second()); } catch (ProvisionException e) { return e.getStatus(); } - Collection artifactRequests = (Collection) parameters.get(ActionConstants.PARM_ARTIFACT_REQUESTS); + @SuppressWarnings("unchecked") + Collection artifactRequests = (Collection) parameters.get(ActionConstants.PARM_ARTIFACT_REQUESTS); artifactRequests.add(requests); return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { // nothing to do for now return Status.OK_STATUS; } - public static boolean isZipped(ITouchpointData[] data) { - if (data == null || data.length == 0) + public static boolean isZipped(List data) { + if (data == null || data.size() == 0) return false; - for (int i = 0; i < data.length; i++) { - if (data[i].getInstruction("zipped") != null) //$NON-NLS-1$ + for (int i = 0; i < data.size(); i++) { + if (data.get(i).getInstruction("zipped") != null) //$NON-NLS-1$ return true; } return false; } - public static Properties createArtifactDescriptorProperties(IInstallableUnit installableUnit) { - Properties descriptorProperties = null; + public static Map createArtifactDescriptorProperties(IInstallableUnit installableUnit) { + Map descriptorProperties = null; if (CollectAction.isZipped(installableUnit.getTouchpointData())) { - descriptorProperties = new Properties(); - descriptorProperties.setProperty(CollectAction.ARTIFACT_FOLDER, Boolean.TRUE.toString()); + descriptorProperties = new HashMap(); + descriptorProperties.put(CollectAction.ARTIFACT_FOLDER, Boolean.TRUE.toString()); } return descriptorProperties; } // TODO: Here we may want to consult multiple caches - public static IArtifactRequest[] collect(IInstallableUnit installableUnit, IProfile profile) throws ProvisionException { - IArtifactKey[] toDownload = installableUnit.getArtifacts(); - if (toDownload == null || toDownload.length == 0) + static IArtifactRequest[] collect(IProvisioningAgent agent, IProfile profile, IInstallableUnit installableUnit) throws ProvisionException { + Collection toDownload = installableUnit.getArtifacts(); + if (toDownload == null || toDownload.size() == 0) return IArtifactRepositoryManager.NO_ARTIFACT_REQUEST; - IArtifactRepository aggregatedRepositoryView = Util.getAggregatedBundleRepository(profile); - IArtifactRepository bundlePool = Util.getBundlePoolRepository(profile); + IArtifactRepository aggregatedRepositoryView = Util.getAggregatedBundleRepository(agent, profile); + IArtifactRepository bundlePool = Util.getBundlePoolRepository(agent, profile); if (bundlePool == null) throw new ProvisionException(Util.createError(NLS.bind(Messages.no_bundle_pool, profile.getProfileId()))); - List requests = new ArrayList(); - for (int i = 0; i < toDownload.length; i++) { - IArtifactKey key = toDownload[i]; + List requests = new ArrayList(); + for (IArtifactKey key : toDownload) { if (!aggregatedRepositoryView.contains(key)) { - Properties repositoryProperties = CollectAction.createArtifactDescriptorProperties(installableUnit); - requests.add(Util.getArtifactRepositoryManager().createMirrorRequest(key, bundlePool, null, repositoryProperties)); + Map repositoryProperties = CollectAction.createArtifactDescriptorProperties(installableUnit); + requests.add(Util.getArtifactRepositoryManager(agent).createMirrorRequest(key, bundlePool, null, repositoryProperties)); } } if (requests.isEmpty()) return IArtifactRepositoryManager.NO_ARTIFACT_REQUEST; - IArtifactRequest[] result = (IArtifactRequest[]) requests.toArray(new IArtifactRequest[requests.size()]); + IArtifactRequest[] result = requests.toArray(new IArtifactRequest[requests.size()]); return result; } } \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/InstallBundleAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/InstallBundleAction.java index ebfc1240f..c3ef27ec8 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/InstallBundleAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/InstallBundleAction.java @@ -9,6 +9,7 @@ package org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions; import java.io.File; +import java.util.Collection; import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; @@ -16,24 +17,27 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.FragmentQuery; import org.eclipse.osgi.util.NLS; public class InstallBundleAction extends ProvisioningAction { public static final String ID = "installBundle"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { return InstallBundleAction.installBundle(parameters); } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { return UninstallBundleAction.uninstallBundle(parameters); } - public static IStatus installBundle(Map parameters) { + public static IStatus installBundle(Map parameters) { + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(ActionConstants.PARM_AGENT); IProfile profile = (IProfile) parameters.get(ActionConstants.PARM_PROFILE); IInstallableUnit iu = (IInstallableUnit) parameters.get(EclipseTouchpoint.PARM_IU); Manipulator manipulator = (Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); @@ -42,26 +46,26 @@ public class InstallBundleAction extends ProvisioningAction { return Util.createError(NLS.bind(Messages.parameter_not_set, ActionConstants.PARM_BUNDLE, ID)); //TODO: eventually remove this. What is a fragment doing here?? - if (iu.isFragment()) { + if (FragmentQuery.isFragment(iu)) { System.out.println("What is a fragment doing here!!! -- " + iu); //$NON-NLS-1$ return Status.OK_STATUS; } - IArtifactKey[] artifacts = iu.getArtifacts(); - if (artifacts == null || artifacts.length == 0) + Collection artifacts = iu.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) return Util.createError(NLS.bind(Messages.iu_contains_no_arifacts, iu)); IArtifactKey artifactKey = null; - for (int i = 0; i < artifacts.length; i++) { - if (artifacts[i].toString().equals(bundleId)) { - artifactKey = artifacts[i]; + for (IArtifactKey candidate : artifacts) { + if (candidate.toString().equals(bundleId)) { + artifactKey = candidate; break; } } if (artifactKey == null) throw new IllegalArgumentException(NLS.bind(Messages.no_matching_artifact, bundleId)); - File bundleFile = Util.getArtifactFile(artifactKey, profile); + File bundleFile = Util.getArtifactFile(agent, artifactKey, profile); if (bundleFile == null || !bundleFile.exists()) return Util.createError(NLS.bind(Messages.artifact_file_not_found, artifactKey)); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/InstallFeatureAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/InstallFeatureAction.java index f0575ebe1..b9d55ba06 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/InstallFeatureAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/InstallFeatureAction.java @@ -9,14 +9,16 @@ package org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions; import java.io.File; +import java.util.Collection; import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.*; import org.eclipse.equinox.internal.p2.update.Site; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.osgi.util.NLS; public class InstallFeatureAction extends ProvisioningAction { @@ -25,29 +27,29 @@ public class InstallFeatureAction extends ProvisioningAction { private static final String UPDATE_FEATURE_PLUGIN_PROP = "org.eclipse.update.feature.plugin"; //$NON-NLS-1$ private static final String UPDATE_FEATURE_PRIMARY_PROP = "org.eclipse.update.feature.primary"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { return InstallFeatureAction.installFeature(parameters); } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { return UninstallFeatureAction.uninstallFeature(parameters); } - public static IStatus installFeature(Map parameters) { + public static IStatus installFeature(Map parameters) { IInstallableUnit iu = (IInstallableUnit) parameters.get(EclipseTouchpoint.PARM_IU); PlatformConfigurationWrapper configuration = (PlatformConfigurationWrapper) parameters.get(EclipseTouchpoint.PARM_PLATFORM_CONFIGURATION); String feature = (String) parameters.get(ActionConstants.PARM_FEATURE); String featureId = (String) parameters.get(ActionConstants.PARM_FEATURE_ID); String featureVersion = (String) parameters.get(ActionConstants.PARM_FEATURE_VERSION); - IArtifactKey[] artifacts = iu.getArtifacts(); - if (artifacts == null || artifacts.length == 0) + Collection artifacts = iu.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) return Util.createError(NLS.bind(Messages.iu_contains_no_arifacts, iu)); IArtifactKey artifactKey = null; - for (int i = 0; i < artifacts.length; i++) { - if (artifacts[i].toString().equals(feature)) { - artifactKey = artifacts[i]; + for (IArtifactKey candidate : artifacts) { + if (candidate.toString().equals(feature)) { + artifactKey = candidate; break; } } @@ -64,8 +66,9 @@ public class InstallFeatureAction extends ProvisioningAction { featureVersion = artifactKey.getVersion().toString(); } + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(ActionConstants.PARM_AGENT); IProfile profile = (IProfile) parameters.get(ActionConstants.PARM_PROFILE); - File file = Util.getArtifactFile(artifactKey, profile); + File file = Util.getArtifactFile(agent, artifactKey, profile); if (file == null || !file.exists()) { return Util.createError(NLS.bind(Messages.artifact_file_not_found, artifactKey)); } diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/LinkAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/LinkAction.java index 13b860045..708d8bf69 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/LinkAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/LinkAction.java @@ -14,7 +14,7 @@ import java.io.*; import java.util.Map; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; import org.eclipse.osgi.util.NLS; //This is basically a copy of the ln action in the native touchpoint only it provides @artifact support and does not support the backup store. @@ -22,7 +22,7 @@ import org.eclipse.osgi.util.NLS; public class LinkAction extends ProvisioningAction { public static final String ID = "ln"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { String targetDir = (String) parameters.get(ActionConstants.PARM_TARGET_DIR); if (targetDir == null) return Util.createError(NLS.bind(Messages.parameter_not_set, ActionConstants.PARM_TARGET_DIR, ID)); @@ -53,7 +53,7 @@ public class LinkAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { return null; } diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/MarkStartedAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/MarkStartedAction.java index 744b266bb..fb27f1197 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/MarkStartedAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/MarkStartedAction.java @@ -11,6 +11,7 @@ package org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions; import java.io.File; +import java.util.Collection; import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; @@ -18,16 +19,18 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.osgi.util.NLS; public class MarkStartedAction extends ProvisioningAction { public static final String ID = "markStarted"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(ActionConstants.PARM_AGENT); IProfile profile = (IProfile) parameters.get(ActionConstants.PARM_PROFILE); Manipulator manipulator = (Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); IInstallableUnit iu = (IInstallableUnit) parameters.get(EclipseTouchpoint.PARM_IU); @@ -35,14 +38,14 @@ public class MarkStartedAction extends ProvisioningAction { if (started == null) return Util.createError(NLS.bind(Messages.parameter_not_set, ActionConstants.PARM_STARTED, ID)); - IArtifactKey[] artifacts = iu.getArtifacts(); - if (artifacts == null || artifacts.length == 0) + Collection artifacts = iu.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) return Util.createError(NLS.bind(Messages.iu_contains_no_arifacts, iu)); - IArtifactKey artifactKey = artifacts[0]; + IArtifactKey artifactKey = artifacts.iterator().next(); // the bundleFile might be null here, that's OK. - File bundleFile = Util.getArtifactFile(artifactKey, profile); + File bundleFile = Util.getArtifactFile(agent, artifactKey, profile); String manifest = Util.getManifest(iu.getTouchpointData()); if (manifest == null) @@ -66,7 +69,8 @@ public class MarkStartedAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(ActionConstants.PARM_AGENT); Boolean previousStarted = (Boolean) getMemento().get(ActionConstants.PARM_PREVIOUS_STARTED); if (previousStarted == null) return Status.OK_STATUS; @@ -75,13 +79,13 @@ public class MarkStartedAction extends ProvisioningAction { Manipulator manipulator = (Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); IInstallableUnit iu = (IInstallableUnit) parameters.get(EclipseTouchpoint.PARM_IU); - IArtifactKey[] artifacts = iu.getArtifacts(); - if (artifacts == null || artifacts.length == 0) + Collection artifacts = iu.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) return Util.createError(NLS.bind(Messages.iu_contains_no_arifacts, iu)); - IArtifactKey artifactKey = artifacts[0]; + IArtifactKey artifactKey = artifacts.iterator().next(); // the bundleFile might be null here, that's OK. - File bundleFile = Util.getArtifactFile(artifactKey, profile); + File bundleFile = Util.getArtifactFile(agent, artifactKey, profile); String manifest = Util.getManifest(iu.getTouchpointData()); if (manifest == null) diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveJVMArgumentAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveJVMArgumentAction.java index 3560e8acd..10d00d6ad 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveJVMArgumentAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveJVMArgumentAction.java @@ -17,13 +17,13 @@ import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.*; import org.eclipse.equinox.internal.provisional.frameworkadmin.LauncherData; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; import org.eclipse.osgi.util.NLS; public class RemoveJVMArgumentAction extends ProvisioningAction { public static final String ID = "removeJvmArg"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { String jvmArg = (String) parameters.get(ActionConstants.PARM_JVM_ARG); if (jvmArg == null) return Util.createError(NLS.bind(Messages.parameter_not_set, ActionConstants.PARM_JVM_ARG, ID)); @@ -31,7 +31,7 @@ public class RemoveJVMArgumentAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { String jvmArg = (String) parameters.get(ActionConstants.PARM_JVM_ARG); if (jvmArg == null) return Util.createError(NLS.bind(Messages.parameter_not_set, ActionConstants.PARM_JVM_ARG, ID)); @@ -39,7 +39,7 @@ public class RemoveJVMArgumentAction extends ProvisioningAction { return Status.OK_STATUS; } - public static IStatus removeArg(String arg, Map parameters) { + public static IStatus removeArg(String arg, Map parameters) { LauncherData launcherData = ((Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR)).getLauncherData(); File storageArea = (File) parameters.get(ActionConstants.PARM_PROFILE_DATA_DIRECTORY); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveProgramArgumentAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveProgramArgumentAction.java index 5cc2277ae..e61c38692 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveProgramArgumentAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveProgramArgumentAction.java @@ -16,21 +16,21 @@ import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; import org.eclipse.osgi.util.NLS; public class RemoveProgramArgumentAction extends ProvisioningAction { public static final String ID = "removeProgramArg"; //$NON-NLS-1$ public static final String EMPTY_ARGUMENT = ""; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { Manipulator manipulator = (Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); String programArg = (String) parameters.get(ActionConstants.PARM_PROGRAM_ARG); if (programArg == null) return Util.createError(NLS.bind(Messages.parameter_not_set, ActionConstants.PARM_PROGRAM_ARG, ID)); if (programArg.startsWith("-")) {//$NON-NLS-1$ - List programArgs = Arrays.asList(manipulator.getLauncherData().getProgramArgs()); + List programArgs = Arrays.asList(manipulator.getLauncherData().getProgramArgs()); int index = programArgs.indexOf(programArg); if (index == -1) @@ -38,7 +38,7 @@ public class RemoveProgramArgumentAction extends ProvisioningAction { index++; // move index to potential programArgValue if (programArgs.size() > index) { - String programArgValue = (String) programArgs.get(index); + String programArgValue = programArgs.get(index); if (!programArgValue.startsWith("-")) //$NON-NLS-1$ getMemento().put(ActionConstants.PARM_PROGRAM_ARG_VALUE, programArgValue); } @@ -48,7 +48,7 @@ public class RemoveProgramArgumentAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { Manipulator manipulator = (Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); String programArg = (String) parameters.get(ActionConstants.PARM_PROGRAM_ARG); if (programArg == null) diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveRepositoryAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveRepositoryAction.java index 4f4fd25ba..b1d388932 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveRepositoryAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveRepositoryAction.java @@ -14,6 +14,9 @@ import java.util.Map; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.engine.Profile; import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfileRegistry; /** * An action that adds a repository to the list of known repositories. @@ -21,30 +24,36 @@ import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; public class RemoveRepositoryAction extends RepositoryAction { public static final String ID = "removeRepository"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { try { + IProvisioningAgent agent = getAgent(parameters); + IProfileRegistry registry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME); + IAgentLocation agentLocation = (IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME); RepositoryEvent event = createEvent(parameters); Profile profile = (Profile) parameters.get(ActionConstants.PARM_PROFILE); if (profile != null) - removeRepositoryFromProfile(profile, event.getRepositoryLocation(), event.getRepositoryType()); + removeRepositoryFromProfile(agentLocation, profile, event.getRepositoryLocation(), event.getRepositoryType()); //if we are provisioning into the self profile, update the current set of repositories in this configuration - if (isSelfProfile(profile)) - removeFromSelf(event); + if (isSelfProfile(registry, profile)) + removeFromSelf(agentLocation, event); } catch (CoreException e) { return e.getStatus(); } return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { try { + IProvisioningAgent agent = getAgent(parameters); + IProfileRegistry registry = (IProfileRegistry) agent.getService(IProfileRegistry.SERVICE_NAME); + IAgentLocation agentLocation = (IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME); RepositoryEvent event = createEvent(parameters); Profile profile = (Profile) parameters.get(ActionConstants.PARM_PROFILE); if (profile != null) - addRepositoryToProfile(profile, event.getRepositoryLocation(), event.getRepositoryNickname(), event.getRepositoryType(), event.isRepositoryEnabled()); + addRepositoryToProfile(agentLocation, profile, event.getRepositoryLocation(), event.getRepositoryNickname(), event.getRepositoryType(), event.isRepositoryEnabled()); //if we are provisioning into the self profile, update the current set of repositories in this configuration - if (isSelfProfile(profile)) - addToSelf(event); + if (isSelfProfile(registry, profile)) + addToSelf(agentLocation, event); return Status.OK_STATUS; } catch (CoreException e) { return e.getStatus(); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveSourceBundleAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveSourceBundleAction.java index 21b1a1490..c94490478 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveSourceBundleAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RemoveSourceBundleAction.java @@ -10,28 +10,31 @@ package org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions; import java.io.File; import java.io.IOException; +import java.util.Collection; import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.osgi.util.NLS; public class RemoveSourceBundleAction extends ProvisioningAction { public static final String ID = "removeSourceBundle"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { return RemoveSourceBundleAction.removeSourceBundle(parameters); } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { return AddSourceBundleAction.addSourceBundle(parameters); } - public static IStatus removeSourceBundle(Map parameters) { + public static IStatus removeSourceBundle(Map parameters) { + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(ActionConstants.PARM_AGENT); IProfile profile = (IProfile) parameters.get(ActionConstants.PARM_PROFILE); IInstallableUnit iu = (IInstallableUnit) parameters.get(EclipseTouchpoint.PARM_IU); SourceManipulator manipulator = (SourceManipulator) parameters.get(EclipseTouchpoint.PARM_SOURCE_BUNDLES); @@ -39,14 +42,14 @@ public class RemoveSourceBundleAction extends ProvisioningAction { if (bundleId == null) return Util.createError(NLS.bind(Messages.parameter_not_set, ActionConstants.PARM_BUNDLE, ID)); - IArtifactKey[] artifacts = iu.getArtifacts(); - if (artifacts == null || artifacts.length == 0) + Collection artifacts = iu.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) return Util.createError(NLS.bind(Messages.iu_contains_no_arifacts, iu)); IArtifactKey artifactKey = null; - for (int i = 0; i < artifacts.length; i++) { - if (artifacts[i].toString().equals(bundleId)) { - artifactKey = artifacts[i]; + for (IArtifactKey candidate : artifacts) { + if (candidate.toString().equals(bundleId)) { + artifactKey = candidate; break; } } @@ -54,7 +57,7 @@ public class RemoveSourceBundleAction extends ProvisioningAction { throw new IllegalArgumentException(NLS.bind(Messages.no_matching_artifact, bundleId)); // the bundleFile might be null here, that's OK. - File bundleFile = Util.getArtifactFile(artifactKey, profile); + File bundleFile = Util.getArtifactFile(agent, artifactKey, profile); try { manipulator.removeBundle(bundleFile, artifactKey.getId(), artifactKey.getVersion()); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RepositoryAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RepositoryAction.java index b3bbf9fe1..38defc24c 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RepositoryAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/RepositoryAction.java @@ -14,15 +14,19 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.preferences.IPreferencesService; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.engine.Profile; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Activator; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.*; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.osgi.util.NLS; import org.osgi.service.prefs.BackingStoreException; import org.osgi.service.prefs.Preferences; @@ -49,11 +53,11 @@ abstract class RepositoryAction extends ProvisioningAction { * Returns the repository manager of the given type, or null * if not available. */ - private static IRepositoryManager getRepositoryManager(int type) { + private static IRepositoryManager getRepositoryManager(int type) { if (type == IRepository.TYPE_METADATA) { - return (IRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); + return (IRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); } else if (type == IRepository.TYPE_ARTIFACT) { - return (IRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); + return (IRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.SERVICE_NAME); } return null; } @@ -62,8 +66,8 @@ abstract class RepositoryAction extends ProvisioningAction { * Associates the repository described by the given event with the given profile. * Has no effect if the repository is already associated with this profile. */ - protected void addRepositoryToProfile(Profile profile, URI location, String nickname, int type, boolean enabled) { - Preferences node = getRepositoryPreferenceNode(profile, location, type); + protected void addRepositoryToProfile(IAgentLocation agentLocation, Profile profile, URI location, String nickname, int type, boolean enabled) { + Preferences node = getRepositoryPreferenceNode(agentLocation, profile, location, type); int count = 0; if (repositoryExists(node)) { @@ -88,10 +92,10 @@ abstract class RepositoryAction extends ProvisioningAction { /** * Adds the repository corresponding to the given event to the currently running instance. */ - protected void addToSelf(RepositoryEvent event) { - IRepositoryManager manager = getRepositoryManager(event.getRepositoryType()); + protected void addToSelf(IAgentLocation agentLocation, RepositoryEvent event) { + IRepositoryManager manager = getRepositoryManager(event.getRepositoryType()); final URI location = event.getRepositoryLocation(); - Preferences node = getRepositoryPreferenceNode(null, location, event.getRepositoryType()); + Preferences node = getRepositoryPreferenceNode(agentLocation, null, location, event.getRepositoryType()); int count = getRepositoryCount(node); if (manager.contains(location)) { @@ -113,7 +117,7 @@ abstract class RepositoryAction extends ProvisioningAction { manager.setRepositoryProperty(location, IRepository.PROP_NICKNAME, name); } - protected RepositoryEvent createEvent(Map parameters) throws CoreException { + protected RepositoryEvent createEvent(Map parameters) throws CoreException { String parm = (String) parameters.get(ActionConstants.PARM_REPOSITORY_LOCATION); if (parm == null) throw new CoreException(Util.createError(NLS.bind(Messages.parameter_not_set, ActionConstants.PARM_REPOSITORY_LOCATION, getId()))); @@ -148,11 +152,10 @@ abstract class RepositoryAction extends ProvisioningAction { * Return true if the given profile is the currently running profile, * and false otherwise. */ - protected boolean isSelfProfile(Profile profile) { + protected boolean isSelfProfile(IProfileRegistry registry, Profile profile) { //if we can't determine the current profile, assume we are running on self if (profile == null) return true; - IProfileRegistry registry = (IProfileRegistry) ServiceHelper.getService(Activator.getContext(), IProfileRegistry.class.getName()); if (registry == null) return false; final IProfile selfProfile = registry.getProfile(IProfileRegistry.SELF); @@ -165,9 +168,9 @@ abstract class RepositoryAction extends ProvisioningAction { /** * Removes the repository corresponding to the given event from the currently running instance. */ - protected void removeFromSelf(RepositoryEvent event) { - IRepositoryManager manager = getRepositoryManager(event.getRepositoryType()); - Preferences node = getRepositoryPreferenceNode(null, event.getRepositoryLocation(), event.getRepositoryType()); + protected void removeFromSelf(IAgentLocation agentLocation, RepositoryEvent event) { + IRepositoryManager manager = getRepositoryManager(event.getRepositoryType()); + Preferences node = getRepositoryPreferenceNode(agentLocation, null, event.getRepositoryLocation(), event.getRepositoryType()); int count = getRepositoryCount(node); if (--count < 1 && manager != null) manager.removeRepository(event.getRepositoryLocation()); @@ -179,8 +182,8 @@ abstract class RepositoryAction extends ProvisioningAction { * and the given profile. Has no effect if the location is not already associated with * this profile. */ - protected void removeRepositoryFromProfile(Profile profile, URI location, int type) { - Preferences node = getRepositoryPreferenceNode(profile, location, type); + protected void removeRepositoryFromProfile(IAgentLocation agentLocation, Profile profile, URI location, int type) { + Preferences node = getRepositoryPreferenceNode(agentLocation, profile, location, type); int count = getRepositoryCount(node); if (--count < 1) { @@ -233,13 +236,10 @@ abstract class RepositoryAction extends ProvisioningAction { /* * Get the preference node associated with profile & location */ - protected Preferences getRepositoryPreferenceNode(Profile profile, URI location, int type) { + protected Preferences getRepositoryPreferenceNode(IAgentLocation agentLocation, Profile profile, URI location, int type) { String key = type == IRepository.TYPE_METADATA ? METADATA_REPOSITORY : ARTIFACT_REPOSITORY; - IPreferencesService prefService = (IPreferencesService) ServiceHelper.getService(Activator.getContext(), IPreferencesService.class.getName()); - - if (profile != null) - return prefService.getRootNode().node("/profile/" + profile.getProfileId() + "/" + key + "/" + NODE_REPOSITORIES + "/" + getKey(location)); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ - return prefService.getRootNode().node("/profile/_SELF_/" + key + "/" + NODE_REPOSITORIES + "/" + getKey(location)); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + String profileId = profile == null ? IProfileRegistry.SELF : profile.getProfileId(); + return new ProfileScope(agentLocation, profileId).getNode(key + '/' + NODE_REPOSITORIES + '/' + getKey(location)); } /* @@ -252,4 +252,12 @@ abstract class RepositoryAction extends ProvisioningAction { key = key.substring(0, key.length() - 1); return key; } + + protected IProvisioningAgent getAgent(Map parameters) throws CoreException { + //We shouldn't really know about the session parameter + IProvisioningAgent agent = (IProvisioningAgent) parameters.get("agent"); //$NON-NLS-1$ + if (agent == null) + throw new CoreException(Util.createError(NLS.bind(Messages.parameter_not_set, "agent", getId()))); //$NON-NLS-1$ + return agent; + } } diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/SetLauncherNameAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/SetLauncherNameAction.java index 040c44de8..6fadd2397 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/SetLauncherNameAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/SetLauncherNameAction.java @@ -16,12 +16,12 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.provisional.frameworkadmin.LauncherData; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; public class SetLauncherNameAction extends ProvisioningAction { public static final String ID = "setLauncherName"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { Manipulator manipulator = (Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); Profile profile = (Profile) parameters.get(ActionConstants.PARM_PROFILE); getMemento().put(EclipseTouchpoint.PROFILE_PROP_LAUNCHER_NAME, profile.getProperty(EclipseTouchpoint.PROFILE_PROP_LAUNCHER_NAME)); @@ -30,7 +30,7 @@ public class SetLauncherNameAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { Manipulator manipulator = (Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); Profile profile = (Profile) parameters.get(ActionConstants.PARM_PROFILE); String previousLauncherName = (String) getMemento().get(EclipseTouchpoint.PROFILE_PROP_LAUNCHER_NAME); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/SetProgramPropertyAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/SetProgramPropertyAction.java index 7d31fbc4e..e334402a8 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/SetProgramPropertyAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/SetProgramPropertyAction.java @@ -15,13 +15,13 @@ import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; import org.eclipse.osgi.util.NLS; public class SetProgramPropertyAction extends ProvisioningAction { public static final String ID = "setProgramProperty"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { Manipulator manipulator = (Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); String propName = (String) parameters.get(ActionConstants.PARM_PROP_NAME); if (propName == null) @@ -40,7 +40,7 @@ public class SetProgramPropertyAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { Manipulator manipulator = (Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); String propName = (String) parameters.get(ActionConstants.PARM_PROP_NAME); if (propName == null) diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/SetStartLevelAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/SetStartLevelAction.java index 55c7314e8..827d8e0d0 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/SetStartLevelAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/SetStartLevelAction.java @@ -11,6 +11,7 @@ package org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions; import java.io.File; +import java.util.Collection; import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; @@ -18,16 +19,18 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.osgi.util.NLS; public class SetStartLevelAction extends ProvisioningAction { public static final String ID = "setStartLevel"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(ActionConstants.PARM_AGENT); IProfile profile = (IProfile) parameters.get(ActionConstants.PARM_PROFILE); Manipulator manipulator = (Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); IInstallableUnit iu = (IInstallableUnit) parameters.get(EclipseTouchpoint.PARM_IU); @@ -35,13 +38,13 @@ public class SetStartLevelAction extends ProvisioningAction { if (startLevel == null) return Util.createError(NLS.bind(Messages.parameter_not_set, ActionConstants.PARM_START_LEVEL, ID)); - IArtifactKey[] artifacts = iu.getArtifacts(); - if (artifacts == null || artifacts.length == 0) + Collection artifacts = iu.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) return Util.createError(NLS.bind(Messages.iu_contains_no_arifacts, iu)); - IArtifactKey artifactKey = artifacts[0]; + IArtifactKey artifactKey = artifacts.iterator().next(); // the bundleFile might be null here, that's OK. - File bundleFile = Util.getArtifactFile(artifactKey, profile); + File bundleFile = Util.getArtifactFile(agent, artifactKey, profile); String manifest = Util.getManifest(iu.getTouchpointData()); if (manifest == null) @@ -69,7 +72,8 @@ public class SetStartLevelAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(ActionConstants.PARM_AGENT); Integer previousStartLevel = (Integer) getMemento().get(ActionConstants.PARM_PREVIOUS_START_LEVEL); if (previousStartLevel == null) return Status.OK_STATUS; @@ -78,13 +82,13 @@ public class SetStartLevelAction extends ProvisioningAction { Manipulator manipulator = (Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); IInstallableUnit iu = (IInstallableUnit) parameters.get(EclipseTouchpoint.PARM_IU); - IArtifactKey[] artifacts = iu.getArtifacts(); - if (artifacts == null || artifacts.length == 0) + Collection artifacts = iu.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) return Util.createError(NLS.bind(Messages.iu_contains_no_arifacts, iu)); - IArtifactKey artifactKey = artifacts[0]; + IArtifactKey artifactKey = artifacts.iterator().next(); // the bundleFile might be null here, that's OK. - File bundleFile = Util.getArtifactFile(artifactKey, profile); + File bundleFile = Util.getArtifactFile(agent, artifactKey, profile); String manifest = Util.getManifest(iu.getTouchpointData()); if (manifest == null) diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/UninstallBundleAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/UninstallBundleAction.java index daf1ec901..7eb4356c1 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/UninstallBundleAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/UninstallBundleAction.java @@ -9,6 +9,7 @@ package org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions; import java.io.File; +import java.util.Collection; import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; @@ -16,24 +17,27 @@ import org.eclipse.equinox.internal.p2.touchpoint.eclipse.EclipseTouchpoint; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; import org.eclipse.equinox.internal.provisional.frameworkadmin.BundleInfo; import org.eclipse.equinox.internal.provisional.frameworkadmin.Manipulator; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.FragmentQuery; import org.eclipse.osgi.util.NLS; public class UninstallBundleAction extends ProvisioningAction { public static final String ID = "uninstallBundle"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { return UninstallBundleAction.uninstallBundle(parameters); } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { return InstallBundleAction.installBundle(parameters); } - public static IStatus uninstallBundle(Map parameters) { + public static IStatus uninstallBundle(Map parameters) { + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(ActionConstants.PARM_AGENT); IProfile profile = (IProfile) parameters.get(ActionConstants.PARM_PROFILE); IInstallableUnit iu = (IInstallableUnit) parameters.get(EclipseTouchpoint.PARM_IU); Manipulator manipulator = (Manipulator) parameters.get(EclipseTouchpoint.PARM_MANIPULATOR); @@ -42,19 +46,19 @@ public class UninstallBundleAction extends ProvisioningAction { return Util.createError(NLS.bind(Messages.parameter_not_set, ActionConstants.PARM_BUNDLE, ID)); //TODO: eventually remove this. What is a fragment doing here?? - if (iu.isFragment()) { + if (FragmentQuery.isFragment(iu)) { System.out.println("What is a fragment doing here!!! -- " + iu); //$NON-NLS-1$ return Status.OK_STATUS; } - IArtifactKey[] artifacts = iu.getArtifacts(); - if (artifacts == null || artifacts.length == 0) + Collection artifacts = iu.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) return Util.createError(NLS.bind(Messages.iu_contains_no_arifacts, iu)); IArtifactKey artifactKey = null; - for (int i = 0; i < artifacts.length; i++) { - if (artifacts[i].toString().equals(bundleId)) { - artifactKey = artifacts[i]; + for (IArtifactKey candidate : artifacts) { + if (candidate.toString().equals(bundleId)) { + artifactKey = candidate; break; } } @@ -62,7 +66,7 @@ public class UninstallBundleAction extends ProvisioningAction { throw new IllegalArgumentException(NLS.bind(Messages.no_matching_artifact, bundleId)); // the bundleFile might be null here, that's OK. - File bundleFile = Util.getArtifactFile(artifactKey, profile); + File bundleFile = Util.getArtifactFile(agent, artifactKey, profile); String manifest = Util.getManifest(iu.getTouchpointData()); if (manifest == null) diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/UninstallFeatureAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/UninstallFeatureAction.java index 95ea30f15..33bee8ef9 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/UninstallFeatureAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/actions/UninstallFeatureAction.java @@ -8,40 +8,41 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions; +import java.util.Collection; import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.*; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.osgi.util.NLS; public class UninstallFeatureAction extends ProvisioningAction { public static final String ID = "uninstallFeature"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { return UninstallFeatureAction.uninstallFeature(parameters); } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { return InstallFeatureAction.installFeature(parameters); } - public static IStatus uninstallFeature(Map parameters) { + public static IStatus uninstallFeature(Map parameters) { IInstallableUnit iu = (IInstallableUnit) parameters.get(EclipseTouchpoint.PARM_IU); PlatformConfigurationWrapper configuration = (PlatformConfigurationWrapper) parameters.get(EclipseTouchpoint.PARM_PLATFORM_CONFIGURATION); String feature = (String) parameters.get(ActionConstants.PARM_FEATURE); String featureId = (String) parameters.get(ActionConstants.PARM_FEATURE_ID); String featureVersion = (String) parameters.get(ActionConstants.PARM_FEATURE_VERSION); - IArtifactKey[] artifacts = iu.getArtifacts(); - if (artifacts == null || artifacts.length == 0) + Collection artifacts = iu.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) return Util.createError(NLS.bind(Messages.iu_contains_no_arifacts, iu)); IArtifactKey artifactKey = null; - for (int i = 0; i < artifacts.length; i++) { - if (artifacts[i].toString().equals(feature)) { - artifactKey = artifacts[i]; + for (IArtifactKey candidate : artifacts) { + if (candidate.toString().equals(feature)) { + artifactKey = candidate; break; } } diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/Configuration.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/Configuration.java index c3285ce7a..588a5c767 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/Configuration.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/Configuration.java @@ -21,21 +21,21 @@ import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.core.helpers.URLUtil; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Activator; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Util; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.core.ProvisionException; /** * @since 1.0 */ public class Configuration { - private List sites = new ArrayList(); + private List sites = new ArrayList(); String date; boolean transientProperty; String version; String shared_ur; public static Configuration load(File location, URL osgiInstallArea) throws ProvisionException { - return ConfigurationParser.parse(location, osgiInstallArea); + return ConfigurationIO.read(location, osgiInstallArea); } public Configuration() { @@ -43,7 +43,7 @@ public class Configuration { } public void save(File location, URL osgiInstallArea) throws ProvisionException { - ConfigurationWriter.save(this, location, osgiInstallArea); + ConfigurationIO.write(location, this, osgiInstallArea); } public String getSharedUR() { @@ -54,17 +54,17 @@ public class Configuration { shared_ur = value; } - public List getSites() { + public List getSites() { return internalGetSites(true); } - List internalGetSites(boolean includeParent) { + List internalGetSites(boolean includeParent) { if (!includeParent) return sites; String shared = getSharedUR(); if (shared == null) return sites; - List result = new ArrayList(sites); + List result = new ArrayList(sites); try { URL url = new URL(shared); File location = URLUtil.toFile(url); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationCache.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationCache.java new file mode 100644 index 000000000..53c5c65f5 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationCache.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.update; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * TODO ensure thread safety + * + */ +public class ConfigurationCache { + private static Map cache = new HashMap(); + + // class used to represent cache values + static class CacheEntry { + long timestamp; + Configuration config; + } + + // helper method to convert the file to a cache key. convert to an absolute + // path to ensure equality between relative and absolute comparisons + private static String toKey(File file) { + try { + return file.getCanonicalPath(); + } catch (IOException e) { + // ignore and return the absolute value instead + } + return file.getAbsolutePath(); + } + + /* + * Return the configuration object in the cache which is represented + * by the given file. Do a check on disk to see if the cache is up-to-date. + * If not, then treat it as a cache miss. + */ + public static Configuration get(File file) { + String key = toKey(file); + CacheEntry entry = cache.get(key); + if (entry == null) + return null; + return file.lastModified() == entry.timestamp ? entry.config : null; + } + + /* + * Store the given configuration in the cache. + */ + public static void put(File file, Configuration config) { + String key = toKey(file); + if (config == null) { + cache.remove(key); + return; + } + CacheEntry entry = new CacheEntry(); + entry.config = config; + entry.timestamp = file.lastModified(); + cache.put(key, entry); + } + +} diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationIO.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationIO.java new file mode 100644 index 000000000..44dfae151 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationIO.java @@ -0,0 +1,74 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.update; + +import java.io.File; +import java.net.URL; +import org.eclipse.equinox.p2.core.ProvisionException; + +/* + * Class which controls the reading and writing of Configuration (platform.xml) objects. + * We keep a local cached copy to avoid multiple reads. When we install new features we + * seem to only write out the platform.xml in the "commit" phase so we don't need to + * batch the writes. + */ +public class ConfigurationIO { + private static CacheEntry cache = null; + + // class used to represent cache values + static class CacheEntry { + Configuration config; + URL osgiInstallArea; + File location; + long timestamp; + } + + /* + * Return the configuration object which is represented by the given file. + */ + static Configuration read(File file, URL osgiInstallArea) throws ProvisionException { + // check the cached copy first + if (cache != null && file.lastModified() == cache.timestamp) + return cache.config; + + // cache miss or file is out of date, read from disk + Configuration config = ConfigurationParser.parse(file, osgiInstallArea); + if (config == null) + return null; + + // successful read, store in the cache before we return + cache(file, config, osgiInstallArea); + return config; + } + + /* + * Store the given configuration file in the local cache. + */ + private static void cache(File location, Configuration config, URL osgiInstallArea) { + CacheEntry entry = new CacheEntry(); + entry.config = config; + entry.osgiInstallArea = osgiInstallArea; + entry.location = location; + entry.timestamp = location.lastModified(); + cache = entry; + } + + /* + * Save the given configuration to the file-system. + */ + static void write(File location, Configuration config, URL osgiInstallArea) throws ProvisionException { + // write it to disk + ConfigurationWriter.save(config, location, osgiInstallArea); + // save a copy in the cache + cache(location, config, osgiInstallArea); + } + +} diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationParser.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationParser.java index c2e5d7de3..4e2cbd18c 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationParser.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationParser.java @@ -16,7 +16,7 @@ import java.net.URL; import java.util.ArrayList; import java.util.StringTokenizer; import javax.xml.parsers.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.core.ProvisionException; import org.eclipse.osgi.util.NLS; import org.w3c.dom.*; import org.xml.sax.SAXException; @@ -34,7 +34,7 @@ public class ConfigurationParser implements ConfigurationConstants { * Parse the given file handle which points to a platform.xml file and a configuration object. * Returns null if the file doesn't exist. */ - public static Configuration parse(File file, URL osgiInstallArea) throws ProvisionException { + static Configuration parse(File file, URL osgiInstallArea) throws ProvisionException { return new ConfigurationParser(osgiInstallArea).internalParse(file); } @@ -79,7 +79,7 @@ public class ConfigurationParser implements ConfigurationConstants { String locations = getAttribute(node, ATTRIBUTE_ROOT); if (locations != null) { StringTokenizer tokenizer = new StringTokenizer(locations, ","); //$NON-NLS-1$ - ArrayList rootList = new ArrayList(); + ArrayList rootList = new ArrayList(); while (tokenizer.hasMoreTokens()) { try { URL rootEntry = new URL(tokenizer.nextToken().trim()); @@ -88,7 +88,7 @@ public class ConfigurationParser implements ConfigurationConstants { // skip bad entries ... } } - URL[] roots = (URL[]) rootList.toArray(new URL[rootList.size()]); + URL[] roots = rootList.toArray(new URL[rootList.size()]); result.setRoots(roots); } @@ -189,12 +189,22 @@ public class ConfigurationParser implements ConfigurationConstants { * Returns null if the file doesn't exist. */ private Configuration internalParse(File file) throws ProvisionException { - if (!file.exists()) + if (!file.exists()) { + // remove from cache since it doesn't exist anymore on disk + ConfigurationCache.put(file, null); return null; + } + // have we read this before? + Configuration result = ConfigurationCache.get(file); + if (result != null) + return result; try { InputStream input = new BufferedInputStream(new FileInputStream(file)); Document document = load(input); - return process(document); + result = process(document); + // save for future use + ConfigurationCache.put(file, result); + return result; } catch (IOException e) { throw new ProvisionException(NLS.bind(Messages.error_reading_config, file), e); } catch (ParserConfigurationException e) { diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationWriter.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationWriter.java index 98d0890be..a66cedc6c 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationWriter.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/ConfigurationWriter.java @@ -13,13 +13,14 @@ package org.eclipse.equinox.internal.p2.update; import java.io.*; import java.net.MalformedURLException; import java.net.URL; -import java.util.*; +import java.util.HashMap; +import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.core.helpers.URLUtil; import org.eclipse.equinox.internal.p2.touchpoint.eclipse.Activator; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.p2.core.ProvisionException; import org.eclipse.osgi.util.NLS; /** @@ -30,12 +31,12 @@ public class ConfigurationWriter implements ConfigurationConstants { /* * Save the given configuration to the specified location. */ - public static void save(Configuration configuration, File location, URL osgiInstallArea) throws ProvisionException { + static void save(Configuration configuration, File location, URL osgiInstallArea) throws ProvisionException { XMLWriter writer = null; try { OutputStream output = new BufferedOutputStream(new FileOutputStream(location)); writer = new XMLWriter(output); - Map args = new HashMap(); + Map args = new HashMap(); String value = configuration.getDate(); if (value != null) @@ -53,8 +54,7 @@ public class ConfigurationWriter implements ConfigurationConstants { writer.startTag(ELEMENT_CONFIG, args); - for (Iterator iter = configuration.internalGetSites(false).iterator(); iter.hasNext();) { - Site site = (Site) iter.next(); + for (Site site : configuration.internalGetSites(false)) { write(writer, site, osgiInstallArea); } @@ -69,13 +69,15 @@ public class ConfigurationWriter implements ConfigurationConstants { writer.close(); } } + // put the config in the cache in case someone in the same session wants to read it + ConfigurationCache.put(location, configuration); } /* * Write out the given site. */ private static void write(XMLWriter writer, Site site, URL osgiInstallArea) { - Map args = new HashMap(); + Map args = new HashMap(); String value = site.getLinkFile(); if (value != null) @@ -144,7 +146,7 @@ public class ConfigurationWriter implements ConfigurationConstants { return; for (int i = 0; i < features.length; i++) { Feature feature = features[i]; - Map args = new HashMap(); + Map args = new HashMap(); String value = feature.getId(); if (value != null) args.put(ATTRIBUTE_ID, value); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/Site.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/Site.java index c4404f16e..ff1f55396 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/Site.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/Site.java @@ -27,8 +27,8 @@ public class Site { private boolean updateable = true; private String url; private String linkFile; - private Collection features = new HashSet(); - private List list = new ArrayList(); + private Collection features = new HashSet(); + private List list = new ArrayList(); public void addFeature(Feature feature) { this.features.add(feature); @@ -39,7 +39,7 @@ public class Site { } public Feature[] getFeatures() { - return (Feature[]) features.toArray(new Feature[features.size()]); + return features.toArray(new Feature[features.size()]); } /* @@ -50,8 +50,7 @@ public class Site { public Feature getFeature(String id, String version) { if (id == null) return null; - for (Iterator iter = features.iterator(); iter.hasNext();) { - Feature feature = (Feature) iter.next(); + for (Feature feature : features) { if (id.equals(feature.getId())) { if (version == null || version.equals(feature.getVersion())) return feature; @@ -61,8 +60,7 @@ public class Site { } public Feature removeFeature(String featureURL) { - for (Iterator iter = features.iterator(); iter.hasNext();) { - Feature feature = (Feature) iter.next(); + for (Feature feature : features) { String nextURL = feature.getUrl(); if (nextURL != null && nextURL.equals(featureURL)) return features.remove(feature) ? feature : null; @@ -75,7 +73,7 @@ public class Site { } public String[] getList() { - return (String[]) list.toArray(new String[list.size()]); + return list.toArray(new String[list.size()]); } public String getPolicy() { diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/XMLWriter.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/XMLWriter.java index 9b86646c1..192f1d708 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/XMLWriter.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/update/XMLWriter.java @@ -11,7 +11,6 @@ package org.eclipse.equinox.internal.p2.update; import java.io.*; -import java.util.Iterator; import java.util.Map; /** @@ -49,18 +48,17 @@ public class XMLWriter extends PrintWriter { super.print('\t'); } - public void printTag(String name, Map parameters) { + public void printTag(String name, Map parameters) { printTag(name, parameters, true, true); } - public void printTag(String name, Map parameters, boolean shouldTab, boolean newLine) { + public void printTag(String name, Map parameters, boolean shouldTab, boolean newLine) { StringBuffer sb = new StringBuffer(); sb.append("<"); //$NON-NLS-1$ sb.append(name); if (parameters != null) - for (Iterator it = parameters.keySet().iterator(); it.hasNext();) { + for (String key : parameters.keySet()) { sb.append(" "); //$NON-NLS-1$ - String key = (String) it.next(); sb.append(key); sb.append("=\""); //$NON-NLS-1$ sb.append(getEscaped(String.valueOf(parameters.get(key)))); @@ -75,11 +73,11 @@ public class XMLWriter extends PrintWriter { print(sb.toString()); } - public void startTag(String name, Map parameters) { + public void startTag(String name, Map parameters) { startTag(name, parameters, true); } - public void startTag(String name, Map parameters, boolean newLine) { + public void startTag(String name, Map parameters, boolean newLine) { printTag(name, parameters, true, newLine); tab++; } diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/p2/touchpoint/eclipse/query/OSGiBundleQuery.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/p2/touchpoint/eclipse/query/OSGiBundleQuery.java new file mode 100644 index 000000000..8cdb7c0d1 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/p2/touchpoint/eclipse/query/OSGiBundleQuery.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.touchpoint.eclipse.query; + +import java.util.Collection; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IProvidedCapability; +import org.eclipse.equinox.p2.query.MatchQuery; + +/** + * A query matching every {@link IInstallableUnit} that describes an OSGi bundle. + * @since 2.0 + */ +public class OSGiBundleQuery extends MatchQuery { + + public boolean isMatch(IInstallableUnit candidate) { + return isOSGiBundle(candidate); + } + + /** + * Test if the {@link IInstallableUnit} describes an OSGi bundle. + * @param iu the element being tested. + * @return true if the parameter describes an OSGi bundle. + */ + public static boolean isOSGiBundle(IInstallableUnit iu) { + Collection provided = iu.getProvidedCapabilities(); + for (IProvidedCapability capability : provided) { + if (capability.getNamespace().equals("osgi.bundle")) { //$NON-NLS-1$ + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/p2/touchpoint/eclipse/query/package.html b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/p2/touchpoint/eclipse/query/package.html new file mode 100644 index 000000000..1af2a8419 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/p2/touchpoint/eclipse/query/package.html @@ -0,0 +1,18 @@ + + + + + Package-level Javadoc + + +Provides query utilities specific to provisioning of OSGi bundles +

    +Package Specification

    +

    +This package specifies API for querying and manipulating provisioning metadata that +is specific to OSGi bundles or Eclipse-specific constructs such as features. +

    +@since 2.0 +

    + + diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/.classpath b/bundles/org.eclipse.equinox.p2.touchpoint.natives/.classpath index 7cdeb7319..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/.classpath +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/.classpath @@ -1,7 +1,7 @@ - - + + diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.touchpoint.natives/.settings/org.eclipse.jdt.core.prefs index 78523cd05..c98f1d59f 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Thu Aug 16 11:00:59 EDT 2007 +#Tue Dec 22 23:15:07 CET 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.builder.cleanOutputFolder=clean org.eclipse.jdt.core.builder.duplicateResourceTask=warning @@ -7,24 +7,24 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fieldHiding=warning org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning @@ -62,7 +62,6 @@ org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unsafeTypeOperation=warning org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=enabled org.eclipse.jdt.core.compiler.problem.unusedImport=error @@ -72,7 +71,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=en org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 @@ -144,7 +143,6 @@ org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.touchpoint.natives/META-INF/MANIFEST.MF index edb4e9e6d..ddcf469c1 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/META-INF/MANIFEST.MF @@ -8,17 +8,20 @@ Bundle-Version: 1.0.200.qualifier Bundle-Activator: org.eclipse.equinox.internal.p2.touchpoint.natives.Activator Import-Package: org.eclipse.equinox.internal.p2.core.helpers, org.eclipse.equinox.internal.p2.engine, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, org.eclipse.equinox.internal.provisional.p2.core, - org.eclipse.equinox.internal.provisional.p2.core.location, - org.eclipse.equinox.internal.provisional.p2.engine, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.repository, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.engine.spi, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, org.eclipse.osgi.util;version="1.0.0", org.osgi.framework;version="1.3.0" Bundle-ActivationPolicy: lazy Require-Bundle: org.eclipse.equinox.common -Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, - J2SE-1.4 +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 Export-Package: org.eclipse.equinox.internal.p2.touchpoint.natives;x-internal:=true, org.eclipse.equinox.internal.p2.touchpoint.natives.actions;x-internal:=true diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/build.properties b/bundles/org.eclipse.equinox.p2.touchpoint.natives/build.properties index 4bbd9bd55..0328daa18 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/build.properties +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/build.properties @@ -16,3 +16,5 @@ bin.includes = META-INF/,\ about.html,\ plugin.properties src.includes = about.html +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/BackupStore.java b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/BackupStore.java index 29fdbfdd1..82a3503cf 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/BackupStore.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/BackupStore.java @@ -406,7 +406,7 @@ public class BackupStore implements IBackupStore { throw new ClosedBackupStoreException(Messages.BackupStore_restore_closed_store); // put back all files // collect things that could not be restored (so final status can be reported) - Set unrestorable = new HashSet(); + Set unrestorable = new HashSet(); boolean restored = true; if (!backupRoot.exists()) { logError(NLS.bind(Messages.BackupStore_missing_backup_directory, backupRoot.getAbsolutePath())); @@ -421,12 +421,12 @@ public class BackupStore implements IBackupStore { closed = true; } - private void logUnrestorables(Set unrestorable) { + private void logUnrestorables(Set unrestorable) { // if there are unrestorable units log them // if (unrestorable != null && unrestorable.size() > 0) { - for (Iterator itor = unrestorable.iterator(); itor.hasNext();) - logError(NLS.bind(Messages.BackupStore_manual_restore_needed, ((File) itor.next()).getAbsolutePath())); + for (File file : unrestorable) + logError(NLS.bind(Messages.BackupStore_manual_restore_needed, file.getAbsolutePath())); } } @@ -509,7 +509,7 @@ public class BackupStore implements IBackupStore { return file.delete(); } - private void restore(File root, File buRoot, Set unrestorable) { + private void restore(File root, File buRoot, Set unrestorable) { File[] children = buRoot.listFiles(); if (children == null) { // error - can't read the backup directory unrestorable.add(buRoot); @@ -576,7 +576,7 @@ public class BackupStore implements IBackupStore { * @param buRoot * @param unrestorable */ - private void restoreRoots(File buRoot, Set unrestorable) { + private void restoreRoots(File buRoot, Set unrestorable) { File[] children = buRoot.listFiles(); if (children == null) { // error - can't read the backup directory unrestorable.add(buRoot); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/NativeTouchpoint.java b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/NativeTouchpoint.java index fe9b9cd4e..7e59d227e 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/NativeTouchpoint.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/NativeTouchpoint.java @@ -10,15 +10,20 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.touchpoint.natives; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.File; import java.io.IOException; import java.util.Map; import java.util.WeakHashMap; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IFileArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.internal.p2.touchpoint.natives.actions.ActionConstants; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.Operand; +import org.eclipse.equinox.p2.engine.spi.Touchpoint; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository; import org.eclipse.osgi.util.NLS; public class NativeTouchpoint extends Touchpoint { @@ -29,13 +34,14 @@ public class NativeTouchpoint extends Touchpoint { public static final String PARM_ARTIFACT_LOCATION = "artifact.location"; //$NON-NLS-1$ - private static Map backups = new WeakHashMap(); + private static Map backups = new WeakHashMap(); - public IStatus initializeOperand(IProfile profile, Operand operand, Map parameters) { + public IStatus initializeOperand(IProfile profile, Operand operand, Map parameters) { + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(ActionConstants.PARM_AGENT); IArtifactKey artifactKey = (IArtifactKey) parameters.get(PARM_ARTIFACT); if (!parameters.containsKey(PARM_ARTIFACT_LOCATION) && artifactKey != null) { try { - IFileArtifactRepository downloadCache = Util.getDownloadCacheRepo(); + IFileArtifactRepository downloadCache = Util.getDownloadCacheRepo(agent); File fileLocation = downloadCache.getArtifactFile(artifactKey); if (fileLocation != null && fileLocation.exists()) parameters.put(PARM_ARTIFACT_LOCATION, fileLocation.getAbsolutePath()); @@ -46,7 +52,7 @@ public class NativeTouchpoint extends Touchpoint { return Status.OK_STATUS; } - public IStatus initializePhase(IProgressMonitor monitor, IProfile profile, String phaseId, Map touchpointParameters) { + public IStatus initializePhase(IProgressMonitor monitor, IProfile profile, String phaseId, Map touchpointParameters) { touchpointParameters.put(PARM_BACKUP, getBackupStore(profile)); return null; } @@ -124,7 +130,7 @@ public class NativeTouchpoint extends Touchpoint { * @return a lazily initialized backup store */ private static synchronized IBackupStore getBackupStore(IProfile profile) { - IBackupStore store = (IBackupStore) backups.get(profile); + IBackupStore store = backups.get(profile); if (store == null) { store = new LazyBackupStore(escape(profile.getProfileId())); backups.put(profile, store); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/Util.java b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/Util.java index b9f79725f..84f45cb91 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/Util.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/Util.java @@ -10,6 +10,8 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.touchpoint.natives; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.*; import java.net.URI; import java.util.*; @@ -17,12 +19,11 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.IAgentLocation; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.*; import org.eclipse.osgi.util.NLS; public class Util { @@ -39,19 +40,19 @@ public class Util { return profile.getProperty(IProfile.PROP_INSTALL_FOLDER); } - private static AgentLocation getAgentLocation() { - return (AgentLocation) ServiceHelper.getService(Activator.getContext(), AgentLocation.class.getName()); + private static IAgentLocation getAgentLocation(IProvisioningAgent agent) { + return (IAgentLocation) agent.getService(IAgentLocation.class.getName()); } - public static IArtifactRepositoryManager getArtifactRepositoryManager() { - return (IArtifactRepositoryManager) ServiceHelper.getService(Activator.getContext(), IArtifactRepositoryManager.class.getName()); + public static IArtifactRepositoryManager getArtifactRepositoryManager(IProvisioningAgent agent) { + return (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME); } - public static IFileArtifactRepository getDownloadCacheRepo() throws ProvisionException { - URI location = getDownloadCacheLocation(); + public static IFileArtifactRepository getDownloadCacheRepo(IProvisioningAgent agent) throws ProvisionException { + URI location = getDownloadCacheLocation(agent); if (location == null) throw new IllegalStateException(Messages.could_not_obtain_download_cache); - IArtifactRepositoryManager manager = getArtifactRepositoryManager(); + IArtifactRepositoryManager manager = getArtifactRepositoryManager(agent); if (manager == null) throw new IllegalStateException(Messages.artifact_repo_not_found); IArtifactRepository repository; @@ -60,7 +61,7 @@ public class Util { } catch (ProvisionException e) { // the download cache doesn't exist or couldn't be read. Create new cache. String repositoryName = location + " - Agent download cache"; //$NON-NLS-1$ - Map properties = new HashMap(1); + Map properties = new HashMap(1); properties.put(IRepository.PROP_SYSTEM, Boolean.TRUE.toString()); repository = manager.createRepository(location, repositoryName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); } @@ -71,9 +72,11 @@ public class Util { return downloadCache; } - static private URI getDownloadCacheLocation() { - AgentLocation location = getAgentLocation(); - return (location != null ? location.getArtifactRepositoryURI() : null); + static private URI getDownloadCacheLocation(IProvisioningAgent agent) { + IAgentLocation location = getAgentLocation(agent); + if (location == null) + return null; + return URIUtil.append(location.getDataArea("org.eclipse.equinox.p2.core"), "cache/"); //$NON-NLS-1$ //$NON-NLS-2$ } /** @@ -106,7 +109,7 @@ public class Util { in.close(); throw new IOException(Messages.Util_Invalid_Zip_File_Format); } - ArrayList unzippedFiles = new ArrayList(); + ArrayList unzippedFiles = new ArrayList(); do { File outFile = new File(outputDir, ze.getName()); unzippedFiles.add(outFile); @@ -133,7 +136,7 @@ public class Util { } while ((ze = in.getNextEntry()) != null); in.close(); - return (File[]) unzippedFiles.toArray(new File[unzippedFiles.size()]); + return unzippedFiles.toArray(new File[unzippedFiles.size()]); } /** diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/ActionConstants.java b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/ActionConstants.java index 39cb3b390..de10738bf 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/ActionConstants.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/ActionConstants.java @@ -12,6 +12,7 @@ package org.eclipse.equinox.internal.p2.touchpoint.natives.actions; public class ActionConstants { + public static final String PARM_AGENT = "agent"; //$NON-NLS-1$ public static final String PARM_PATH = "path"; //$NON-NLS-1$ public static final String PARM_TARGET_FILE = "targetFile"; //$NON-NLS-1$ public static final String PARM_PERMISSIONS = "permissions"; //$NON-NLS-1$ diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/ChmodAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/ChmodAction.java index c08a76180..b9d5d5b1b 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/ChmodAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/ChmodAction.java @@ -18,13 +18,13 @@ import java.util.Map; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.touchpoint.natives.Messages; import org.eclipse.equinox.internal.p2.touchpoint.natives.Util; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; import org.eclipse.osgi.util.NLS; public class ChmodAction extends ProvisioningAction { private static final String ACTION_CHMOD = "chmod"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { String targetDir = (String) parameters.get(ActionConstants.PARM_TARGET_DIR); if (targetDir == null) return Util.createError(NLS.bind(Messages.param_not_set, ActionConstants.PARM_TARGET_DIR, ACTION_CHMOD)); @@ -43,7 +43,7 @@ public class ChmodAction extends ProvisioningAction { String options[] = null; if (optionsString != null) { - ArrayList collect = new ArrayList(); + ArrayList collect = new ArrayList(); String r = optionsString.trim(); while (r.length() > 0) { int spaceIdx = r.indexOf(' '); @@ -66,7 +66,7 @@ public class ChmodAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { //TODO: implement undo ?? return Status.OK_STATUS; } diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CleanupcopyAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CleanupcopyAction.java index 862c52963..b394f0adf 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CleanupcopyAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CleanupcopyAction.java @@ -16,20 +16,20 @@ import java.util.*; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.touchpoint.natives.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.osgi.util.NLS; public class CleanupcopyAction extends ProvisioningAction { public static final String ACTION_CLEANUPCOPY = "cleanupcopy"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { return cleanupcopy(parameters, true); } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { return CopyAction.copy(parameters, false); } @@ -39,7 +39,7 @@ public class CleanupcopyAction extends ProvisioningAction { * @param restoreable flag indicating if the operation should be backed up * @return status */ - public static IStatus cleanupcopy(Map parameters, boolean restoreable) { + public static IStatus cleanupcopy(Map parameters, boolean restoreable) { String source = (String) parameters.get(ActionConstants.PARM_SOURCE); if (source == null) return Util.createError(NLS.bind(Messages.param_not_set, ActionConstants.PARM_SOURCE, ACTION_CLEANUPCOPY)); @@ -57,7 +57,7 @@ public class CleanupcopyAction extends ProvisioningAction { return Status.OK_STATUS; StringTokenizer tokenizer = new StringTokenizer(copied, ActionConstants.PIPE); - List directories = new ArrayList(); + List directories = new ArrayList(); while (tokenizer.hasMoreTokens()) { String fileName = tokenizer.nextToken(); File file = new File(fileName); @@ -80,8 +80,7 @@ public class CleanupcopyAction extends ProvisioningAction { } } - for (Iterator it = directories.iterator(); it.hasNext();) { - File directory = (File) it.next(); + for (File directory : directories) { File[] children = directory.listFiles(); if (children == null) return Util.createError(NLS.bind(Messages.Error_list_children_0, directory)); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CleanupzipAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CleanupzipAction.java index c5938e749..e442d4465 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CleanupzipAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CleanupzipAction.java @@ -17,8 +17,8 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.engine.Profile; import org.eclipse.equinox.internal.p2.touchpoint.natives.*; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.osgi.util.NLS; public class CleanupzipAction extends ProvisioningAction { @@ -26,15 +26,15 @@ public class CleanupzipAction extends ProvisioningAction { private static final String UNZIPPED = "unzipped"; //$NON-NLS-1$ public static final String ACTION_CLEANUPZIP = "cleanupzip"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { return cleanupzip(parameters, true); } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { return UnzipAction.unzip(parameters, false); } - public static IStatus cleanupzip(Map parameters, boolean restoreable) { + public static IStatus cleanupzip(Map parameters, boolean restoreable) { String source = (String) parameters.get(ActionConstants.PARM_SOURCE); if (source == null) return Util.createError(NLS.bind(Messages.param_not_set, ActionConstants.PARM_SOURCE, ACTION_CLEANUPZIP)); @@ -51,15 +51,14 @@ public class CleanupzipAction extends ProvisioningAction { if (unzipped == null) { // best effort // we try to substitute the current target with what was written. - Map iuProperties = profile.getInstallableUnitProperties(iu); + Map iuProperties = profile.getInstallableUnitProperties(iu); String sourcePrefix = UNZIPPED + ActionConstants.PIPE + source + ActionConstants.PIPE; - for (Iterator iterator = iuProperties.keySet().iterator(); iterator.hasNext();) { - String key = (String) iterator.next(); + for (String key : iuProperties.keySet()) { if (key.startsWith(sourcePrefix)) { if (unzipped == null) { iuPropertyKey = key; String storedTarget = key.substring(sourcePrefix.length()); - unzipped = substituteTarget(storedTarget, target, (String) iuProperties.get(key)); + unzipped = substituteTarget(storedTarget, target, iuProperties.get(key)); } else return Status.OK_STATUS; // possible two unzips of this source - give up on best effort } @@ -71,7 +70,7 @@ public class CleanupzipAction extends ProvisioningAction { IBackupStore store = restoreable ? (IBackupStore) parameters.get(NativeTouchpoint.PARM_BACKUP) : null; StringTokenizer tokenizer = new StringTokenizer(unzipped, ActionConstants.PIPE); - List directories = new ArrayList(); + List directories = new ArrayList(); while (tokenizer.hasMoreTokens()) { String fileName = tokenizer.nextToken(); File file = new File(fileName); @@ -96,8 +95,7 @@ public class CleanupzipAction extends ProvisioningAction { // the leafs first in the list of directories. // Since backup will deny backup of non empty directory a check must be made // - for (Iterator it = directories.iterator(); it.hasNext();) { - File directory = (File) it.next(); + for (File directory : directories) { if (store != null) { File[] children = directory.listFiles(); if (children == null || children.length == 0) diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CollectAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CollectAction.java index 6fbf20b84..9626bb4c4 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CollectAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CollectAction.java @@ -10,28 +10,34 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.touchpoint.natives.actions; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.util.Collection; import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.touchpoint.natives.Util; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRequest; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.InstallableUnitOperand; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRequest; public class CollectAction extends ProvisioningAction { public static final String ACTION_COLLECT = "collect"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { IProfile profile = (IProfile) parameters.get(ActionConstants.PARM_PROFILE); + IProvisioningAgent agent = (IProvisioningAgent) parameters.get(ActionConstants.PARM_AGENT); InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(ActionConstants.PARM_OPERAND); try { - IArtifactRequest[] requests = collect(operand.second(), profile); - Collection artifactRequests = (Collection) parameters.get(ActionConstants.PARM_ARTIFACT_REQUESTS); + IArtifactRequest[] requests = collect(agent, operand.second(), profile); + @SuppressWarnings("unchecked") + Collection artifactRequests = (Collection) parameters.get(ActionConstants.PARM_ARTIFACT_REQUESTS); artifactRequests.add(requests); } catch (ProvisionException e) { return e.getStatus(); @@ -39,21 +45,21 @@ public class CollectAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { // nothing to do for now return Status.OK_STATUS; } - IArtifactRequest[] collect(IInstallableUnit installableUnit, IProfile profile) throws ProvisionException { - IArtifactKey[] toDownload = installableUnit.getArtifacts(); + IArtifactRequest[] collect(IProvisioningAgent agent, IInstallableUnit installableUnit, IProfile profile) throws ProvisionException { + Collection toDownload = installableUnit.getArtifacts(); if (toDownload == null) return new IArtifactRequest[0]; - IArtifactRepository destination = Util.getDownloadCacheRepo(); - IArtifactRequest[] requests = new IArtifactRequest[toDownload.length]; + IArtifactRepository destination = Util.getDownloadCacheRepo(agent); + IArtifactRequest[] requests = new IArtifactRequest[toDownload.size()]; int count = 0; - for (int i = 0; i < toDownload.length; i++) { + for (IArtifactKey key : toDownload) { //TODO Here there are cases where the download is not necessary again because what needs to be done is just a configuration step - requests[count++] = Util.getArtifactRepositoryManager().createMirrorRequest(toDownload[i], destination, null, null); + requests[count++] = Util.getArtifactRepositoryManager(agent).createMirrorRequest(key, destination, null, null); } if (requests.length == count) diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CopyAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CopyAction.java index 6e9b0395d..d9dab3c98 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CopyAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/CopyAction.java @@ -10,6 +10,8 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.touchpoint.natives.actions; +import java.io.File; + import java.io.*; import java.util.ArrayList; import java.util.Map; @@ -17,9 +19,9 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.engine.Profile; import org.eclipse.equinox.internal.p2.touchpoint.natives.*; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.osgi.util.NLS; /** @@ -33,7 +35,7 @@ import org.eclipse.osgi.util.NLS; public class CopyAction extends ProvisioningAction { public static final String ID = "cp"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { return copy(parameters, true); } @@ -43,7 +45,7 @@ public class CopyAction extends ProvisioningAction { * @param restoreable flag indicating if the operation should be backed up * @return status */ - public static IStatus copy(Map parameters, boolean restoreable) { + public static IStatus copy(Map parameters, boolean restoreable) { String target = (String) parameters.get(ActionConstants.PARM_COPY_TARGET); IBackupStore backupStore = restoreable ? (IBackupStore) parameters.get(NativeTouchpoint.PARM_BACKUP) : null; @@ -86,7 +88,7 @@ public class CopyAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { return CleanupcopyAction.cleanupcopy(parameters, false); } @@ -98,9 +100,9 @@ public class CopyAction extends ProvisioningAction { * @throws IOException */ private static File[] mergeCopy(File source, File target, boolean overwrite, IBackupStore backupStore) throws IOException { - ArrayList copiedFiles = new ArrayList(); + ArrayList copiedFiles = new ArrayList(); xcopy(copiedFiles, source, target, overwrite, backupStore); - return (File[]) copiedFiles.toArray(new File[copiedFiles.size()]); + return copiedFiles.toArray(new File[copiedFiles.size()]); } /** @@ -111,7 +113,7 @@ public class CopyAction extends ProvisioningAction { * @param overwrite * @throws IOException */ - private static void xcopy(ArrayList copiedFiles, File source, File target, boolean overwrite, IBackupStore backupStore) throws IOException { + private static void xcopy(ArrayList copiedFiles, File source, File target, boolean overwrite, IBackupStore backupStore) throws IOException { if (!source.exists()) throw new IOException("Source: " + source + "does not exists"); //$NON-NLS-1$//$NON-NLS-2$ diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/LinkAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/LinkAction.java index b34903c42..d5cfd2761 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/LinkAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/LinkAction.java @@ -14,13 +14,13 @@ import java.io.*; import java.util.Map; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.touchpoint.natives.*; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; import org.eclipse.osgi.util.NLS; public class LinkAction extends ProvisioningAction { public static final String ID = "ln"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { String targetDir = (String) parameters.get(ActionConstants.PARM_TARGET_DIR); if (targetDir == null) return new Status(IStatus.ERROR, Activator.ID, IStatus.OK, NLS.bind(Messages.param_not_set, ActionConstants.PARM_TARGET_DIR, ID), null); @@ -45,7 +45,7 @@ public class LinkAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { String targetDir = (String) parameters.get(ActionConstants.PARM_TARGET_DIR); String linkName = (String) parameters.get(ActionConstants.PARM_LINK_NAME); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/MkdirAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/MkdirAction.java index ce60b52ca..bea5668c0 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/MkdirAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/MkdirAction.java @@ -16,13 +16,13 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.touchpoint.natives.Messages; import org.eclipse.equinox.internal.p2.touchpoint.natives.Util; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; import org.eclipse.osgi.util.NLS; public class MkdirAction extends ProvisioningAction { public static final String ID = "mkdir"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { String path = (String) parameters.get(ActionConstants.PARM_PATH); if (path == null) return Util.createError(NLS.bind(Messages.param_not_set, ActionConstants.PARM_PATH, ID)); @@ -35,7 +35,7 @@ public class MkdirAction extends ProvisioningAction { return Util.createError(NLS.bind(Messages.mkdir_failed, path, ID)); } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { String path = (String) parameters.get(ActionConstants.PARM_PATH); if (path == null) return Util.createError(NLS.bind(Messages.param_not_set, ActionConstants.PARM_PATH, ID)); diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/RemoveAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/RemoveAction.java index ab442c416..c820a9bbd 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/RemoveAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/RemoveAction.java @@ -10,21 +10,19 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.touchpoint.natives.actions; -import org.eclipse.equinox.internal.p2.touchpoint.natives.IBackupStore; - import java.io.File; import java.io.IOException; import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.touchpoint.natives.*; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; import org.eclipse.osgi.util.NLS; public class RemoveAction extends ProvisioningAction { public static final String ID = "remove"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { String path = (String) parameters.get(ActionConstants.PARM_PATH); if (path == null) return Util.createError(NLS.bind(Messages.param_not_set, ActionConstants.PARM_PATH, ID)); @@ -43,7 +41,7 @@ public class RemoveAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { // Does not have to do anything as the backup will restore what was deleted return Status.OK_STATUS; } diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/RmdirAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/RmdirAction.java index 26ea0464d..8473a2ae8 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/RmdirAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/RmdirAction.java @@ -16,13 +16,13 @@ import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.touchpoint.natives.*; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; import org.eclipse.osgi.util.NLS; public class RmdirAction extends ProvisioningAction { public static final String ID = "rmdir"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { String path = (String) parameters.get(ActionConstants.PARM_PATH); if (path == null) return Util.createError(NLS.bind(Messages.param_not_set, ActionConstants.PARM_PATH, ID)); @@ -49,7 +49,7 @@ public class RmdirAction extends ProvisioningAction { return Status.OK_STATUS; } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { String path = (String) parameters.get(ActionConstants.PARM_PATH); IBackupStore store = (IBackupStore) parameters.get(NativeTouchpoint.PARM_BACKUP); if (path == null) diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/UnzipAction.java b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/UnzipAction.java index 9c1c18f62..108161650 100644 --- a/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/UnzipAction.java +++ b/bundles/org.eclipse.equinox.p2.touchpoint.natives/src/org/eclipse/equinox/internal/p2/touchpoint/natives/actions/UnzipAction.java @@ -16,20 +16,20 @@ import java.util.Map; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.engine.Profile; import org.eclipse.equinox.internal.p2.touchpoint.natives.*; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningAction; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.engine.spi.ProvisioningAction; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.osgi.util.NLS; public class UnzipAction extends ProvisioningAction { public static final String ACTION_UNZIP = "unzip"; //$NON-NLS-1$ - public IStatus execute(Map parameters) { + public IStatus execute(Map parameters) { return unzip(parameters, true); } - public IStatus undo(Map parameters) { + public IStatus undo(Map parameters) { return CleanupzipAction.cleanupzip(parameters, false); } @@ -40,7 +40,7 @@ public class UnzipAction extends ProvisioningAction { * @param restoreable - if the unzip should be backed up * @return status */ - public static IStatus unzip(Map parameters, boolean restoreable) { + public static IStatus unzip(Map parameters, boolean restoreable) { String source = (String) parameters.get(ActionConstants.PARM_SOURCE); if (source == null) return Util.createError(NLS.bind(Messages.param_not_set, ActionConstants.PARM_SOURCE, ACTION_UNZIP)); diff --git a/bundles/org.eclipse.equinox.p2.ui.admin.rcp/ProvAdminUI.launch b/bundles/org.eclipse.equinox.p2.ui.admin.rcp/ProvAdminUI.launch index 28ac8d428..1e02d5792 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin.rcp/ProvAdminUI.launch +++ b/bundles/org.eclipse.equinox.p2.ui.admin.rcp/ProvAdminUI.launch @@ -19,7 +19,7 @@ - + @@ -36,29 +36,29 @@ - + - + - + - + - - + + @@ -70,11 +70,11 @@ - - - + + + @@ -83,10 +83,10 @@ - - + + @@ -100,23 +100,23 @@ - + - + - + - - + + @@ -126,8 +126,8 @@ - + @@ -140,30 +140,30 @@ - + - + - + - - + + @@ -172,8 +172,8 @@ - + @@ -181,8 +181,8 @@ - + @@ -196,30 +196,30 @@ - + - + - + - + - + @@ -235,12 +235,12 @@ - + - + @@ -257,21 +257,21 @@ - + - + - - + + @@ -296,12 +296,12 @@ - + - + diff --git a/bundles/org.eclipse.equinox.p2.ui.admin.rcp/src/org/eclipse/equinox/internal/p2/ui/admin/rcp/ApplicationWorkbenchAdvisor.java b/bundles/org.eclipse.equinox.p2.ui.admin.rcp/src/org/eclipse/equinox/internal/p2/ui/admin/rcp/ApplicationWorkbenchAdvisor.java index 5955baa8a..dc31db156 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin.rcp/src/org/eclipse/equinox/internal/p2/ui/admin/rcp/ApplicationWorkbenchAdvisor.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin.rcp/src/org/eclipse/equinox/internal/p2/ui/admin/rcp/ApplicationWorkbenchAdvisor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,4 +21,8 @@ public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { public String getInitialWindowPerspectiveId() { return "org.eclipse.equinox.p2.ui.admin.rcp.ProvisioningRCPPerspective"; //$NON-NLS-1$ } + + public void initialize(IWorkbenchConfigurer configurer) { + configurer.setSaveAndRestore(true); + } } diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/.classpath b/bundles/org.eclipse.equinox.p2.ui.admin/.classpath index ce7393340..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/.classpath +++ b/bundles/org.eclipse.equinox.p2.ui.admin/.classpath @@ -1,7 +1,7 @@ - - + + diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.ui.admin/.settings/org.eclipse.jdt.core.prefs index 78523cd05..eba723b85 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.ui.admin/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Thu Aug 16 11:00:59 EDT 2007 +#Tue Dec 22 23:48:18 CET 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.builder.cleanOutputFolder=clean org.eclipse.jdt.core.builder.duplicateResourceTask=warning @@ -7,24 +7,24 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fieldHiding=warning org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning @@ -62,7 +62,6 @@ org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unsafeTypeOperation=warning org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=enabled org.eclipse.jdt.core.compiler.problem.unusedImport=error @@ -72,7 +71,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=en org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 @@ -144,7 +143,6 @@ org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.ui.admin/META-INF/MANIFEST.MF index 3f8bf2210..618b5065e 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.ui.admin/META-INF/MANIFEST.MF @@ -6,32 +6,36 @@ Bundle-Localization: plugin Bundle-SymbolicName: org.eclipse.equinox.p2.ui.admin;singleton:=true Bundle-Version: 1.0.0.qualifier Bundle-Activator: org.eclipse.equinox.internal.p2.ui.admin.ProvAdminUIActivator -Bundle-RequiredExecutionEnvironment: J2SE-1.4, +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, CDC-1.1/Foundation-1.1 Import-Package: org.eclipse.equinox.internal.p2.core.helpers, + org.eclipse.equinox.internal.p2.ui, + org.eclipse.equinox.internal.p2.ui.actions, + org.eclipse.equinox.internal.p2.ui.dialogs, org.eclipse.equinox.internal.p2.ui.model, org.eclipse.equinox.internal.p2.ui.query, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, + org.eclipse.equinox.internal.p2.ui.viewers, org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.core.eventbus, - org.eclipse.equinox.internal.provisional.p2.repository, org.eclipse.equinox.internal.provisional.p2.director, - org.eclipse.equinox.internal.provisional.p2.engine, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.p2.ui, - org.eclipse.equinox.internal.provisional.p2.ui.actions, - org.eclipse.equinox.internal.provisional.p2.ui.dialogs, - org.eclipse.equinox.internal.provisional.p2.ui.model, - org.eclipse.equinox.internal.provisional.p2.ui.operations, - org.eclipse.equinox.internal.provisional.p2.ui.policy, - org.eclipse.equinox.internal.provisional.p2.ui.viewers, + org.eclipse.equinox.internal.provisional.p2.repository, org.eclipse.equinox.internal.provisional.p2.updatechecker, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.engine.query, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.operations, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.metadata, + org.eclipse.equinox.p2.ui, org.eclipse.osgi.service.environment;version="1.0.0", org.eclipse.osgi.util;version="1.1.0", org.osgi.framework;version="1.3.0" -Export-Package: org.eclipse.equinox.internal.p2.ui.admin;x-internal:=true, +Export-Package: org.eclipse.equinox.internal.p2.ui.admin;x-friends:="org.eclipse.equinox.internal.p2.ui.analysis", org.eclipse.equinox.internal.p2.ui.admin.dialogs;x-internal:=true, org.eclipse.equinox.internal.p2.ui.admin.preferences;x-internal:=true Require-Bundle: org.eclipse.core.runtime, diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/build.properties b/bundles/org.eclipse.equinox.p2.ui.admin/build.properties index 35011865d..b7d66df9b 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/build.properties +++ b/bundles/org.eclipse.equinox.p2.ui.admin/build.properties @@ -16,6 +16,5 @@ bin.includes = plugin.properties,\ META-INF/ src.includes = about.html source.. = src/ - - - +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/plugin.xml b/bundles/org.eclipse.equinox.p2.ui.admin/plugin.xml index d866395a7..6aa850827 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/plugin.xml +++ b/bundles/org.eclipse.equinox.p2.ui.admin/plugin.xml @@ -66,7 +66,7 @@ class="org.eclipse.equinox.internal.p2.ui.admin.dialogs.ProfilePropertyPage" id="org.eclipse.equinox.internal.p2.ui.admin.dialogs.ProfilePropertyPage"> - + - + + value="org.eclipse.equinox.internal.p2.ui.model.InstalledIUElement"> @@ -92,7 +92,7 @@ class="org.eclipse.equinox.internal.p2.ui.admin.dialogs.RepositoryImplementationPropertyPage" id="org.eclipse.equinox.internal.p2.ui.admin.dialogs.RepositoryImplementationPropertyPage"> - + diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/AddArtifactRepositoryOperation.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/AddArtifactRepositoryOperation.java deleted file mode 100644 index 7882bf660..000000000 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/AddArtifactRepositoryOperation.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.ui.admin; - -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; - -import java.net.URI; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.AddRepositoryOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; - -/** - * Operation which adds an artifact repository given its URI. - * - * @since 3.4 - */ -public class AddArtifactRepositoryOperation extends AddRepositoryOperation { - - public AddArtifactRepositoryOperation(String label, URI location) { - super(label, new URI[] {location}); - } - - protected IStatus doBatchedExecute(IProgressMonitor monitor) throws ProvisionException { - SubMonitor mon = SubMonitor.convert(monitor, locations.length); - for (int i = 0; i < locations.length; i++) { - ProvisioningUtil.addArtifactRepository(locations[i], notify); - mon.worked(1); - } - return okStatus(); - } - - protected void setNickname(URI location, String nickname) throws ProvisionException { - for (int i = 0; i < locations.length; i++) { - ProvisioningUtil.setArtifactRepositoryProperty(location, IRepository.PROP_NICKNAME, nickname); - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/AddMetadataRepositoryOperation.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/AddMetadataRepositoryOperation.java deleted file mode 100644 index 4d1baa1b2..000000000 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/AddMetadataRepositoryOperation.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.ui.admin; - -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; - -import java.net.URI; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.AddRepositoryOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; - -/** - * Operation that adds a metadata repository given its URL. - * - * @since 3.4 - */ -public class AddMetadataRepositoryOperation extends AddRepositoryOperation { - - public AddMetadataRepositoryOperation(String label, URI location) { - super(label, new URI[] {location}); - } - - protected IStatus doBatchedExecute(IProgressMonitor monitor) throws ProvisionException { - SubMonitor mon = SubMonitor.convert(monitor, locations.length); - for (int i = 0; i < locations.length; i++) { - ProvisioningUtil.addMetadataRepository(locations[i], notify); - mon.worked(1); - } - return okStatus(); - } - - protected void setNickname(URI location, String nickname) throws ProvisionException { - for (int i = 0; i < locations.length; i++) { - ProvisioningUtil.setMetadataRepositoryProperty(location, IRepository.PROP_NICKNAME, nickname); - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/AddProfileJob.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/AddProfileJob.java new file mode 100644 index 000000000..4a3efe470 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/AddProfileJob.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.admin; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.util.Map; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.p2.operations.ProvisioningJob; +import org.eclipse.equinox.p2.operations.ProvisioningSession; + +/** + * Operation that adds the given profile to the profile registry. + * + * @since 3.6 + */ +public class AddProfileJob extends ProvisioningJob { + private String profileId; + private Map profileProperties; + + public AddProfileJob(String label, ProvisioningSession session, String profileId, Map profileProperties) { + super(label, session); + this.profileId = profileId; + this.profileProperties = profileProperties; + } + + public IStatus runModal(IProgressMonitor monitor) { + IStatus status = Status.OK_STATUS; + try { + getSession().getProfileRegistry().addProfile(profileId, profileProperties); + } catch (ProvisionException e) { + status = getErrorStatus(null, e); + } + return status; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ArtifactRepositoriesView.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ArtifactRepositoriesView.java index 376bad13a..a2bdc4e7b 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ArtifactRepositoriesView.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ArtifactRepositoriesView.java @@ -10,16 +10,12 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.admin; -import java.net.URI; -import java.util.ArrayList; +import org.eclipse.equinox.internal.p2.ui.ProvUIProvisioningListener; +import org.eclipse.equinox.internal.p2.ui.QueryableArtifactRepositoryManager; import org.eclipse.equinox.internal.p2.ui.admin.dialogs.AddArtifactRepositoryDialog; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner; -import org.eclipse.equinox.internal.provisional.p2.ui.model.ArtifactRepositories; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IRepositoryElement; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.RemoveRepositoryOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.StructuredViewerProvisioningListener; +import org.eclipse.equinox.internal.p2.ui.model.ArtifactRepositories; +import org.eclipse.equinox.p2.operations.RepositoryTracker; import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.statushandlers.StatusManager; /** * This view allows users to interact with artifact repositories @@ -28,6 +24,8 @@ import org.eclipse.ui.statushandlers.StatusManager; */ public class ArtifactRepositoriesView extends RepositoriesView { + private RepositoryTracker tracker; + /** * */ @@ -36,7 +34,7 @@ public class ArtifactRepositoriesView extends RepositoriesView { } protected Object getInput() { - return new ArtifactRepositories(ProvAdminUIActivator.getDefault().getPolicy()); + return new ArtifactRepositories(getProvisioningUI(), new QueryableArtifactRepositoryManager(getProvisioningUI(), false)); } protected String getAddCommandLabel() { @@ -52,16 +50,7 @@ public class ArtifactRepositoriesView extends RepositoriesView { } protected int openAddRepositoryDialog(Shell shell) { - return new AddArtifactRepositoryDialog(shell, ProvAdminUIActivator.getDefault().getPolicy()).open(); - } - - protected RemoveRepositoryOperation getRemoveOperation(Object[] elements) { - ArrayList locations = new ArrayList(); - for (int i = 0; i < elements.length; i++) { - if (elements[i] instanceof IRepositoryElement) - locations.add(((IRepositoryElement) elements[i]).getLocation()); - } - return new RemoveArtifactRepositoryOperation(ProvAdminUIMessages.ArtifactRepositoriesView_RemoveRepositoryOperationLabel, (URI[]) locations.toArray(new URI[locations.size()])); + return new AddArtifactRepositoryDialog(shell, getProvisioningUI()).open(); } /* @@ -69,15 +58,16 @@ public class ArtifactRepositoriesView extends RepositoriesView { * @see org.eclipse.equinox.internal.p2.ui.admin.RepositoriesView#getListenerEventTypes() */ protected int getListenerEventTypes() { - return StructuredViewerProvisioningListener.PROV_EVENT_ARTIFACT_REPOSITORY; + return ProvUIProvisioningListener.PROV_EVENT_ARTIFACT_REPOSITORY; } - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.ui.admin.ProvView#refreshUnderlyingModel() + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.admin.RepositoriesView#getRepositoryTracker() */ - protected void refreshUnderlyingModel() { - ProvisioningOperationRunner.schedule(new RefreshArtifactRepositoriesOperation(ProvAdminUIMessages.ProvView_RefreshCommandLabel, ProvAdminUIActivator.getDefault().getPolicy().getQueryContext().getArtifactRepositoryFlags()), StatusManager.SHOW | StatusManager.LOG); + protected RepositoryTracker getRepositoryTracker() { + if (tracker == null) + tracker = new ArtifactRepositoryTracker(getProvisioningUI()); + return tracker; } } diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ArtifactRepositoryTracker.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ArtifactRepositoryTracker.java new file mode 100644 index 000000000..b4fbdba2d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ArtifactRepositoryTracker.java @@ -0,0 +1,83 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.admin; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.net.URI; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.ui.ProvisioningUI; + +public class ArtifactRepositoryTracker extends RepositoryTracker { + + ProvisioningUI ui; + + public ArtifactRepositoryTracker(ProvisioningUI ui) { + this.ui = ui; + } + + public URI[] getKnownRepositories(ProvisioningSession session) { + return session.getArtifactRepositoryManager().getKnownRepositories(getArtifactRepositoryFlags()); + } + + protected IStatus validateRepositoryLocationWithManager(ProvisioningSession session, URI location, IProgressMonitor monitor) { + return Status.OK_STATUS; + } + + public void addRepository(URI repoLocation, String nickname, ProvisioningSession session) { + ui.signalRepositoryOperationStart(); + try { + session.getArtifactRepositoryManager().addRepository(repoLocation); + if (nickname != null) + session.getArtifactRepositoryManager().setRepositoryProperty(repoLocation, IRepository.PROP_NICKNAME, nickname); + } finally { + ui.signalRepositoryOperationComplete(new RepositoryEvent(repoLocation, IRepository.TYPE_ARTIFACT, RepositoryEvent.ADDED, true), true); + } + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.RepositoryTracker#removeRepositories(java.net.URI[], org.eclipse.equinox.p2.operations.ProvisioningSession) + */ + public void removeRepositories(URI[] repoLocations, ProvisioningSession session) { + ui.signalRepositoryOperationStart(); + try { + for (int i = 0; i < repoLocations.length; i++) { + session.getArtifactRepositoryManager().removeRepository(repoLocations[i]); + } + } finally { + ui.signalRepositoryOperationComplete(null, true); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.RepositoryTracker#refreshRepositories(java.net.URI[], org.eclipse.equinox.p2.operations.ProvisioningSession, org.eclipse.core.runtime.IProgressMonitor) + */ + public void refreshRepositories(URI[] locations, ProvisioningSession session, IProgressMonitor monitor) { + ui.signalRepositoryOperationStart(); + SubMonitor mon = SubMonitor.convert(monitor, locations.length * 100); + for (int i = 0; i < locations.length; i++) { + try { + session.getArtifactRepositoryManager().refreshRepository(locations[i], mon.newChild(100)); + } catch (ProvisionException e) { + //ignore problematic repositories when refreshing + } + } + // We have no idea how many repos may have been added/removed as a result of + // refreshing these, this one, so we do not use a specific repository event to represent it. + ui.signalRepositoryOperationComplete(null, true); + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/MetadataRepositoriesView.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/MetadataRepositoriesView.java index 172726c5e..df1c314c1 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/MetadataRepositoriesView.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/MetadataRepositoriesView.java @@ -11,27 +11,24 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.admin; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; - -import java.net.URI; -import java.util.ArrayList; import java.util.List; +import org.eclipse.equinox.internal.p2.ui.ProvUIProvisioningListener; +import org.eclipse.equinox.internal.p2.ui.QueryableMetadataRepositoryManager; +import org.eclipse.equinox.internal.p2.ui.actions.InstallAction; import org.eclipse.equinox.internal.p2.ui.admin.dialogs.AddMetadataRepositoryDialog; import org.eclipse.equinox.internal.p2.ui.admin.preferences.PreferenceConstants; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.InstallAction; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IRepositoryElement; -import org.eclipse.equinox.internal.provisional.p2.ui.model.MetadataRepositories; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.RemoveRepositoryOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.IUDragAdapter; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.StructuredViewerProvisioningListener; +import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositories; +import org.eclipse.equinox.internal.p2.ui.query.IUViewQueryContext; +import org.eclipse.equinox.internal.p2.ui.viewers.IUDragAdapter; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.ui.Policy; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.dnd.*; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.part.PluginTransfer; -import org.eclipse.ui.statushandlers.StatusManager; /** * This view allows users to interact with metadata repositories @@ -41,6 +38,8 @@ import org.eclipse.ui.statushandlers.StatusManager; public class MetadataRepositoriesView extends RepositoriesView { private InstallAction installAction; + private RepositoryTracker tracker; + MetadataRepositories input; /** * The constructor. @@ -50,7 +49,18 @@ public class MetadataRepositoriesView extends RepositoriesView { } protected Object getInput() { - return new MetadataRepositories(ProvAdminUIActivator.getDefault().getPolicy()); + if (input == null) { + // view by repo + IUViewQueryContext context = new IUViewQueryContext(IUViewQueryContext.AVAILABLE_VIEW_BY_REPO); + Policy policy = ProvAdminUIActivator.getDefault().getPolicy(); + context.setShowLatestVersionsOnly(policy.getShowLatestVersionsOnly()); + context.setShowInstallChildren(policy.getShowDrilldownRequirements()); + context.setShowProvisioningPlanChildren(policy.getShowDrilldownRequirements()); + context.setUseCategories(policy.getGroupByCategory()); + + input = new MetadataRepositories(context, getProvisioningUI(), new QueryableMetadataRepositoryManager(getProvisioningUI(), false)); + } + return input; } protected String getAddCommandLabel() { @@ -66,21 +76,12 @@ public class MetadataRepositoriesView extends RepositoriesView { } protected int openAddRepositoryDialog(Shell shell) { - return new AddMetadataRepositoryDialog(shell, ProvAdminUIActivator.getDefault().getPolicy()).open(); - } - - protected RemoveRepositoryOperation getRemoveOperation(Object[] elements) { - ArrayList locations = new ArrayList(); - for (int i = 0; i < elements.length; i++) { - if (elements[i] instanceof IRepositoryElement) - locations.add(((IRepositoryElement) elements[i]).getLocation()); - } - return new RemoveMetadataRepositoryOperation(ProvAdminUIMessages.ArtifactRepositoriesView_RemoveRepositoryOperationLabel, (URI[]) locations.toArray(new URI[locations.size()])); + return new AddMetadataRepositoryDialog(shell, getProvisioningUI()).open(); } protected void makeActions() { super.makeActions(); - installAction = new InstallAction(ProvAdminUIActivator.getDefault().getPolicy(), viewer, null); + installAction = new InstallAction(getProvisioningUI(), viewer, null); } protected void fillContextMenu(IMenuManager manager) { @@ -109,21 +110,22 @@ public class MetadataRepositoriesView extends RepositoriesView { * @see org.eclipse.equinox.internal.p2.ui.admin.RepositoriesView#getListenerEventTypes() */ protected int getListenerEventTypes() { - return StructuredViewerProvisioningListener.PROV_EVENT_METADATA_REPOSITORY; + return ProvUIProvisioningListener.PROV_EVENT_METADATA_REPOSITORY; } - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.ui.admin.ProvView#refreshUnderlyingModel() - */ - protected void refreshUnderlyingModel() { - ProvisioningOperationRunner.schedule(new RefreshMetadataRepositoriesOperation(ProvAdminUIMessages.ProvView_RefreshCommandLabel, getRepoFlags()), StatusManager.SHOW | StatusManager.LOG); - } - - protected List getVisualProperties() { - List list = super.getVisualProperties(); + protected List getVisualProperties() { + List list = super.getVisualProperties(); list.add(PreferenceConstants.PREF_USE_CATEGORIES); list.add(PreferenceConstants.PREF_COLLAPSE_IU_VERSIONS); return list; } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.admin.RepositoriesView#getRepositoryTracker() + */ + protected RepositoryTracker getRepositoryTracker() { + if (tracker == null) + tracker = new MetadataRepositoryTracker(getProvisioningUI()); + return tracker; + } } diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/MetadataRepositoryTracker.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/MetadataRepositoryTracker.java new file mode 100644 index 000000000..52c260adb --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/MetadataRepositoryTracker.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.admin; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.net.URI; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.ui.ProvisioningUI; + +public class MetadataRepositoryTracker extends RepositoryTracker { + + ProvisioningUI ui; + + public MetadataRepositoryTracker(ProvisioningUI ui) { + this.ui = ui; + } + + public URI[] getKnownRepositories(ProvisioningSession session) { + return session.getMetadataRepositoryManager().getKnownRepositories(getArtifactRepositoryFlags()); + } + + protected IStatus validateRepositoryLocationWithManager(ProvisioningSession session, URI location, IProgressMonitor monitor) { + return Status.OK_STATUS; + } + + public void addRepository(URI repoLocation, String nickname, ProvisioningSession session) { + ui.signalRepositoryOperationStart(); + try { + session.getMetadataRepositoryManager().addRepository(repoLocation); + if (nickname != null) + session.getMetadataRepositoryManager().setRepositoryProperty(repoLocation, IRepository.PROP_NICKNAME, nickname); + + } finally { + ui.signalRepositoryOperationComplete(new RepositoryEvent(repoLocation, IRepository.TYPE_METADATA, RepositoryEvent.ADDED, true), true); + } + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.RepositoryTracker#removeRepositories(java.net.URI[], org.eclipse.equinox.p2.operations.ProvisioningSession) + */ + public void removeRepositories(URI[] repoLocations, ProvisioningSession session) { + ui.signalRepositoryOperationStart(); + try { + for (int i = 0; i < repoLocations.length; i++) { + session.getMetadataRepositoryManager().removeRepository(repoLocations[i]); + } + } finally { + ui.signalRepositoryOperationComplete(null, true); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.RepositoryTracker#refreshRepositories(java.net.URI[], org.eclipse.equinox.p2.operations.ProvisioningSession, org.eclipse.core.runtime.IProgressMonitor) + */ + public void refreshRepositories(URI[] locations, ProvisioningSession session, IProgressMonitor monitor) { + ui.signalRepositoryOperationStart(); + SubMonitor mon = SubMonitor.convert(monitor, locations.length * 100); + for (int i = 0; i < locations.length; i++) { + try { + session.getArtifactRepositoryManager().refreshRepository(locations[i], mon.newChild(100)); + } catch (ProvisionException e) { + //ignore problematic repositories when refreshing + } + } + // We have no idea how many repos may have been added/removed as a result of + // refreshing these, this one, so we do not use a specific repository event to represent it. + ui.signalRepositoryOperationComplete(null, true); + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProfileFactory.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProfileFactory.java new file mode 100644 index 000000000..cae6b67f1 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProfileFactory.java @@ -0,0 +1,80 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.admin; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.util.HashMap; +import java.util.Map; +import org.eclipse.core.runtime.Platform; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.osgi.service.environment.EnvironmentInfo; + +/** + * Factory class that can create a new profile with the correct + * default values. + * + * @since 3.4 + * + */ +public class ProfileFactory { + + static private String FLAVOR_DEFAULT = "tooling"; //$NON-NLS-1$ + static private String EMPTY = ""; //$NON-NLS-1$ + static private EnvironmentInfo info; + + public static IProfile makeProfile(String profileId) { + Map profileProperties = new HashMap(); + profileProperties.put(IProfile.PROP_INSTALL_FOLDER, getDefaultLocation()); + profileProperties.put(IProfile.PROP_ENVIRONMENTS, getDefaultEnvironments()); + profileProperties.put(IProfile.PROP_NL, getDefaultNL()); + + try { + return ProvAdminUIActivator.getDefault().getProvisioningUI(null).getSession().getProfileRegistry().addProfile(profileId, profileProperties); + } catch (ProvisionException e) { + // log + } + return null; + } + + public static String getDefaultLocation() { + return Platform.getUserLocation().getURL().getPath(); + } + + public static String getDefaultFlavor() { + return FLAVOR_DEFAULT; + } + + private static EnvironmentInfo getEnvironmentInfo() { + if (info == null) { + info = (EnvironmentInfo) ServiceHelper.getService(ProvUIActivator.getContext(), EnvironmentInfo.class.getName()); + } + return info; + } + + public static String getDefaultNL() { + if (getEnvironmentInfo() != null) { + return info.getNL(); + } + return EMPTY; + } + + public static String getDefaultEnvironments() { + if (getEnvironmentInfo() != null) { + return "osgi.os=" //$NON-NLS-1$ + + info.getOS() + ",osgi.ws=" + info.getWS() //$NON-NLS-1$ + + ",osgi.arch=" + info.getOSArch(); //$NON-NLS-1$ + } + return EMPTY; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProfilesView.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProfilesView.java index 43cb8b357..df5cef119 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProfilesView.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProfilesView.java @@ -13,28 +13,23 @@ package org.eclipse.equinox.internal.p2.ui.admin; import java.util.ArrayList; import java.util.List; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.actions.UninstallAction; +import org.eclipse.equinox.internal.p2.ui.actions.UpdateAction; import org.eclipse.equinox.internal.p2.ui.admin.dialogs.AddProfileDialog; import org.eclipse.equinox.internal.p2.ui.admin.preferences.PreferenceConstants; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.UninstallAction; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.UpdateAction; -import org.eclipse.equinox.internal.provisional.p2.ui.model.*; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.RemoveProfilesOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.IProfileChooser; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.*; +import org.eclipse.equinox.internal.p2.ui.model.*; +import org.eclipse.equinox.internal.p2.ui.viewers.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.action.*; import org.eclipse.jface.viewers.*; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.Transfer; -import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.dialogs.PropertyDialogAction; -import org.eclipse.ui.statushandlers.StatusManager; /** * This view allows users to interact with installed profiles. @@ -42,7 +37,7 @@ import org.eclipse.ui.statushandlers.StatusManager; * @since 3.4 */ public class ProfilesView extends ProvView { - private Action addProfileAction, removeProfileAction, uninstallAction; + protected Action addProfileAction, removeProfileAction, uninstallAction; UpdateAction updateAction; private PropertyDialogAction propertiesAction; private StructuredViewerProvisioningListener listener; @@ -58,13 +53,13 @@ public class ProfilesView extends ProvView { public void run() { Object[] selections = getSelection().toArray(); - List profilesOnly = new ArrayList(); + List profilesOnly = new ArrayList(); for (int i = 0; i < selections.length; i++) { if (selections[i] instanceof ProfileElement) profilesOnly.add(((ProfileElement) selections[i]).getProfileId()); } - RemoveProfilesOperation op = new RemoveProfilesOperation(ProvAdminUIMessages.Ops_RemoveProfileOperationLabel, (String[]) profilesOnly.toArray(new String[profilesOnly.size()])); - ProvisioningOperationRunner.run(op, StatusManager.SHOW | StatusManager.LOG); + RemoveProfilesJob op = new RemoveProfilesJob(ProvAdminUIMessages.Ops_RemoveProfileOperationLabel, getProvisioningUI().getSession(), profilesOnly.toArray(new String[profilesOnly.size()])); + ProfilesView.this.run(op); } } @@ -86,7 +81,7 @@ public class ProfilesView extends ProvView { protected void addListeners() { super.addListeners(); - listener = new StructuredViewerProvisioningListener(viewer, StructuredViewerProvisioningListener.PROV_EVENT_IU | StructuredViewerProvisioningListener.PROV_EVENT_PROFILE); + listener = new StructuredViewerProvisioningListener(viewer, ProvUIProvisioningListener.PROV_EVENT_IU | ProvUIProvisioningListener.PROV_EVENT_PROFILE); ProvUI.addProvisioningListener(listener); } @@ -97,7 +92,7 @@ public class ProfilesView extends ProvView { protected void configureViewer(TreeViewer treeViewer) { super.configureViewer(treeViewer); - InstallIUDropAdapter adapter = new InstallIUDropAdapter(ProvAdminUIActivator.getDefault().getPolicy(), treeViewer); + InstallIUDropAdapter adapter = new InstallIUDropAdapter(getProvisioningUI(), treeViewer); adapter.setFeedbackEnabled(false); Transfer[] transfers = new Transfer[] {org.eclipse.jface.util.LocalSelectionTransfer.getTransfer()}; treeViewer.addDropSupport(DND.DROP_COPY, transfers, adapter); @@ -137,9 +132,9 @@ public class ProfilesView extends ProvView { super.makeActions(); addProfileAction = new AddProfileAction(); removeProfileAction = new RemoveProfileAction(); - uninstallAction = new UninstallAction(ProvAdminUIActivator.getDefault().getPolicy(), viewer, null); + uninstallAction = new UninstallAction(getProvisioningUI(), viewer, null); propertiesAction = new PropertyDialogAction(this.getSite(), viewer); - updateAction = new UpdateAction(ProvAdminUIActivator.getDefault().getPolicy(), viewer, null, true); + updateAction = new UpdateAction(getProvisioningUI(), viewer, null, true); updateAction.setSkipSelectionPage(true); getViewSite().getActionBars().setGlobalActionHandler(ActionFactory.PROPERTIES.getId(), propertiesAction); @@ -165,7 +160,7 @@ public class ProfilesView extends ProvView { if (selectionArray.length > 0) { removeProfileAction.setEnabled(true); for (int i = 0; i < selectionArray.length; i++) { - IProfile profile = (IProfile) ProvUI.getAdapter(selectionArray[i], IProfile.class); + IProfile profile = ProvUI.getAdapter(selectionArray[i], IProfile.class); if (profile == null) { removeProfileAction.setEnabled(false); break; @@ -183,41 +178,35 @@ public class ProfilesView extends ProvView { } protected Object getInput() { - return new Profiles(ProvAdminUIActivator.getDefault().getPolicy()); + return new Profiles(getProvisioningUI()); } - IProfileChooser getProfileChooser() { - return new IProfileChooser() { - public String getProfileId(Shell shell) { - Object firstElement = getSelection().getFirstElement(); - if (firstElement instanceof InstalledIUElement) { - return ((InstalledIUElement) firstElement).getProfileId(); - } - IProfile profile = (IProfile) ProvUI.getAdapter(firstElement, IProfile.class); - if (profile != null) - return profile.getProfileId(); - return null; - } - }; + protected String getProfileId() { + Object firstElement = getSelection().getFirstElement(); + if (firstElement instanceof InstalledIUElement) { + return ((InstalledIUElement) firstElement).getProfileId(); + } + IProfile profile = ProvUI.getAdapter(firstElement, IProfile.class); + if (profile != null) + return profile.getProfileId(); + return null; } - protected List getVisualProperties() { - List list = super.getVisualProperties(); + protected List getVisualProperties() { + List list = super.getVisualProperties(); list.add(PreferenceConstants.PREF_SHOW_INSTALL_ROOTS_ONLY); return list; } String[] getKnownProfileIds() { - try { - IProfile[] allProfiles = ProvisioningUtil.getProfiles(); - String[] ids = new String[allProfiles.length]; - for (int i = 0; i < allProfiles.length; i++) - ids[i] = allProfiles[i].getProfileId(); - return ids; - } catch (ProvisionException e) { - ProvUI.handleException(e, ProvAdminUIMessages.ProfilesView_ErrorRetrievingProfiles, StatusManager.LOG); - return new String[0]; - } + IProfile[] allProfiles = getProvisioningUI().getSession().getProfileRegistry().getProfiles(); + String[] ids = new String[allProfiles.length]; + for (int i = 0; i < allProfiles.length; i++) + ids[i] = allProfiles[i].getProfileId(); + return ids; + } + protected ProvisioningUI getProvisioningUI() { + return ProvAdminUIActivator.getDefault().getProvisioningUI(getProfileId()); } } diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProvAdminUIActivator.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProvAdminUIActivator.java index 04daad34e..b9dafea71 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProvAdminUIActivator.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProvAdminUIActivator.java @@ -10,26 +10,21 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.admin; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; - -import org.eclipse.equinox.internal.p2.ui.admin.dialogs.AddProfileDialog; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; +import org.eclipse.equinox.internal.p2.ui.ValidationDialogServiceUI; import org.eclipse.equinox.internal.p2.ui.admin.preferences.PreferenceConstants; import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.ValidationDialogServiceUI; -import org.eclipse.equinox.internal.provisional.p2.ui.model.Profiles; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.ProvElementContentProvider; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.ProvElementLabelProvider; +import org.eclipse.equinox.p2.engine.query.UserVisibleRootQuery; +import org.eclipse.equinox.p2.metadata.query.GroupQuery; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.ui.Policy; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.jface.window.Window; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.dialogs.ListDialog; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; @@ -105,79 +100,52 @@ public class ProvAdminUIActivator extends AbstractUIPlugin { if (preferenceListener == null) { preferenceListener = new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { - updateForPreferences(getPolicy().getQueryContext()); + updateForPreferences(); } }; } return preferenceListener; } - void updateForPreferences(IUViewQueryContext queryContext) { + void updateForPreferences() { + if (getPreferenceStore().getBoolean(PreferenceConstants.PREF_SHOW_GROUPS_ONLY)) - queryContext.setVisibleAvailableIUProperty(IInstallableUnit.PROP_TYPE_GROUP); + policy.setVisibleAvailableIUQuery(new GroupQuery()); else - queryContext.setVisibleAvailableIUProperty(null); + policy.setVisibleAvailableIUQuery(InstallableUnitQuery.ANY); if (getPreferenceStore().getBoolean(PreferenceConstants.PREF_SHOW_INSTALL_ROOTS_ONLY)) - queryContext.setVisibleInstalledIUProperty(IInstallableUnit.PROP_PROFILE_ROOT_IU); + policy.setVisibleInstalledIUQuery(new UserVisibleRootQuery()); else - queryContext.setVisibleInstalledIUProperty(null); + policy.setVisibleInstalledIUQuery(InstallableUnitQuery.ANY); + RepositoryTracker tracker = getRepositoryTracker(); if (getPreferenceStore().getBoolean(PreferenceConstants.PREF_HIDE_SYSTEM_REPOS)) { - queryContext.setArtifactRepositoryFlags(IRepositoryManager.REPOSITORIES_NON_SYSTEM); - queryContext.setMetadataRepositoryFlags(IRepositoryManager.REPOSITORIES_NON_SYSTEM); + tracker.setArtifactRepositoryFlags(IRepositoryManager.REPOSITORIES_NON_SYSTEM); + tracker.setMetadataRepositoryFlags(IRepositoryManager.REPOSITORIES_NON_SYSTEM); } else { - queryContext.setArtifactRepositoryFlags(IRepositoryManager.REPOSITORIES_ALL); - queryContext.setMetadataRepositoryFlags(IRepositoryManager.REPOSITORIES_ALL); + tracker.setArtifactRepositoryFlags(IRepositoryManager.REPOSITORIES_ALL); + tracker.setMetadataRepositoryFlags(IRepositoryManager.REPOSITORIES_ALL); } - queryContext.setShowLatestVersionsOnly(getPreferenceStore().getBoolean(PreferenceConstants.PREF_COLLAPSE_IU_VERSIONS)); - queryContext.setUseCategories(getPreferenceStore().getBoolean(PreferenceConstants.PREF_USE_CATEGORIES)); + // store in ui prefs + policy.setShowLatestVersionsOnly(getPreferenceStore().getBoolean(PreferenceConstants.PREF_COLLAPSE_IU_VERSIONS)); + policy.setGroupByCategory(getPreferenceStore().getBoolean(PreferenceConstants.PREF_USE_CATEGORIES)); + } + + private RepositoryTracker getRepositoryTracker() { + return (RepositoryTracker) ServiceHelper.getService(ProvUIActivator.getContext(), RepositoryTracker.class.getName()); } void initializePolicy() { policy = new Policy(); // Manipulate the default query context according to our preferences - IUViewQueryContext queryContext = new IUViewQueryContext(IUViewQueryContext.AVAILABLE_VIEW_BY_REPO); - policy.setQueryContext(queryContext); - updateForPreferences(queryContext); - policy.setPlanValidator(new PlanValidator() { - public boolean continueWorkingWithPlan(ProvisioningPlan plan, Shell shell) { - if (plan == null) - return false; - return true; - } - }); - policy.setProfileChooser(new IProfileChooser() { - public String getProfileId(Shell shell) { - // TODO would be nice if the profile chooser dialog let you - // create a new profile - ProvElementContentProvider provider = new ProvElementContentProvider(); - if (provider.getElements(new Profiles(getPolicy())).length == 0) { - AddProfileDialog dialog = new AddProfileDialog(shell, new String[0]); - if (dialog.open() == Window.OK) { - return dialog.getAddedProfileId(); - } - return null; - } - - ListDialog dialog = new ListDialog(shell); - dialog.setTitle(ProvAdminUIMessages.MetadataRepositoriesView_ChooseProfileDialogTitle); - dialog.setLabelProvider(new ProvElementLabelProvider()); - dialog.setInput(new Profiles(getPolicy())); - dialog.setContentProvider(provider); - dialog.open(); - Object[] result = dialog.getResult(); - if (result != null && result.length > 0) { - IProfile profile = (IProfile) ProvUI.getAdapter(result[0], IProfile.class); - if (profile != null) - return profile.getProfileId(); - } - return null; - } - }); - policy.setRepositoryManipulator(new ColocatedRepositoryManipulator(policy, null)); + updateForPreferences(); } public Policy getPolicy() { return policy; } + + public ProvisioningUI getProvisioningUI(String profileId) { + return new ProvisioningUI(ProvisioningUI.getDefaultUI().getSession(), profileId, policy); + } } diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProvAdminUIMessages.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProvAdminUIMessages.java index 750c738a3..b91502737 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProvAdminUIMessages.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProvAdminUIMessages.java @@ -24,20 +24,13 @@ public class ProvAdminUIMessages extends NLS { // load message values from bundle file NLS.initializeMessages(BUNDLE_NAME, ProvAdminUIMessages.class); } - public static String AddArtifactRepositoryDialog_DuplicateURL; - public static String AddArtifactRepositoryDialog_ManipulateRepositoryInstruction; - public static String AddArtifactRepositoryDialog_OperationLabel; public static String AddProfileDialog_Title; - public static String AddMetadataRepositoryDialog_OperationLabel; public static String MetadataRepositoriesView_AddRepositoryTooltip; public static String MetadataRepositoriesView_AddRepositoryLabel; - public static String MetadataRepositoriesView_ChooseProfileDialogTitle; public static String MetadataRepositoriesView_RemoveRepositoryTooltip; public static String ArtifactRepositoriesView_AddRepositoryTooltip; public static String ArtifactRepositoriesView_AddRepositoryLabel; public static String ArtifactRepositoriesView_RemoveRepositoryTooltip; - public static String ArtifactRepositoriesView_RemoveRepositoryOperationLabel; - public static String ProfilesView_ErrorRetrievingProfiles; public static String ProfilesView_AddProfileTooltip; public static String ProfilesView_AddProfileLabel; public static String ProfilesView_RemoveProfileLabel; @@ -53,7 +46,6 @@ public class ProvAdminUIMessages extends NLS { public static String Ops_RemoveProfileOperationLabel; public static String AddProfileDialog_OperationLabel; public static String AddProfileDialog_DuplicateProfileID; - public static String ProvView_RefreshCommandLabel; public static String ProvView_RefreshCommandTooltip; public static String ProfileRootPropertyName; @@ -75,7 +67,6 @@ public class ProvAdminUIMessages extends NLS { public static String IUGroup_TouchpointData; public static String IUGroup_TouchpointType; public static String IUGroup_Version; - public static String IUProfilePropertiesGroup_InvalidProfileID; public static String IUPropertiesGroup_DescriptionPropertyLabel; public static String IUPropertiesGroup_NamePropertyLabel; diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProvView.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProvView.java index fb68eba51..c6d28b7e1 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProvView.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/ProvView.java @@ -12,9 +12,13 @@ package org.eclipse.equinox.internal.p2.ui.admin; import java.util.ArrayList; import java.util.List; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.ui.actions.RefreshAction; import org.eclipse.equinox.internal.p2.ui.admin.preferences.PreferenceConstants; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.RefreshAction; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.*; +import org.eclipse.equinox.internal.p2.ui.viewers.*; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.operations.ProvisioningJob; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.action.*; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; @@ -25,6 +29,7 @@ import org.eclipse.swt.widgets.*; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.part.ViewPart; +import org.eclipse.ui.progress.IWorkbenchSiteProgressService; /** * This class supports the common characteristics for views that manipulate @@ -33,10 +38,11 @@ import org.eclipse.ui.part.ViewPart; * @since 3.4 */ abstract class ProvView extends ViewPart { - TreeViewer viewer; + protected TreeViewer viewer; RefreshAction refreshAction; private IPropertyChangeListener preferenceListener; protected Display display; + private ProvisioningUI ui; /** * The constructor. @@ -118,7 +124,7 @@ abstract class ProvView extends ViewPart { protected abstract IAction getDoubleClickAction(); protected void makeActions() { - refreshAction = new RefreshAction(viewer, viewer.getControl()) { + refreshAction = new RefreshAction(ProvisioningUI.getDefaultUI(), viewer, viewer.getControl()) { protected void refresh() { refreshAll(true); } @@ -172,10 +178,18 @@ abstract class ProvView extends ViewPart { return viewer.getControl(); } - IStructuredSelection getSelection() { + protected IStructuredSelection getSelection() { return (IStructuredSelection) viewer.getSelection(); } + protected void run(ProvisioningJob job) { + IWorkbenchSiteProgressService service = (IWorkbenchSiteProgressService) getSite().getService(IWorkbenchSiteProgressService.class); + if (service != null) + service.schedule(job); + else + job.runModal(new NullProgressMonitor()); + } + protected void configureViewer(final TreeViewer treeViewer) { viewer.setComparator(new IUComparator(IUComparator.IU_ID)); viewer.setComparer(new ProvElementComparer()); @@ -206,11 +220,11 @@ abstract class ProvView extends ViewPart { } protected void refreshUnderlyingModel() { - // Default is to do nothing + // do nothing by default } - protected List getVisualProperties() { - ArrayList list = new ArrayList(1); + protected List getVisualProperties() { + ArrayList list = new ArrayList(1); list.add(PreferenceConstants.PREF_SHOW_GROUPS_ONLY); return list; } @@ -224,4 +238,14 @@ abstract class ProvView extends ViewPart { // will get queried again. viewer.setInput(getInput()); } + + protected String getProfileId() { + return IProfileRegistry.SELF; + } + + protected ProvisioningUI getProvisioningUI() { + if (ui == null) + ui = ProvAdminUIActivator.getDefault().getProvisioningUI(getProfileId()); + return ui; + } } diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RefreshArtifactRepositoriesOperation.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RefreshArtifactRepositoriesOperation.java deleted file mode 100644 index a7754a95e..000000000 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RefreshArtifactRepositoriesOperation.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.p2.ui.admin; - -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.RepositoryOperation; - -import java.net.URI; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.ui.statushandlers.StatusManager; - -/** - * @since 3.4 - * - */ -public class RefreshArtifactRepositoriesOperation extends RepositoryOperation { - - /** - * @param label - * @param locations - */ - public RefreshArtifactRepositoriesOperation(String label, URI[] locations) { - super(label, locations); - } - - public RefreshArtifactRepositoriesOperation(String label, int flags) { - super(label, new URI[0]); - try { - this.locations = ProvisioningUtil.getArtifactRepositories(flags); - } catch (ProvisionException e) { - ProvUI.handleException(e, null, StatusManager.LOG); - } - } - - protected IStatus doBatchedExecute(IProgressMonitor monitor) throws ProvisionException { - ProvisioningUtil.refreshArtifactRepositories(locations, monitor); - return Status.OK_STATUS; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RefreshMetadataRepositoriesOperation.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RefreshMetadataRepositoriesOperation.java deleted file mode 100644 index 44b086d09..000000000 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RefreshMetadataRepositoriesOperation.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.p2.ui.admin; - -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.RepositoryOperation; - -import java.net.URI; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.ui.statushandlers.StatusManager; - -/** - * @since 3.4 - * - */ -public class RefreshMetadataRepositoriesOperation extends RepositoryOperation { - - /** - * @param label - * @param locations - */ - public RefreshMetadataRepositoriesOperation(String label, URI[] locations) { - super(label, locations); - } - - public RefreshMetadataRepositoriesOperation(String label, int flags) { - super(label, new URI[0]); - try { - this.locations = ProvisioningUtil.getMetadataRepositories(flags); - } catch (ProvisionException e) { - ProvUI.handleException(e, null, StatusManager.LOG); - } - } - - protected IStatus doBatchedExecute(IProgressMonitor monitor) throws ProvisionException { - // Clear the not found cache so that repos not found are reported again. - ProvUI.clearRepositoriesNotFound(); - ProvisioningUtil.refreshMetadataRepositories(locations, monitor); - return Status.OK_STATUS; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RemoveArtifactRepositoryOperation.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RemoveArtifactRepositoryOperation.java deleted file mode 100644 index c5dda16d4..000000000 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RemoveArtifactRepositoryOperation.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.ui.admin; - -import java.net.URI; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.RemoveRepositoryOperation; - -/** - * Operation which removes the artifact repository with the given URL. - * - * @since 3.4 - */ -public class RemoveArtifactRepositoryOperation extends RemoveRepositoryOperation { - - public RemoveArtifactRepositoryOperation(String label, URI[] repoLocations) { - super(label, repoLocations); - } - - protected IStatus doBatchedExecute(IProgressMonitor monitor) throws ProvisionException { - SubMonitor mon = SubMonitor.convert(monitor, locations.length); - for (int i = 0; i < locations.length; i++) { - ProvisioningUtil.removeArtifactRepository(locations[i]); - mon.worked(1); - } - return okStatus(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RemoveMetadataRepositoryOperation.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RemoveMetadataRepositoryOperation.java deleted file mode 100644 index 7f99b5d3e..000000000 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RemoveMetadataRepositoryOperation.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.ui.admin; - -import java.net.URI; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.RemoveRepositoryOperation; - -/** - * Operation that removes the metadata repository with the given location. - * - * @since 3.4 - */ -public class RemoveMetadataRepositoryOperation extends RemoveRepositoryOperation { - - public RemoveMetadataRepositoryOperation(String label, URI[] repoLocations) { - super(label, repoLocations); - } - - protected IStatus doBatchedExecute(IProgressMonitor monitor) throws ProvisionException { - SubMonitor mon = SubMonitor.convert(monitor, locations.length); - for (int i = 0; i < locations.length; i++) { - ProvisioningUtil.removeMetadataRepository(locations[i]); - mon.worked(1); - } - return okStatus(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RemoveProfilesJob.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RemoveProfilesJob.java new file mode 100644 index 000000000..94d1eec82 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RemoveProfilesJob.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.admin; + +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.p2.operations.ProvisioningJob; +import org.eclipse.equinox.p2.operations.ProvisioningSession; + +/** + * Job that removes one or more profiles. + * + * @since 3.6 + */ +public class RemoveProfilesJob extends ProvisioningJob { + String[] profileIds; + + public RemoveProfilesJob(String label, ProvisioningSession session, String[] profileIds) { + super(label, session); + this.profileIds = profileIds; + } + + public IStatus runModal(IProgressMonitor monitor) { + for (int i = 0; i < profileIds.length; i++) { + getSession().getProfileRegistry().removeProfile(profileIds[i]); + } + return Status.OK_STATUS; + + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RepositoriesView.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RepositoriesView.java index fecff8b3e..cf21efabc 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RepositoriesView.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/RepositoriesView.java @@ -10,22 +10,29 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.admin; +import java.lang.reflect.InvocationTargetException; +import java.net.URI; import java.util.ArrayList; import java.util.List; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.internal.p2.ui.ProvUIImages; import org.eclipse.equinox.internal.p2.ui.admin.preferences.PreferenceConstants; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IRepositoryElement; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.RemoveRepositoryOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.RepositoryContentProvider; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.StructuredViewerProvisioningListener; +import org.eclipse.equinox.internal.p2.ui.model.IRepositoryElement; +import org.eclipse.equinox.internal.p2.ui.viewers.RepositoryContentProvider; +import org.eclipse.equinox.internal.p2.ui.viewers.StructuredViewerProvisioningListener; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.RepositoryTracker; import org.eclipse.jface.action.*; +import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.*; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.dialogs.PropertyDialogAction; +import org.eclipse.ui.progress.IWorkbenchSiteProgressService; import org.eclipse.ui.statushandlers.StatusManager; /** @@ -46,7 +53,14 @@ abstract class RepositoriesView extends ProvView { } public void run() { - ProvisioningOperationRunner.run(getRemoveOperation(getSelection().toArray()), StatusManager.SHOW | StatusManager.LOG); + RepositoryTracker tracker = RepositoriesView.this.getRepositoryTracker(); + Object[] elements = getSelection().toArray(); + ArrayList uris = new ArrayList(elements.length); + for (int i = 0; i < elements.length; i++) { + if (elements[i] instanceof IRepositoryElement) + uris.add(((IRepositoryElement) elements[i]).getLocation()); + } + tracker.removeRepositories(uris.toArray(new URI[uris.size()]), RepositoriesView.this.getProvisioningUI().getSession()); } } @@ -60,10 +74,10 @@ abstract class RepositoriesView extends ProvView { public void run() { Object[] elements = ((ITreeContentProvider) viewer.getContentProvider()).getElements(getInput()); - ArrayList urls = new ArrayList(); + ArrayList urls = new ArrayList(); for (int i = 0; i < elements.length; i++) - if (elements[i] instanceof IRepositoryElement) - urls.add(((IRepositoryElement) elements[i]).getLocation()); + if (elements[i] instanceof IRepositoryElement) + urls.add(((IRepositoryElement) elements[i]).getLocation()); openAddRepositoryDialog(getShell()); } } @@ -164,9 +178,9 @@ abstract class RepositoriesView extends ProvView { } - protected abstract int openAddRepositoryDialog(Shell shell); + protected abstract RepositoryTracker getRepositoryTracker(); - protected abstract RemoveRepositoryOperation getRemoveOperation(Object[] elements); + protected abstract int openAddRepositoryDialog(Shell shell); protected abstract String getAddCommandLabel(); @@ -179,14 +193,32 @@ abstract class RepositoriesView extends ProvView { protected abstract String getRemoveCommandTooltip(); protected boolean isRepository(Object element) { - return element instanceof IRepositoryElement; + return element instanceof IRepositoryElement; } protected abstract int getListenerEventTypes(); - protected List getVisualProperties() { - List list = super.getVisualProperties(); + protected List getVisualProperties() { + List list = super.getVisualProperties(); list.add(PreferenceConstants.PREF_HIDE_SYSTEM_REPOS); return list; } + + protected void refreshUnderlyingModel() { + IWorkbenchSiteProgressService service = (IWorkbenchSiteProgressService) getSite().getAdapter(IWorkbenchSiteProgressService.class); + if (service != null) { + try { + service.run(true, false, new IRunnableWithProgress() { + public void run(IProgressMonitor monitor) { + getRepositoryTracker().refreshRepositories(getRepositoryTracker().getKnownRepositories(getProvisioningUI().getSession()), getProvisioningUI().getSession(), monitor); + } + }); + } catch (InvocationTargetException e) { + ProvUI.handleException(e, null, StatusManager.SHOW); + } catch (InterruptedException e) { + // ignore + } + } else + getRepositoryTracker().refreshRepositories(getRepositoryTracker().getKnownRepositories(getProvisioningUI().getSession()), getProvisioningUI().getSession(), new NullProgressMonitor()); + } } diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/AddArtifactRepositoryDialog.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/AddArtifactRepositoryDialog.java index 8d4f2655d..e94be5aac 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/AddArtifactRepositoryDialog.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/AddArtifactRepositoryDialog.java @@ -10,13 +10,10 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.admin.dialogs; -import java.net.URI; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.ui.admin.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.AddRepositoryDialog; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.*; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; +import org.eclipse.equinox.internal.p2.ui.admin.ArtifactRepositoryTracker; +import org.eclipse.equinox.internal.p2.ui.dialogs.AddRepositoryDialog; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.swt.widgets.Shell; /** @@ -27,101 +24,17 @@ import org.eclipse.swt.widgets.Shell; */ public class AddArtifactRepositoryDialog extends AddRepositoryDialog { - class ArtifactRepositoryManipulator extends RepositoryManipulator { - RepositoryLocationValidator validator; + RepositoryTracker tracker; - public AddRepositoryOperation getAddOperation(URI location) { - return new AddArtifactRepositoryOperation(ProvAdminUIMessages.AddArtifactRepositoryDialog_OperationLabel, location); - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getAddOperationLabel() - */ - public String getAddOperationLabel() { - return ProvAdminUIMessages.AddArtifactRepositoryDialog_OperationLabel; - } - - public String getManipulatorButtonLabel() { - // Not used in this dialog - return null; - } - - public String getManipulatorLinkLabel() { - // Not used in this dialog - return null; - } - - public RemoveRepositoryOperation getRemoveOperation(URI[] repoLocations) { - return new RemoveArtifactRepositoryOperation(ProvAdminUIMessages.ArtifactRepositoriesView_RemoveRepositoryOperationLabel, repoLocations); - } - - public String getRemoveOperationLabel() { - return ProvAdminUIMessages.ArtifactRepositoriesView_RemoveRepositoryOperationLabel; - } - - public RepositoryLocationValidator getRepositoryLocationValidator(Shell shell) { - if (validator == null) { - validator = new RepositoryLocationValidator() { - public IStatus validateRepositoryLocation(URI location, boolean contactRepositories, IProgressMonitor monitor) { - IStatus duplicateStatus = Status.OK_STATUS; - URI[] knownRepositories = getKnownRepositories(); - for (int i = 0; i < knownRepositories.length; i++) { - if (knownRepositories[i].equals(location)) { - duplicateStatus = new Status(IStatus.ERROR, ProvAdminUIActivator.PLUGIN_ID, LOCAL_VALIDATION_ERROR, ProvAdminUIMessages.AddArtifactRepositoryDialog_DuplicateURL, null); - break; - } - } - return duplicateStatus; - } - }; - } - return validator; - } - - public boolean manipulateRepositories(Shell shell) { - // Not used in this dialog - return false; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getKnownRepositories() - */ - public URI[] getKnownRepositories() { - try { - return ProvisioningUtil.getArtifactRepositories(ProvAdminUIActivator.getDefault().getPolicy().getQueryContext().getArtifactRepositoryFlags()); - } catch (ProvisionException e) { - return new URI[0]; - } - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getManipulatorInstructionString() - */ - public String getManipulatorInstructionString() { - // We don't have a manipulator - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getSiteNotFoundCorrectionString() - */ - public String getRepositoryNotFoundInstructionString() { - return ProvAdminUIMessages.AddArtifactRepositoryDialog_ManipulateRepositoryInstruction; - } - - } - - RepositoryManipulator manipulator; - - public AddArtifactRepositoryDialog(Shell parentShell, Policy policy) { - super(parentShell, policy); + public AddArtifactRepositoryDialog(Shell parentShell, ProvisioningUI ui) { + super(parentShell, ui); } - protected RepositoryManipulator getRepositoryManipulator() { - if (manipulator == null) { - manipulator = new ArtifactRepositoryManipulator(); + protected RepositoryTracker getRepositoryTracker() { + if (tracker == null) { + tracker = new ArtifactRepositoryTracker(getProvisioningUI()); } - return manipulator; + return tracker; } } diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/AddMetadataRepositoryDialog.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/AddMetadataRepositoryDialog.java index bbf0d8b0e..8281f22bf 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/AddMetadataRepositoryDialog.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/AddMetadataRepositoryDialog.java @@ -10,12 +10,10 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.admin.dialogs; -import java.net.URI; -import org.eclipse.equinox.internal.p2.ui.admin.AddMetadataRepositoryOperation; -import org.eclipse.equinox.internal.p2.ui.admin.ProvAdminUIMessages; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.AddRepositoryDialog; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.AddRepositoryOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.admin.MetadataRepositoryTracker; +import org.eclipse.equinox.internal.p2.ui.dialogs.AddRepositoryDialog; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.swt.widgets.Shell; /** @@ -26,11 +24,16 @@ import org.eclipse.swt.widgets.Shell; */ public class AddMetadataRepositoryDialog extends AddRepositoryDialog { - public AddMetadataRepositoryDialog(Shell parentShell, Policy policy) { - super(parentShell, policy); + RepositoryTracker tracker; + + public AddMetadataRepositoryDialog(Shell parentShell, ProvisioningUI ui) { + super(parentShell, ui); } - protected AddRepositoryOperation getOperation(URI location) { - return new AddMetadataRepositoryOperation(ProvAdminUIMessages.AddMetadataRepositoryDialog_OperationLabel, location); + protected RepositoryTracker getRepositoryTracker() { + if (tracker == null) { + tracker = new MetadataRepositoryTracker(getProvisioningUI()); + } + return tracker; } } diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/AddProfileDialog.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/AddProfileDialog.java index 5b215dea5..7d5d88ce2 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/AddProfileDialog.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/AddProfileDialog.java @@ -11,19 +11,15 @@ package org.eclipse.equinox.internal.p2.ui.admin.dialogs; import java.util.Map; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.equinox.internal.p2.ui.admin.ProvAdminUIActivator; -import org.eclipse.equinox.internal.p2.ui.admin.ProvAdminUIMessages; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.AddProfileOperation; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.ui.admin.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.widgets.*; -import org.eclipse.ui.statushandlers.StatusManager; /** * Dialog that allows a profile to be defined and added. @@ -77,8 +73,9 @@ public class AddProfileDialog extends StatusDialog { return; } addedProfileId = profileGroup.getProfileId(); - Map profileProperties = profileGroup.getProfileProperties(); - ProvisioningOperationRunner.run(new AddProfileOperation(ProvAdminUIMessages.AddProfileDialog_OperationLabel, addedProfileId, profileProperties), StatusManager.SHOW | StatusManager.LOG); + Map profileProperties = profileGroup.getProfileProperties(); + AddProfileJob job = new AddProfileJob(ProvAdminUIMessages.AddProfileDialog_OperationLabel, ProvisioningUI.getDefaultUI().getSession(), addedProfileId, profileProperties); + job.runModal(new NullProgressMonitor()); } void verifyComplete() { diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUGroup.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUGroup.java index 61d125416..e3729873a 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUGroup.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUGroup.java @@ -10,8 +10,8 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.admin.dialogs; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.widgets.Composite; @@ -38,7 +38,7 @@ public abstract class IUGroup { } public IInstallableUnit getIU() { - return (IInstallableUnit) ProvUI.getAdapter(iuElement, IInstallableUnit.class); + return ProvUI.getAdapter(iuElement, IInstallableUnit.class); } public void updateIU() { diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUImplementationGroup.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUImplementationGroup.java index 158a70ace..9e898e6ee 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUImplementationGroup.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUImplementationGroup.java @@ -10,14 +10,19 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.admin.dialogs; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.Version; +import org.eclipse.equinox.p2.metadata.*; + +import java.util.Collection; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.ui.admin.ProvAdminUIActivator; import org.eclipse.equinox.internal.p2.ui.admin.ProvAdminUIMessages; import org.eclipse.equinox.internal.provisional.p2.metadata.*; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; @@ -154,23 +159,25 @@ public class IUImplementationGroup extends IUGroup { if (type != null) { touchpointType.setText(type.getId()); } - ITouchpointData[] data = iu.getTouchpointData(); - String[] items = new String[data.length]; - for (int i = 0; i < data.length; i++) { - items[i] = data[i].toString(); + java.util.List data = iu.getTouchpointData(); + String[] items = new String[data.size()]; + for (int i = 0; i < data.size(); i++) { + items[i] = data.get(i).toString(); } touchpointData.setItems(items); - IRequiredCapability[] req = iu.getRequiredCapabilities(); - items = new String[req.length]; - for (int i = 0; i < req.length; i++) { - items[i] = req[i].toString(); + Collection reqs = iu.getRequiredCapabilities(); + items = new String[reqs.size()]; + int j = 0; + for (IRequirement req : reqs) { + items[j++] = req.toString(); } requiredCapabilities.setItems(items); - IProvidedCapability[] prov = iu.getProvidedCapabilities(); - items = new String[prov.length]; - for (int i = 0; i < prov.length; i++) { - items[i] = prov[i].toString(); + Collection prov = iu.getProvidedCapabilities(); + items = new String[prov.size()]; + int i = 0; + for (IProvidedCapability capability : prov) { + items[i++] = capability.toString(); } providedCapabilities.setItems(items); } @@ -180,10 +187,10 @@ public class IUImplementationGroup extends IUGroup { if (iuElement == null || iuElement instanceof IInstallableUnit) { InstallableUnitDescription unit = new InstallableUnitDescription(); unit.setId(id.getText().trim()); - unit.setVersion(new Version(version.getText().trim())); + unit.setVersion(Version.create(version.getText().trim())); unit.setProperty(IInstallableUnit.NAMESPACE_IU_ID, namespace.getText().trim()); // TODO this is bogus because we don't let user provide a touchpoint type version - unit.setTouchpointType(MetadataFactory.createTouchpointType(touchpointType.getText().trim(), new Version("1.0.0"))); //$NON-NLS-1$ + unit.setTouchpointType(MetadataFactory.createTouchpointType(touchpointType.getText().trim(), Version.create("1.0.0"))); //$NON-NLS-1$ iuElement = MetadataFactory.createInstallableUnit(unit); } } diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUImplementationPropertyPage.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUImplementationPropertyPage.java index 8a679d479..04a751e26 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUImplementationPropertyPage.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUImplementationPropertyPage.java @@ -11,9 +11,9 @@ package org.eclipse.equinox.internal.p2.ui.admin.dialogs; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.ui.ProvUI; import org.eclipse.equinox.internal.p2.ui.admin.ProvAdminUIMessages; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; @@ -31,7 +31,7 @@ public class IUImplementationPropertyPage extends PropertyPage { private IUImplementationGroup iuGroup; protected Control createContents(Composite parent) { - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(getElement(), IInstallableUnit.class); + IInstallableUnit iu = ProvUI.getAdapter(getElement(), IInstallableUnit.class); if (iu == null) { Label label = new Label(parent, SWT.DEFAULT); label.setText(ProvAdminUIMessages.No_Property_Item_Selected); diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUProfilePropertiesGroup.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUProfilePropertiesGroup.java index e71fd366e..468b5ed93 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUProfilePropertiesGroup.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUProfilePropertiesGroup.java @@ -11,19 +11,14 @@ package org.eclipse.equinox.internal.p2.ui.admin.dialogs; import org.eclipse.equinox.internal.p2.ui.admin.ProvAdminUIMessages; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.model.InstalledIUElement; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.osgi.util.NLS; +import org.eclipse.equinox.internal.p2.ui.model.InstalledIUElement; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; -import org.eclipse.ui.statushandlers.StatusManager; /** * An IUPropertiesGroup is a reusable UI component that displays and edits the @@ -68,7 +63,7 @@ public class IUProfilePropertiesGroup extends IUGroup { if (iuElement == null || !(iuElement instanceof InstalledIUElement)) { return; } - String[] propNames = new String[] {IInstallableUnit.PROP_PROFILE_ROOT_IU}; + String[] propNames = new String[] {IProfile.PROP_PROFILE_ROOT_IU}; String[] userPropNames = new String[] {ProvAdminUIMessages.ProfileRootPropertyName}; for (int i = 0; i < propNames.length; i++) { TableItem item = new TableItem(propertiesTable, SWT.NULL); @@ -80,11 +75,6 @@ public class IUProfilePropertiesGroup extends IUGroup { } private IProfile getProfile(InstalledIUElement element) { - try { - return ProvisioningUtil.getProfile(element.getProfileId()); - } catch (ProvisionException e) { - ProvUI.handleException(e, NLS.bind(ProvAdminUIMessages.IUProfilePropertiesGroup_InvalidProfileID, element.getProfileId()), StatusManager.LOG); - return null; - } + return ProvisioningUI.getDefaultUI().getSession().getProfileRegistry().getProfile(element.getProfileId()); } } diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUPropertiesGroup.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUPropertiesGroup.java index 6c766444b..ac7b80810 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUPropertiesGroup.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/IUPropertiesGroup.java @@ -12,8 +12,7 @@ package org.eclipse.equinox.internal.p2.ui.admin.dialogs; import org.eclipse.equinox.internal.p2.ui.admin.ProvAdminUIMessages; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.IUPropertyUtils; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; @@ -67,7 +66,7 @@ public class IUPropertiesGroup extends IUGroup { String[] userPropNames = new String[] {ProvAdminUIMessages.IUPropertiesGroup_NamePropertyLabel, ProvAdminUIMessages.IUPropertiesGroup_DescriptionPropertyLabel, ProvAdminUIMessages.IUPropertiesGroup_ProviderPropertyLabel}; for (int i = 0; i < propNames.length; i++) { TableItem item = new TableItem(propertiesTable, SWT.NULL); - String value = IUPropertyUtils.getIUProperty(getIU(), propNames[i]); + String value = getIU().getProperty(propNames[i], null); if (value != null) item.setText(new String[] {userPropNames[i], value}); } diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/InstalledIUPropertyPage.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/InstalledIUPropertyPage.java index f9aa001be..7694a0138 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/InstalledIUPropertyPage.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/InstalledIUPropertyPage.java @@ -11,7 +11,7 @@ package org.eclipse.equinox.internal.p2.ui.admin.dialogs; import org.eclipse.equinox.internal.p2.ui.admin.ProvAdminUIMessages; -import org.eclipse.equinox.internal.provisional.p2.ui.model.InstalledIUElement; +import org.eclipse.equinox.internal.p2.ui.model.InstalledIUElement; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/ProfileGroup.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/ProfileGroup.java index b67f72f14..07f546092 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/ProfileGroup.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/ProfileGroup.java @@ -16,10 +16,8 @@ import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; -import org.eclipse.equinox.internal.p2.ui.admin.ProvAdminUIActivator; -import org.eclipse.equinox.internal.p2.ui.admin.ProvAdminUIMessages; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.ui.ProfileFactory; +import org.eclipse.equinox.internal.p2.ui.admin.*; +import org.eclipse.equinox.p2.engine.IProfile; import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.GridData; @@ -42,7 +40,6 @@ public class ProfileGroup { Text cache; Text name; Text description; - Text flavor; Text environments; Text nl; IProfile profile; @@ -122,9 +119,6 @@ public class ProfileGroup { label = new Label(composite, SWT.NONE); label.setText(ProvAdminUIMessages.ProfileGroup_Flavor); - flavor = new Text(composite, SWT.BORDER); - flavor.setLayoutData(gd); - setEditable(flavor, profile == null, listener); label = new Label(composite, SWT.NONE); label.setText(ProvAdminUIMessages.ProfileGroup_Environments); @@ -146,7 +140,6 @@ public class ProfileGroup { location.setText(ProfileFactory.getDefaultLocation()); environments.setText(ProfileFactory.getDefaultEnvironments()); nl.setText(ProfileFactory.getDefaultNL()); - flavor.setText(ProfileFactory.getDefaultFlavor()); } else { String value = profile.getProfileId(); // Should not happen, profiles must have an id, but just in case. @@ -172,8 +165,6 @@ public class ProfileGroup { if (value != null) { description.setText(value); } - value = profile.getProperty(IProfile.PROP_FLAVOR); - flavor.setText(value != null ? value : ProfileFactory.getDefaultFlavor()); value = profile.getProperty(IProfile.PROP_ENVIRONMENTS); if (value != null) { @@ -186,9 +177,9 @@ public class ProfileGroup { } } - public Map getProfileProperties() { + public Map getProfileProperties() { if (profile == null) { - Map profileProperties = new HashMap(); + Map profileProperties = new HashMap(); String value = location.getText().trim(); if (value.length() > 0) { @@ -207,10 +198,6 @@ public class ProfileGroup { if (value.length() > 0) { profileProperties.put(IProfile.PROP_DESCRIPTION, value); } - value = flavor.getText().trim(); - if (value.length() > 0) { - profileProperties.put(IProfile.PROP_FLAVOR, value); - } value = environments.getText().trim(); if (value.length() > 0) { profileProperties.put(IProfile.PROP_ENVIRONMENTS, value); diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/ProfilePropertyPage.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/ProfilePropertyPage.java index 374a7f01b..cea15ad83 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/ProfilePropertyPage.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/ProfilePropertyPage.java @@ -10,9 +10,9 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.admin.dialogs; +import org.eclipse.equinox.internal.p2.ui.ProvUI; import org.eclipse.equinox.internal.p2.ui.admin.ProvAdminUIMessages; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; +import org.eclipse.equinox.p2.engine.IProfile; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.*; @@ -28,7 +28,7 @@ public class ProfilePropertyPage extends PropertyPage { private ProfileGroup profileGroup; protected Control createContents(Composite parent) { - IProfile profile = (IProfile) ProvUI.getAdapter(getElement(), IProfile.class); + IProfile profile = ProvUI.getAdapter(getElement(), IProfile.class); if (profile == null) { Label label = new Label(parent, SWT.DEFAULT); label.setText(ProvAdminUIMessages.No_Property_Item_Selected); diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/RepositoryImplementationPropertyPage.java b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/RepositoryImplementationPropertyPage.java index 8cd83d6a1..7c28fc184 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/RepositoryImplementationPropertyPage.java +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/dialogs/RepositoryImplementationPropertyPage.java @@ -10,12 +10,11 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.admin.dialogs; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; - import java.util.Map; +import org.eclipse.equinox.internal.p2.ui.ProvUI; import org.eclipse.equinox.internal.p2.ui.admin.ProvAdminUIMessages; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IRepositoryElement; +import org.eclipse.equinox.internal.p2.ui.model.IRepositoryElement; +import org.eclipse.equinox.p2.repository.IRepository; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; @@ -28,7 +27,7 @@ import org.eclipse.ui.dialogs.PropertyPage; * @since 3.4 */ public class RepositoryImplementationPropertyPage extends PropertyPage { - private IRepositoryElement repositoryElement; + private IRepositoryElement repositoryElement; private Composite composite; private Text name; private Text location; @@ -106,9 +105,9 @@ public class RepositoryImplementationPropertyPage extends PropertyPage { } private void initializeFields() { - IRepositoryElement element = getRepositoryElement(); + IRepositoryElement element = getRepositoryElement(); if (element != null) { - IRepository repo = getRepositoryElement().getRepository(null); + IRepository repo = getRepositoryElement().getRepository(null); location.setText(repo.getLocation().toString()); String value = repo.getName(); if (value != null) @@ -127,9 +126,9 @@ public class RepositoryImplementationPropertyPage extends PropertyPage { private void initializeTable() { if (getRepositoryElement() != null) { - Map repoProperties = getRepositoryElement().getRepository(null).getProperties(); + Map repoProperties = getRepositoryElement().getRepository(null).getProperties(); if (repoProperties != null) { - String[] propNames = (String[]) repoProperties.keySet().toArray(new String[repoProperties.size()]); + String[] propNames = repoProperties.keySet().toArray(new String[repoProperties.size()]); for (int i = 0; i < propNames.length; i++) { TableItem item = new TableItem(propertiesTable, SWT.NULL); item.setText(new String[] {propNames[i], repoProperties.get(propNames[i]).toString()}); @@ -138,9 +137,9 @@ public class RepositoryImplementationPropertyPage extends PropertyPage { } } - private IRepositoryElement getRepositoryElement() { + private IRepositoryElement getRepositoryElement() { if (repositoryElement == null) { - repositoryElement = (IRepositoryElement) ProvUI.getAdapter(getElement(), IRepositoryElement.class); + repositoryElement = ProvUI.getAdapter(getElement(), IRepositoryElement.class); } return repositoryElement; } diff --git a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/messages.properties b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/messages.properties index b5f968204..a818c8b06 100644 --- a/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/messages.properties +++ b/bundles/org.eclipse.equinox.p2.ui.admin/src/org/eclipse/equinox/internal/p2/ui/admin/messages.properties @@ -17,24 +17,16 @@ ProvisioningPrefPage_UseCategories=Show IUs by &category in repository views InstalledIUPropertyPage_NoInfoAvailable=No profile-specific properties are available. AddProfileDialog_Title=Add Profile AddProfileDialog_OperationLabel=Add Profile -AddMetadataRepositoryDialog_OperationLabel=Add Metadata Repository -AddArtifactRepositoryDialog_DuplicateURL=Duplicate URL -AddArtifactRepositoryDialog_ManipulateRepositoryInstruction=You can add and remove artifact repositories in the Artifact Repositories view. -AddArtifactRepositoryDialog_OperationLabel=Add Artifact Repository MetadataRepositoriesView_AddRepositoryLabel=Add repository... MetadataRepositoriesView_AddRepositoryTooltip=Add a new metadata repository RepositoriesView_RemoveCommandLabel=Remove MetadataRepositoriesView_RemoveRepositoryTooltip=Remove the selected metadata repositories -MetadataRepositoriesView_ChooseProfileDialogTitle=Choose Profile -ArtifactRepositoriesView_RemoveRepositoryOperationLabel=Remove Artifact Repositories ArtifactRepositoriesView_AddRepositoryLabel=Add repository... ArtifactRepositoriesView_AddRepositoryTooltip=Add a new artifact repository ArtifactRepositoriesView_RemoveRepositoryTooltip=Remove the selected artifact repositories -ProfilesView_ErrorRetrievingProfiles=Error retrieving profiles ProfilesView_AddProfileTooltip=Add a new profile ProvView_RefreshCommandTooltip=Refresh the items in the view. ProfilesView_AddProfileLabel=Add profile... -ProvView_RefreshCommandLabel=Refresh ProfilesView_RemoveProfileLabel=Remove ProfilesView_RemoveProfileTooltip=Remove the selected profiles AddProfileDialog_DuplicateProfileID=The profile ID is already in use. @@ -57,7 +49,6 @@ IUGroup_TouchpointData=Touchpoint &data: IUGroup_RequiredCapabilities=&Required capabilities: IUGroup_ProvidedCapabilities=&Provided capabilities: IUGroup_IU_ID_Required=Must set an IU ID -IUProfilePropertiesGroup_InvalidProfileID=Profile id {0} not valid. IUPropertiesGroup_DescriptionPropertyLabel=Description IUPropertiesGroup_NamePropertyLabel=Name IUPropertiesGroup_ProviderPropertyLabel=Provider diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/META-INF/MANIFEST.MF index 2dc1c32c2..d577f0222 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/META-INF/MANIFEST.MF @@ -8,21 +8,24 @@ Bundle-Version: 1.0.0.qualifier Bundle-Activator: org.eclipse.equinox.internal.p2.ui.sdk.scheduler.AutomaticUpdatePlugin Import-Package: com.ibm.icu.util;version="4.0.1", org.eclipse.equinox.internal.p2.core.helpers, + org.eclipse.equinox.internal.p2.engine, + org.eclipse.equinox.internal.p2.engine.phases, + org.eclipse.equinox.internal.p2.metadata.query, + org.eclipse.equinox.internal.p2.ui.actions, org.eclipse.equinox.internal.p2.ui.query, org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.core.eventbus, org.eclipse.equinox.internal.provisional.p2.director, - org.eclipse.equinox.internal.provisional.p2.engine, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, org.eclipse.equinox.internal.provisional.p2.repository, - org.eclipse.equinox.internal.provisional.p2.ui, - org.eclipse.equinox.internal.provisional.p2.ui.actions, - org.eclipse.equinox.internal.provisional.p2.ui.model, - org.eclipse.equinox.internal.provisional.p2.ui.operations, - org.eclipse.equinox.internal.provisional.p2.ui.policy, org.eclipse.equinox.internal.provisional.p2.updatechecker, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.operations, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.ui, org.eclipse.osgi.service.resolver;version="1.1.0", org.eclipse.osgi.util;version="1.1.0", org.osgi.framework;version="1.3.0", diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/build.properties b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/build.properties index 84a2da1e9..479f2f7a7 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/build.properties +++ b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/build.properties @@ -9,6 +9,7 @@ # IBM Corporation - initial API and implementation ############################################################################### bin.includes = plugin.properties,\ + icons/,\ .,\ about.html,\ META-INF/,\ diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/close.gif b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/close.gif new file mode 100644 index 000000000..1aca259db Binary files /dev/null and b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/close.gif differ diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/close_hot.gif b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/close_hot.gif new file mode 100644 index 000000000..d5360165c Binary files /dev/null and b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/close_hot.gif differ diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/update.gif b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/update.gif new file mode 100644 index 000000000..aa84ebeaa Binary files /dev/null and b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/update.gif differ diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/update_problems.gif b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/update_problems.gif new file mode 100644 index 000000000..c0cfaca34 Binary files /dev/null and b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/icons/tool/update_problems.gif differ diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdateAction.java b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdateAction.java deleted file mode 100644 index 82e31f760..000000000 --- a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdateAction.java +++ /dev/null @@ -1,157 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.ui.sdk.scheduler; - -import java.util.ArrayList; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIProvisioningListener; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.UpdateAction; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.PlanValidator; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.window.Window; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.PlatformUI; - -/** - * Overridden to hide the resolution from the user and optionally suppress - * the wizard if we are resolving for reasons other than user request. - * - * @since 3.5 - * - */ -final class AutomaticUpdateAction extends UpdateAction { - - /** - * - */ - final AutomaticUpdater automaticUpdater; - private boolean suppressWizard = false; - private PlannerResolutionOperation resolvedOperation; - private ProvUIProvisioningListener profileListener; - private boolean alreadyOpen = false; - - AutomaticUpdateAction(AutomaticUpdater automaticUpdater, - ISelectionProvider selectionProvider, String profileId, - PlannerResolutionOperation op, IUElementListRoot root, - ArrayList initialSelections) { - super(new Policy(), selectionProvider, profileId, false); - ProvUI.addProvisioningListener(createProfileListener()); - this.resolvedOperation = op; - this.automaticUpdater = automaticUpdater; - this.root = root; - this.initialSelections = initialSelections; - } - - private ProvUIProvisioningListener createProfileListener() { - profileListener = new ProvUIProvisioningListener( - ProvUIProvisioningListener.PROV_EVENT_PROFILE) { - protected void profileChanged(final String profileId) { - String id = getProfileId(false); - if (id == IProfileRegistry.SELF) { - try { - IProfile profile = ProvisioningUtil.getProfile(IProfileRegistry.SELF); - id = profile.getProfileId(); - } catch (ProvisionException e) { - id = null; - } - } - if (profileId.equals(id)) { - resolvedOperation = null; - automaticUpdater.validateUpdates(); - } - } - }; - return profileListener; - } - - protected void run(final IInstallableUnit[] ius, final String id) { - // Do we have a plan?? - if (resolvedOperation != null - && resolvedOperation.getProvisioningPlan() != null) { - if (PlatformUI.isWorkbenchRunning()) { - PlatformUI.getWorkbench().getDisplay().asyncExec( - new Runnable() { - public void run() { - if (validatePlan(resolvedOperation - .getProvisioningPlan())) { - performAction(ius, id, resolvedOperation); - } - } - }); - } - } else - super.run(ius, id); - } - - void suppressWizard(boolean suppress) { - suppressWizard = suppress; - } - - protected int performAction(IInstallableUnit[] ius, String targetProfileId, - PlannerResolutionOperation resolution) { - if (suppressWizard) { - automaticUpdater.setUpdateAffordanceState(resolution != null - && resolution.getResolutionResult().getSummaryStatus() - .isOK()); - return Window.OK; - } - if (alreadyOpen) - return Window.CANCEL; - alreadyOpen = true; - int retCode = super.performAction(ius, targetProfileId, resolution); - alreadyOpen = false; - return retCode; - } - - protected PlanValidator getPlanValidator() { - return new PlanValidator() { - public boolean continueWorkingWithPlan(ProvisioningPlan plan, - Shell shell) { - if (automaticUpdater.alreadyValidated) - return true; - // In all other cases we return false, because clicking the - // popup will actually run the action. - // We are just determining whether to show the popup or not. - if (plan != null) { - // If the user cancelled the operation, don't continue - if (plan.getStatus().getSeverity() == IStatus.CANCEL) - return false; - boolean noError = plan.getStatus().getSeverity() != IStatus.ERROR; - // Show the affordance regardless of the status since - // updates were found. - if (automaticUpdater.updateAffordance == null) - automaticUpdater.createUpdateAffordance(); - automaticUpdater.setUpdateAffordanceState(noError); - if (noError && automaticUpdater.popup == null) - automaticUpdater.createUpdatePopup(); - } - return false; - } - }; - } - - public void dispose() { - if (profileListener != null) - ProvUI.removeProvisioningListener(profileListener); - profileListener = null; - } -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdateMessages.java b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdateMessages.java index 34a9496b9..18fb531ed 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdateMessages.java +++ b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdateMessages.java @@ -68,8 +68,6 @@ public class AutomaticUpdateMessages extends NLS { public static String AutomaticUpdater_AutomaticDownloadOperationName; public static String AutomaticUpdater_ClickToReviewUpdates; public static String AutomaticUpdater_ClickToReviewUpdatesWithProblems; - public static String AutomaticUpdater_ErrorCheckingUpdates; - public static String AutomaticUpdater_ResolutionOperationLabel; public static String AutomaticUpdatesPreferencePage_UpdateSchedule; public static String AutomaticUpdatesPreferencePage_findOnStart; public static String AutomaticUpdatesPreferencePage_findOnSchedule; diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdatePlugin.java b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdatePlugin.java index 96b2874b0..d7b7abf93 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdatePlugin.java +++ b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdatePlugin.java @@ -11,11 +11,17 @@ package org.eclipse.equinox.internal.p2.ui.sdk.scheduler; import java.io.IOException; +import java.net.URL; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.engine.ProfileScope; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.engine.ProfileScope; +import org.eclipse.equinox.p2.operations.ProvisioningSession; import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.ui.preferences.ScopedPreferenceStore; import org.eclipse.ui.statushandlers.StatusManager; @@ -27,6 +33,15 @@ import org.osgi.service.packageadmin.PackageAdmin; */ public class AutomaticUpdatePlugin extends AbstractUIPlugin { + // bundle-relative icon path + public final static String ICON_PATH = "$nl$/icons/"; //$NON-NLS-1$ + + // tool icons + public final static String IMG_TOOL_UPDATE = "tool/update.gif"; //$NON-NLS-1$ + public final static String IMG_TOOL_UPDATE_PROBLEMS = "tool/update_problems.gif"; //$NON-NLS-1$ + public final static String IMG_TOOL_CLOSE = "tool/close.gif"; //$NON-NLS-1$ + public final static String IMG_TOOL_CLOSE_HOT = "tool/close_hot.gif"; //$NON-NLS-1$ + private static AutomaticUpdatePlugin plugin; private static BundleContext context; private static PackageAdmin packageAdmin = null; @@ -36,6 +51,8 @@ public class AutomaticUpdatePlugin extends AbstractUIPlugin { private AutomaticUpdater updater; private ScopedPreferenceStore preferenceStore; + private ProvisioningSession session; + public static final String PLUGIN_ID = "org.eclipse.equinox.p2.ui.sdk.scheduler"; //$NON-NLS-1$ public static BundleContext getContext() { @@ -89,10 +106,11 @@ public class AutomaticUpdatePlugin extends AbstractUIPlugin { // Application launch config won't let me specify bundles to start. // TODO how should we react if we are unable to start one of these bundles? startEarly("org.eclipse.equinox.p2.exemplarysetup"); //$NON-NLS-1$ - startEarly("org.eclipse.equinox.frameworkadmin.equinox"); //$NON-NLS-1$ - startEarly("org.eclipse.equinox.simpleconfigurator.manipulator"); //$NON-NLS-1$ startEarly("org.eclipse.equinox.p2.updatechecker"); //$NON-NLS-1$ + IProvisioningAgent agent = (IProvisioningAgent) ServiceHelper.getService(getContext(), IProvisioningAgent.class.getName()); + session = new ProvisioningSession(agent); + PreferenceInitializer.migratePreferences(); } @@ -162,7 +180,27 @@ public class AutomaticUpdatePlugin extends AbstractUIPlugin { try { preferenceStore.save(); } catch (IOException e) { - ProvUI.handleException(e, AutomaticUpdateMessages.ErrorSavingPreferences, StatusManager.LOG | StatusManager.SHOW); + StatusManager.getManager().handle(new Status(IStatus.ERROR, AutomaticUpdatePlugin.PLUGIN_ID, 0, AutomaticUpdateMessages.ErrorSavingPreferences, e), StatusManager.LOG | StatusManager.SHOW); } } + + protected void initializeImageRegistry(ImageRegistry reg) { + createImageDescriptor(IMG_TOOL_UPDATE, reg); + createImageDescriptor(IMG_TOOL_UPDATE_PROBLEMS, reg); + createImageDescriptor(IMG_TOOL_CLOSE, reg); + createImageDescriptor(IMG_TOOL_CLOSE_HOT, reg); + } + + /** + * Creates the specified image descriptor and registers it + */ + private void createImageDescriptor(String id, ImageRegistry reg) { + URL url = FileLocator.find(getBundle(), new Path(ICON_PATH + id), null); + ImageDescriptor desc = ImageDescriptor.createFromURL(url); + reg.put(id, desc); + } + + public ProvisioningSession getSession() { + return session; + } } diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdateScheduler.java b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdateScheduler.java index c19f4d964..855d9b00e 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdateScheduler.java +++ b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdateScheduler.java @@ -10,17 +10,16 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.sdk.scheduler; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; - import com.ibm.icu.util.Calendar; import com.ibm.icu.util.ULocale; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IUPropertyQuery; +import org.eclipse.equinox.internal.p2.metadata.query.IUPropertyQuery; import org.eclipse.equinox.internal.provisional.p2.updatechecker.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQuery; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.IStartup; import org.eclipse.ui.statushandlers.StatusManager; @@ -88,7 +87,7 @@ public class AutomaticUpdateScheduler implements IStartup { private IProfile getProfile() { if (cachedProfile == null) { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(AutomaticUpdatePlugin.getContext(), IProfileRegistry.class.getName()); + IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(AutomaticUpdatePlugin.getContext(), IProfileRegistry.SERVICE_NAME); if (profileRegistry != null) cachedProfile = profileRegistry.getProfile(profileId); } @@ -166,10 +165,10 @@ public class AutomaticUpdateScheduler implements IStartup { } - private Query getProfileQuery() { - // We specifically avoid going through the default policy's query provider or - // through the sdk ui bundle, so that we don't load all the p2 UI classes in doing so. - return new IUProfilePropertyByIdQuery(IInstallableUnit.PROP_PROFILE_ROOT_IU, Boolean.toString(true)); + private IQuery getProfileQuery() { + // We specifically avoid using the default policy's root property so that we don't load all the + // p2 UI classes in doing so. + return new IUProfilePropertyByIdQuery(IProfile.PROP_PROFILE_ROOT_IU, Boolean.toString(true)); } private int getDay(IPreferenceStore pref) { diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdater.java b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdater.java index 72f167b38..de1e4d39c 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdater.java +++ b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdater.java @@ -13,49 +13,21 @@ package org.eclipse.equinox.internal.p2.ui.sdk.scheduler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.IJobChangeEvent; -import org.eclipse.core.runtime.jobs.IJobChangeListener; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.core.runtime.jobs.JobChangeAdapter; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.UpdateWizard; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.DownloadPhaseSet; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProfileModificationOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; +import java.util.EventObject; +import org.eclipse.core.runtime.*; +import org.eclipse.core.runtime.jobs.*; +import org.eclipse.equinox.internal.provisional.p2.core.eventbus.ProvisioningListener; import org.eclipse.equinox.internal.provisional.p2.updatechecker.IUpdateListener; import org.eclipse.equinox.internal.provisional.p2.updatechecker.UpdateEvent; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.*; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Listener; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IEditorSite; -import org.eclipse.ui.IViewSite; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPartSite; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PlatformUI; +import org.eclipse.swt.widgets.*; +import org.eclipse.ui.*; import org.eclipse.ui.statushandlers.StatusManager; /** @@ -64,16 +36,43 @@ import org.eclipse.ui.statushandlers.StatusManager; public class AutomaticUpdater implements IUpdateListener { StatusLineCLabelContribution updateAffordance; - AutomaticUpdateAction updateAction; IStatusLineManager statusLineManager; IInstallableUnit[] iusWithUpdates; String profileId; + ProvisioningListener profileListener; AutomaticUpdatesPopup popup; - IJobChangeListener provisioningJobListener; - boolean alreadyValidated = false; boolean alreadyDownloaded = false; + UpdateOperation operation; private static final String AUTO_UPDATE_STATUS_ITEM = "AutoUpdatesStatus"; //$NON-NLS-1$ + public AutomaticUpdater() { + createProfileListener(); + } + + private void createProfileListener() { + profileListener = new ProvisioningListener() { + public void notify(EventObject o) { + if (o instanceof ProfileEvent) { + ProfileEvent event = (ProfileEvent) o; + if (event.getReason() == ProfileEvent.CHANGED && sameProfile(event.getProfileId())) { + triggerNewUpdateNotification(); + } + } + } + }; + getProvisioningUI().getSession().getProvisioningEventBus().addListener(profileListener); + } + + private boolean sameProfile(String another) { + if (another.equals(IProfileRegistry.SELF)) { + another = getSession().getProfileRegistry().getProfile(another).getProfileId(); + } + if (profileId.equals(IProfileRegistry.SELF)) { + profileId = getSession().getProfileRegistry().getProfile(profileId).getProfileId(); + } + return profileId.equals(another); + } + /* * (non-Javadoc) * @@ -84,155 +83,108 @@ public class AutomaticUpdater implements IUpdateListener { * .UpdateEvent) */ public void updatesAvailable(final UpdateEvent event) { - final boolean download = getPreferenceStore().getBoolean( - PreferenceConstants.PREF_DOWNLOAD_ONLY); + final boolean download = getPreferenceStore().getBoolean(PreferenceConstants.PREF_DOWNLOAD_ONLY); profileId = event.getProfileId(); iusWithUpdates = event.getIUs(); - validateUpdates(null, true); + validateIusToUpdate(); alreadyDownloaded = false; - if (iusWithUpdates.length <= 0) { + // Create an update operation to reflect the new updates that are available. + operation = new UpdateOperation(getSession(), iusWithUpdates); + operation.setProfileId(event.getProfileId()); + // operation.setRootMarkerKey(IProfile.PROP_PROFILE_ROOT_IU); + IStatus status = operation.resolveModal(new NullProgressMonitor()); + + if (!status.isOK() || operation.getPossibleUpdates() == null || operation.getPossibleUpdates().length == 0) { clearUpdatesAvailable(); return; } - registerProvisioningJobListener(); - - // Always get a profile change request and provisioning plan. - // A side-effect of making the change request is producing the model - // elements necessary for a wizard, so initialize the data structures - // for getting these. - final ArrayList initialSelections = new ArrayList(); - final IUElementListRoot root = new IUElementListRoot(); - try { - ProfileChangeRequest request = UpdateWizard - .createProfileChangeRequest(event.getIUs(), event - .getProfileId(), root, initialSelections, null); - if (request == null) { - clearUpdatesAvailable(); - return; - } - final PlannerResolutionOperation operation = new PlannerResolutionOperation( - AutomaticUpdateMessages.AutomaticUpdater_ResolutionOperationLabel, - event.getProfileId(), request, null, new MultiStatus( - AutomaticUpdatePlugin.PLUGIN_ID, 0, null, null), - false); - if ((operation.execute(new NullProgressMonitor())).isOK()) { - // Download the items before notifying user if the - // preference dictates. - - if (download) { - Job job = ProvisioningOperationRunner - .schedule( - new ProfileModificationOperation( - AutomaticUpdateMessages.AutomaticUpdater_AutomaticDownloadOperationName, - event.getProfileId(), operation - .getProvisioningPlan(), - new ProvisioningContext(), - new DownloadPhaseSet(), false), - StatusManager.LOG); - job.addJobChangeListener(new JobChangeAdapter() { - public void done(IJobChangeEvent jobEvent) { - alreadyDownloaded = true; - IStatus status = jobEvent.getResult(); - if (status.isOK()) { - createUpdateAction(operation, root, - initialSelections); - PlatformUI.getWorkbench().getDisplay() - .asyncExec(new Runnable() { - public void run() { - updateAction - .suppressWizard(true); - updateAction.run(); - } - }); - } else if (status.getSeverity() != IStatus.CANCEL) { - ProvUI.reportStatus(status, StatusManager.LOG); + // Download the items before notifying user if the + // preference dictates. + + if (download) { + ProfileModificationJob job = new ProfileModificationJob(AutomaticUpdateMessages.AutomaticUpdater_AutomaticDownloadOperationName, getSession(), event.getProfileId(), operation.getProvisioningPlan(), new ProvisioningContext()); + job.setPhaseSet(new DownloadPhaseSet()); + job.setUser(false); + job.setSystem(true); + job.addJobChangeListener(new JobChangeAdapter() { + public void done(IJobChangeEvent jobEvent) { + IStatus jobStatus = jobEvent.getResult(); + if (jobStatus.isOK()) { + alreadyDownloaded = true; + PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { + public void run() { + setUpdateAffordanceState(operation.getResolutionResult().isOK()); } - } - }); - } else { - createUpdateAction(operation, root, initialSelections); - PlatformUI.getWorkbench().getDisplay().asyncExec( - new Runnable() { - public void run() { - updateAction.suppressWizard(true); - updateAction.run(); - } - }); + }); + } else if (jobStatus.getSeverity() != IStatus.CANCEL) { + StatusManager.getManager().handle(jobStatus, StatusManager.LOG); + } } - } - } catch (ProvisionException e) { - ProvUI - .handleException( - e, - AutomaticUpdateMessages.AutomaticUpdater_ErrorCheckingUpdates, - StatusManager.LOG); + }); + job.schedule(); + } else { + PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { + public void run() { + setUpdateAffordanceState(operation.getResolutionResult().isOK()); + } + }); } } + ProvisioningSession getSession() { + return AutomaticUpdatePlugin.getDefault().getSession(); + } + + /* + * Use with caution, as this still start the whole UI bundle. Shouldn't be used + * in any of the update checking code, only the code that presents updates when notified. + */ + ProvisioningUI getProvisioningUI() { + return ProvisioningUI.getDefaultUI(); + } + /* - * Validate that iusToBeUpdated is valid, and reset the cache. If - * isKnownToBeAvailable is false, then recheck that the update is available. - * isKnownToBeAvailable should be false when the update list might be stale - * (Reminding the user of updates may happen long after the update check. - * This reduces the risk of notifying the user of updates and then not - * finding them .) + * Filter out the ius that aren't visible to the user or are + * locked for updating. */ - void validateUpdates(IProgressMonitor monitor, boolean isKnownToBeAvailable) { + void validateIusToUpdate() { ArrayList list = new ArrayList(); + IProfile profile = getSession().getProfileRegistry().getProfile(profileId); + for (int i = 0; i < iusWithUpdates.length; i++) { try { - if (isKnownToBeAvailable - || ProvisioningUtil.getPlanner().updatesFor( - iusWithUpdates[i], new ProvisioningContext(), - monitor).length > 0) { - if (validToUpdate(iusWithUpdates[i])) - list.add(iusWithUpdates[i]); - } - } catch (ProvisionException e) { - ProvUI - .handleException( - e, - AutomaticUpdateMessages.AutomaticUpdater_ErrorCheckingUpdates, - StatusManager.LOG); - continue; + if (validToUpdate(profile, iusWithUpdates[i])) + list.add(iusWithUpdates[i]); } catch (OperationCanceledException e) { // Nothing to report } } - iusWithUpdates = (IInstallableUnit[]) list - .toArray(new IInstallableUnit[list.size()]); + iusWithUpdates = (IInstallableUnit[]) list.toArray(new IInstallableUnit[list.size()]); } // A proposed update is valid if it is still visible to the user as an // installed item (it is a root) // and if it is not locked for updating. - private boolean validToUpdate(IInstallableUnit iu) { - int lock = IInstallableUnit.LOCK_NONE; + private boolean validToUpdate(IProfile profile, IInstallableUnit iu) { + int lock = IProfile.LOCK_NONE; boolean isRoot = false; try { - IProfile profile = ProvisioningUtil.getProfile(profileId); - String value = profile.getInstallableUnitProperty(iu, - IInstallableUnit.PROP_PROFILE_LOCKED_IU); + String value = profile.getInstallableUnitProperty(iu, IProfile.PROP_PROFILE_LOCKED_IU); if (value != null) lock = Integer.parseInt(value); - value = profile.getInstallableUnitProperty(iu, - IInstallableUnit.PROP_PROFILE_ROOT_IU); - isRoot = value == null ? false : Boolean.valueOf(value) - .booleanValue(); - } catch (ProvisionException e) { - // ignore + value = profile.getInstallableUnitProperty(iu, IProfile.PROP_PROFILE_ROOT_IU); + isRoot = value == null ? false : Boolean.valueOf(value).booleanValue(); } catch (NumberFormatException e) { // ignore and assume no lock } - return isRoot && (lock & IInstallableUnit.LOCK_UPDATE) == 0; + return isRoot && (lock & IProfile.LOCK_UPDATE) == 0; } Shell getWorkbenchWindowShell() { - IWorkbenchWindow activeWindow = PlatformUI.getWorkbench() - .getActiveWorkbenchWindow(); + IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); return activeWindow != null ? activeWindow.getShell() : null; } @@ -240,16 +192,14 @@ public class AutomaticUpdater implements IUpdateListener { IStatusLineManager getStatusLineManager() { if (statusLineManager != null) return statusLineManager; - IWorkbenchWindow activeWindow = PlatformUI.getWorkbench() - .getActiveWorkbenchWindow(); + IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (activeWindow == null) return null; // YUCK! YUCK! YUCK! // IWorkbenchWindow does not define getStatusLineManager(), yet // WorkbenchWindow does try { - Method method = activeWindow.getClass().getDeclaredMethod( - "getStatusLineManager", new Class[0]); //$NON-NLS-1$ + Method method = activeWindow.getClass().getDeclaredMethod("getStatusLineManager", new Class[0]); //$NON-NLS-1$ try { Object statusLine = method.invoke(activeWindow, new Object[0]); if (statusLine instanceof IStatusLineManager) { @@ -265,14 +215,11 @@ public class AutomaticUpdater implements IUpdateListener { // can't blame us for trying. } - IWorkbenchPartSite site = activeWindow.getActivePage().getActivePart() - .getSite(); + IWorkbenchPartSite site = activeWindow.getActivePage().getActivePart().getSite(); if (site instanceof IViewSite) { - statusLineManager = ((IViewSite) site).getActionBars() - .getStatusLineManager(); + statusLineManager = ((IViewSite) site).getActionBars().getStatusLineManager(); } else if (site instanceof IEditorSite) { - statusLineManager = ((IEditorSite) site).getActionBars() - .getStatusLineManager(); + statusLineManager = ((IEditorSite) site).getActionBars().getStatusLineManager(); } return statusLineManager; } @@ -284,8 +231,7 @@ public class AutomaticUpdater implements IUpdateListener { } void createUpdateAffordance() { - updateAffordance = new StatusLineCLabelContribution( - AUTO_UPDATE_STATUS_ITEM, 5); + updateAffordance = new StatusLineCLabelContribution(AUTO_UPDATE_STATUS_ITEM, 5); updateAffordance.addListener(SWT.MouseDown, new Listener() { public void handleEvent(Event event) { launchUpdate(); @@ -302,15 +248,11 @@ public class AutomaticUpdater implements IUpdateListener { if (updateAffordance == null) return; if (isValid) { - updateAffordance - .setTooltip(AutomaticUpdateMessages.AutomaticUpdater_ClickToReviewUpdates); - updateAffordance.setImage(ProvUIImages - .getImage(ProvUIImages.IMG_TOOL_UPDATE)); + updateAffordance.setTooltip(AutomaticUpdateMessages.AutomaticUpdater_ClickToReviewUpdates); + updateAffordance.setImage(AutomaticUpdatePlugin.getDefault().getImageRegistry().get((AutomaticUpdatePlugin.IMG_TOOL_UPDATE))); } else { - updateAffordance - .setTooltip(AutomaticUpdateMessages.AutomaticUpdater_ClickToReviewUpdatesWithProblems); - updateAffordance.setImage(ProvUIImages - .getImage(ProvUIImages.IMG_TOOL_UPDATE_PROBLEMS)); + updateAffordance.setTooltip(AutomaticUpdateMessages.AutomaticUpdater_ClickToReviewUpdatesWithProblems); + updateAffordance.setImage(AutomaticUpdatePlugin.getDefault().getImageRegistry().get((AutomaticUpdatePlugin.IMG_TOOL_UPDATE_PROBLEMS))); } IStatusLineManager manager = getStatusLineManager(); if (manager != null) { @@ -323,8 +265,7 @@ public class AutomaticUpdater implements IUpdateListener { // so we hide it if it should not be enabled. if (updateAffordance == null) return; - boolean shouldBeVisible = !ProvisioningOperationRunner - .hasScheduledOperations(); + boolean shouldBeVisible = getProvisioningUI().hasScheduledOperations(); if (updateAffordance.isVisible() != shouldBeVisible) { IStatusLineManager manager = getStatusLineManager(); if (manager != null) { @@ -335,21 +276,11 @@ public class AutomaticUpdater implements IUpdateListener { } void createUpdatePopup() { - popup = new AutomaticUpdatesPopup(getWorkbenchWindowShell(), - alreadyDownloaded, getPreferenceStore()); + popup = new AutomaticUpdatesPopup(getWorkbenchWindowShell(), alreadyDownloaded, getPreferenceStore()); popup.open(); } - void createUpdateAction(PlannerResolutionOperation operation, - IUElementListRoot root, ArrayList initialSelections) { - if (updateAction != null) { - updateAction.dispose(); - } - updateAction = new AutomaticUpdateAction(this, getSelectionProvider(), - profileId, operation, root, initialSelections); - } - void clearUpdatesAvailable() { if (updateAffordance != null) { IStatusLineManager manager = getStatusLineManager(); @@ -364,97 +295,10 @@ public class AutomaticUpdater implements IUpdateListener { popup.close(false); popup = null; } - alreadyValidated = false; - } - - ISelectionProvider getSelectionProvider() { - return new ISelectionProvider() { - - /* - * (non-Javadoc) - * - * @seeorg.eclipse.jface.viewers.ISelectionProvider# - * addSelectionChangedListener - * (org.eclipse.jface.viewers.ISelectionChangedListener) - */ - public void addSelectionChangedListener( - ISelectionChangedListener listener) { - // Ignore because the selection won't change - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.ISelectionProvider#getSelection() - */ - public ISelection getSelection() { - return new StructuredSelection(iusWithUpdates); - } - - /* - * (non-Javadoc) - * - * @seeorg.eclipse.jface.viewers.ISelectionProvider# - * removeSelectionChangedListener - * (org.eclipse.jface.viewers.ISelectionChangedListener) - */ - public void removeSelectionChangedListener( - ISelectionChangedListener listener) { - // ignore because the selection is static - } - - /* - * (non-Javadoc) - * - * @see - * org.eclipse.jface.viewers.ISelectionProvider#setSelection(org - * .eclipse.jface.viewers.ISelection) - */ - public void setSelection(ISelection sel) { - throw new UnsupportedOperationException( - "This ISelectionProvider is static, and cannot be modified."); //$NON-NLS-1$ - } - }; } public void launchUpdate() { - alreadyValidated = true; - updateAction.suppressWizard(false); - updateAction.run(); - } - - private void registerProvisioningJobListener() { - if (provisioningJobListener == null) { - provisioningJobListener = new JobChangeAdapter() { - public void done(IJobChangeEvent event) { - IWorkbench workbench = PlatformUI.getWorkbench(); - if (workbench == null || workbench.isClosing()) - return; - if (workbench.getDisplay() == null) - return; - workbench.getDisplay().asyncExec(new Runnable() { - public void run() { - checkUpdateAffordanceEnablement(); - } - }); - } - - public void scheduled(final IJobChangeEvent event) { - IWorkbench workbench = PlatformUI.getWorkbench(); - if (workbench == null || workbench.isClosing()) - return; - if (workbench.getDisplay() == null) - return; - workbench.getDisplay().asyncExec(new Runnable() { - public void run() { - checkUpdateAffordanceEnablement(); - } - }); - } - }; - ProvisioningOperationRunner - .addJobChangeListener(provisioningJobListener); - } + getProvisioningUI().openUpdateWizard(getProvisioningUI().getDefaultParentShell(), true, operation, null); } /* @@ -462,45 +306,29 @@ public class AutomaticUpdater implements IUpdateListener { * if there is nothing to update, get rid of the update popup and * affordance. */ - void validateUpdates() { - Job validateJob = new Job("Update validate job") { //$NON-NLS-1$ + void triggerNewUpdateNotification() { + Job notifyJob = new Job("Update validate job") { //$NON-NLS-1$ public IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) return Status.CANCEL_STATUS; - validateUpdates(monitor, false); - // If there are no more updates, clear the indicators - if (iusWithUpdates.length == 0) { - if (PlatformUI.isWorkbenchRunning()) - PlatformUI.getWorkbench().getDisplay().asyncExec( - new Runnable() { - public void run() { - clearUpdatesAvailable(); - } - }); - } else { - // Run through the same update notification logic as before, - // which will cause a new plan to be created against the - // changed profile. - updatesAvailable(new UpdateEvent(profileId, iusWithUpdates)); - } + // notify that updates are available for all roots. We don't know for sure that + // there are any, but this will cause everything to be rechecked + updatesAvailable(new UpdateEvent(profileId, getSession().getInstalledIUs(profileId, false))); return Status.OK_STATUS; } }; - validateJob.setSystem(true); - validateJob.setPriority(Job.LONG); - validateJob.schedule(); + notifyJob.setSystem(true); + notifyJob.setUser(false); + notifyJob.setPriority(Job.LONG); + notifyJob.schedule(); } public void shutdown() { - if (updateAction != null) - updateAction.dispose(); - if (provisioningJobListener != null) { - ProvisioningOperationRunner - .removeJobChangeListener(provisioningJobListener); - provisioningJobListener = null; - } statusLineManager = null; - updateAction = null; + if (profileListener != null) { + getSession().getProvisioningEventBus().removeListener(profileListener); + profileListener = null; + } } IPreferenceStore getPreferenceStore() { diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdatesPopup.java b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdatesPopup.java index b28826409..af7b27685 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdatesPopup.java +++ b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdatesPopup.java @@ -12,7 +12,6 @@ package org.eclipse.equinox.internal.p2.ui.sdk.scheduler; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.PopupDialog; import org.eclipse.jface.layout.GridDataFactory; @@ -262,8 +261,8 @@ public class AutomaticUpdatesPopup extends PopupDialog { ToolItem closeButton = new ToolItem(toolBar, SWT.PUSH, 0); GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(toolBar); - closeButton.setImage(ProvUIImages.getImage(ProvUIImages.IMG_TOOL_CLOSE)); - closeButton.setHotImage(ProvUIImages.getImage(ProvUIImages.IMG_TOOL_CLOSE_HOT)); + closeButton.setImage(AutomaticUpdatePlugin.getDefault().getImageRegistry().get((AutomaticUpdatePlugin.IMG_TOOL_CLOSE))); + closeButton.setHotImage(AutomaticUpdatePlugin.getDefault().getImageRegistry().get((AutomaticUpdatePlugin.IMG_TOOL_CLOSE_HOT))); closeButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { close(); diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdatesPreferencePage.java b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdatesPreferencePage.java index c7febd33b..55752f2d0 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdatesPreferencePage.java +++ b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdatesPreferencePage.java @@ -18,15 +18,8 @@ import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.ui.PlatformUI; +import org.eclipse.swt.widgets.*; +import org.eclipse.ui.*; /** * Preference page for automated updates. diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/DownloadPhaseSet.java b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/DownloadPhaseSet.java new file mode 100644 index 000000000..07f1b911a --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/DownloadPhaseSet.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +/** + * + */ +package org.eclipse.equinox.internal.p2.ui.sdk.scheduler; + +import org.eclipse.equinox.internal.p2.engine.Phase; +import org.eclipse.equinox.internal.p2.engine.PhaseSet; +import org.eclipse.equinox.internal.p2.engine.phases.Collect; + + +public class DownloadPhaseSet extends PhaseSet { + public DownloadPhaseSet() { + super(new Phase[] {new Collect(10)}); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/PreferenceInitializer.java b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/PreferenceInitializer.java index 1cdbb9da2..d1df0f770 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/PreferenceInitializer.java +++ b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/PreferenceInitializer.java @@ -10,11 +10,10 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.sdk.scheduler; -import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.preferences.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.engine.ProfileScope; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.engine.ProfileScope; import org.eclipse.ui.statushandlers.StatusManager; import org.osgi.service.prefs.BackingStoreException; import org.osgi.service.prefs.Preferences; @@ -44,7 +43,7 @@ public class PreferenceInitializer extends AbstractPreferenceInitializer { pref.flush(); } } catch (BackingStoreException e) { - ProvUI.handleException(e, AutomaticUpdateMessages.ErrorLoadingPreferenceKeys, StatusManager.LOG); + handleException(e, AutomaticUpdateMessages.ErrorLoadingPreferenceKeys); } // Have we migrated from 3.4 pref values? @@ -90,7 +89,7 @@ public class PreferenceInitializer extends AbstractPreferenceInitializer { try { pref.flush(); } catch (BackingStoreException e) { - ProvUI.handleException(e, AutomaticUpdateMessages.ErrorSavingPreferences, StatusManager.LOG); + handleException(e, AutomaticUpdateMessages.ErrorSavingPreferences); } } // pref used to track 3.3 migration @@ -122,11 +121,15 @@ public class PreferenceInitializer extends AbstractPreferenceInitializer { pref.putBoolean(PreferenceConstants.PREF_AUTO_UPDATE_INIT, true); pref.flush(); } catch (BackingStoreException e) { - ProvUI.handleException(e, AutomaticUpdateMessages.ErrorSavingClassicPreferences, StatusManager.LOG); + handleException(e, AutomaticUpdateMessages.ErrorSavingClassicPreferences); } } } + private static void handleException(Exception e, String message) { + StatusManager.getManager().handle(new Status(IStatus.ERROR, AutomaticUpdatePlugin.PLUGIN_ID, 0, message, e), StatusManager.LOG); + } + public void initializeDefaultPreferences() { // initialize the default scope Preferences node = new DefaultScope().getNode(AutomaticUpdatePlugin.PLUGIN_ID); diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/messages.properties b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/messages.properties index ebec0c283..59ea000fa 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/messages.properties +++ b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/messages.properties @@ -54,8 +54,6 @@ AutomaticUpdatesPopup_UpdatesAvailableTitle=Updates Available AutomaticUpdater_AutomaticDownloadOperationName=Automatic updates download AutomaticUpdater_ClickToReviewUpdates=Updates are available. Click here to review and install them. AutomaticUpdater_ClickToReviewUpdatesWithProblems=Updates are available, but there may be some compatibility problems. Click here to review them. -AutomaticUpdater_ErrorCheckingUpdates=Unexpected error while checking the validity of updates. -AutomaticUpdater_ResolutionOperationLabel=Computing Automatic Updates AutomaticUpdatesPreferencePage_UpdateSchedule=&Update schedule AutomaticUpdatesPreferencePage_findOnStart=Look for updates each time &platform is started AutomaticUpdatesPreferencePage_findOnSchedule=Look for updates on the following &schedule: diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.ui.sdk/META-INF/MANIFEST.MF index 0dffe2968..00c46d46e 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.ui.sdk/META-INF/MANIFEST.MF @@ -6,28 +6,26 @@ Bundle-Localization: plugin Bundle-SymbolicName: org.eclipse.equinox.p2.ui.sdk;singleton:=true Bundle-Version: 1.0.100.qualifier Bundle-Activator: org.eclipse.equinox.internal.p2.ui.sdk.ProvSDKUIActivator -Import-Package: org.eclipse.equinox.internal.p2.core.helpers, +Import-Package: javax.xml.parsers, + org.eclipse.equinox.internal.p2.core.helpers, + org.eclipse.equinox.internal.p2.ui.actions, org.eclipse.equinox.internal.p2.ui.query, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.core.eventbus, - org.eclipse.equinox.internal.provisional.p2.repository, org.eclipse.equinox.internal.provisional.p2.director, - org.eclipse.equinox.internal.provisional.p2.engine, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.p2.ui, - org.eclipse.equinox.internal.provisional.p2.ui.actions, - org.eclipse.equinox.internal.provisional.p2.ui.dialogs, - org.eclipse.equinox.internal.provisional.p2.ui.model, - org.eclipse.equinox.internal.provisional.p2.ui.operations, - org.eclipse.equinox.internal.provisional.p2.ui.policy, - org.eclipse.equinox.internal.provisional.p2.ui.viewers, + org.eclipse.equinox.internal.provisional.p2.repository, + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.engine.query, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.operations, org.eclipse.osgi.service.resolver;version="1.1.0", org.eclipse.osgi.util;version="1.1.0", org.osgi.framework;version="1.3.0", - org.osgi.service.packageadmin;version="1.2.0" + org.osgi.service.packageadmin;version="1.2.0", + org.w3c.dom, + org.xml.sax Export-Package: org.eclipse.equinox.internal.p2.ui.sdk;x-internal:=true, org.eclipse.equinox.internal.p2.ui.sdk.prefs;x-internal:=true Require-Bundle: org.eclipse.ui, @@ -36,4 +34,4 @@ Require-Bundle: org.eclipse.ui, Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: J2SE-1.4, CDC-1.1/Foundation-1.1 -Service-Component: OSGI-INF/policy_component.xml, OSGI-INF/serviceui_component.xml +Service-Component: OSGI-INF/policy_component.xml, OSGI-INF/licenseManager_component.xml diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/OSGI-INF/licenseManager_component.xml b/bundles/org.eclipse.equinox.p2.ui.sdk/OSGI-INF/licenseManager_component.xml new file mode 100644 index 000000000..bdaeb067d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui.sdk/OSGI-INF/licenseManager_component.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/OSGI-INF/policy_component.xml b/bundles/org.eclipse.equinox.p2.ui.sdk/OSGI-INF/policy_component.xml index 41869455d..c02500765 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk/OSGI-INF/policy_component.xml +++ b/bundles/org.eclipse.equinox.p2.ui.sdk/OSGI-INF/policy_component.xml @@ -2,6 +2,6 @@ - + diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/OSGI-INF/serviceui_component.xml b/bundles/org.eclipse.equinox.p2.ui.sdk/OSGI-INF/serviceui_component.xml deleted file mode 100644 index 1c361514c..000000000 --- a/bundles/org.eclipse.equinox.p2.ui.sdk/OSGI-INF/serviceui_component.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/plugin.xml b/bundles/org.eclipse.equinox.p2.ui.sdk/plugin.xml index be40b4ead..380c82540 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk/plugin.xml +++ b/bundles/org.eclipse.equinox.p2.ui.sdk/plugin.xml @@ -5,40 +5,7 @@ id="preferences" point="org.eclipse.core.runtime.preferences" name="%preferences"> - - - - - - - - - - - - - - - - - - - - - @@ -143,12 +110,12 @@ point="org.eclipse.ui.installationPages"> diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/InstallNewSoftwareHandler.java b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/InstallNewSoftwareHandler.java index 28c17299c..20f281b10 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/InstallNewSoftwareHandler.java +++ b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/InstallNewSoftwareHandler.java @@ -11,12 +11,7 @@ package org.eclipse.equinox.internal.p2.ui.sdk; import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.InstallWizard; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.ProvisioningWizardDialog; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.wizard.WizardDialog; -import org.eclipse.ui.PlatformUI; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; /** * InstallNewSoftwareHandler invokes the install wizard @@ -32,29 +27,25 @@ public class InstallNewSoftwareHandler extends PreloadingRepositoryHandler { super(); } - protected void doExecute(String profileId, QueryableMetadataRepositoryManager manager) { - InstallWizard wizard = new InstallWizard(Policy.getDefault(), profileId, null, null, manager); - WizardDialog dialog = new ProvisioningWizardDialog(getShell(), wizard); - dialog.create(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IProvHelpContextIds.INSTALL_WIZARD); - - dialog.open(); + protected void doExecute(LoadMetadataRepositoryJob job) { + getProvisioningUI().openInstallWizard(getShell(), null, null, job); } protected boolean waitForPreload() { - // If there is no way for the user to manipulate repositories, - // then we may as well wait for existing repos to load so that - // content is available. If the user can manipulate the - // repositories, then we don't wait, because we don't know which - // ones they want to work with. - return Policy.getDefault().getRepositoryManipulator() == null; + // If the user cannot see repositories, then we may as well wait + // for existing repos to load so that content is available. + // If the user can manipulate the repositories, then we don't wait, + // because we don't know which ones they want to work with. + return !getProvisioningUI().getPolicy().getRepositoriesVisible(); } protected void setLoadJobProperties(Job loadJob) { + super.setLoadJobProperties(loadJob); // If we are doing a background load, we do not wish to authenticate, as the // user is unaware that loading was needed if (!waitForPreload()) { - loadJob.setProperty(ValidationDialogServiceUI.SUPPRESS_AUTHENTICATION_JOB_MARKER, Boolean.toString(true)); + loadJob.setProperty(LoadMetadataRepositoryJob.SUPPRESS_AUTHENTICATION_JOB_MARKER, Boolean.toString(true)); + loadJob.setProperty(LoadMetadataRepositoryJob.SUPPRESS_REPOSITORY_EVENTS, Boolean.toString(true)); } } } diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/PreloadingRepositoryHandler.java b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/PreloadingRepositoryHandler.java index 585207890..73655e87d 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/PreloadingRepositoryHandler.java +++ b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/PreloadingRepositoryHandler.java @@ -12,17 +12,11 @@ package org.eclipse.equinox.internal.p2.ui.sdk; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.swt.custom.BusyIndicator; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.statushandlers.StatusManager; /** * PreloadingRepositoryHandler provides background loading of @@ -32,8 +26,6 @@ import org.eclipse.ui.statushandlers.StatusManager; */ abstract class PreloadingRepositoryHandler extends AbstractHandler { - Object LOAD_FAMILY = new Object(); - /** * The constructor. */ @@ -45,38 +37,15 @@ abstract class PreloadingRepositoryHandler extends AbstractHandler { * Execute the command. */ public Object execute(ExecutionEvent event) { - try { - final String profileId = ProvSDKUIActivator.getSelfProfileId(); - BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { - public void run() { - doExecuteAndLoad(profileId, preloadRepositories()); - } - }); - - } catch (ProvisionException e) { - MessageDialog.openInformation(null, ProvSDKMessages.Handler_SDKUpdateUIMessageTitle, ProvSDKMessages.Handler_CannotLaunchUI); - ProvUI.handleException(e, null, StatusManager.LOG); - } + doExecuteAndLoad(); return null; } - void doExecuteAndLoad(final String profileId, boolean preloadRepositories) { - //cancel any load that is already running - Job.getJobManager().cancel(LOAD_FAMILY); - final QueryableMetadataRepositoryManager queryableManager = new QueryableMetadataRepositoryManager(Policy.getDefault().getQueryContext(), false); - if (preloadRepositories) { - Job loadJob = new Job(ProvSDKMessages.InstallNewSoftwareHandler_LoadRepositoryJobLabel) { - - protected IStatus run(IProgressMonitor monitor) { - queryableManager.loadAll(monitor); - return Status.OK_STATUS; - } - - public boolean belongsTo(Object family) { - return family == LOAD_FAMILY; - } - - }; + void doExecuteAndLoad() { + if (preloadRepositories()) { + //cancel any load that is already running + Job.getJobManager().cancel(LoadMetadataRepositoryJob.LOAD_FAMILY); + final LoadMetadataRepositoryJob loadJob = new LoadMetadataRepositoryJob(getProvisioningUI()); setLoadJobProperties(loadJob); if (waitForPreload()) { loadJob.addJobChangeListener(new JobChangeAdapter() { @@ -85,7 +54,7 @@ abstract class PreloadingRepositoryHandler extends AbstractHandler { if (event.getResult().isOK()) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { - doExecute(profileId, queryableManager); + doExecute(loadJob); } }); } @@ -98,14 +67,14 @@ abstract class PreloadingRepositoryHandler extends AbstractHandler { loadJob.setSystem(true); loadJob.setUser(false); loadJob.schedule(); - doExecute(profileId, queryableManager); + doExecute(null); } } else { - doExecute(profileId, queryableManager); + doExecute(null); } } - protected abstract void doExecute(String profileId, QueryableMetadataRepositoryManager manager); + protected abstract void doExecute(LoadMetadataRepositoryJob job); protected boolean preloadRepositories() { return true; @@ -116,7 +85,11 @@ abstract class PreloadingRepositoryHandler extends AbstractHandler { } protected void setLoadJobProperties(Job loadJob) { - // nothing to do by default + loadJob.setProperty(LoadMetadataRepositoryJob.ACCUMULATE_LOAD_ERRORS, Boolean.toString(true)); + } + + protected ProvisioningUI getProvisioningUI() { + return ProvisioningUI.getDefaultUI(); } /** @@ -124,6 +97,6 @@ abstract class PreloadingRepositoryHandler extends AbstractHandler { * @return a Shell */ protected Shell getShell() { - return ProvUI.getDefaultParentShell(); + return getProvisioningUI().getDefaultParentShell(); } } diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/ProvSDKMessages.java b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/ProvSDKMessages.java index cab15b6b0..f6ad748bb 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/ProvSDKMessages.java +++ b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/ProvSDKMessages.java @@ -24,9 +24,6 @@ public class ProvSDKMessages extends NLS { // load message values from bundle file NLS.initializeMessages(BUNDLE_NAME, ProvSDKMessages.class); } - public static String Handler_CannotLaunchUI; - public static String Handler_SDKUpdateUIMessageTitle; - public static String InstallNewSoftwareHandler_LoadRepositoryJobLabel; public static String PreferenceInitializer_Error; public static String ProvisioningPreferencePage_AlwaysOpenWizard; public static String ProvisioningPreferencePage_BrowsingPrefsGroup; @@ -41,7 +38,7 @@ public class ProvSDKMessages extends NLS { public static String ProvSDKUIActivator_NoSelfProfile; public static String ProvSDKUIActivator_OpenWizardAnyway; public static String ProvSDKUIActivator_Question; - public static String ProvSDKUIActivator_SitePrefLink; + public static String ProvUILicenseManager_ParsingError; public static String UpdateHandler_NoSitesMessage; public static String UpdateHandler_NoSitesTitle; } diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/ProvSDKUIActivator.java b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/ProvSDKUIActivator.java index a9b53c10b..1c24767c2 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/ProvSDKUIActivator.java +++ b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/ProvSDKUIActivator.java @@ -10,20 +10,18 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.sdk; +import org.eclipse.equinox.p2.ui.LicenseManager; + import java.io.*; import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.ui.sdk.prefs.PreferenceConstants; import org.eclipse.equinox.internal.p2.ui.sdk.prefs.PreferenceInitializer; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.ProfileFactory; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.IUViewQueryContext; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.engine.ProfileScope; +import org.eclipse.equinox.p2.ui.Policy; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.util.IPropertyChangeListener; @@ -39,8 +37,6 @@ import org.osgi.framework.ServiceReference; */ public class ProvSDKUIActivator extends AbstractUIPlugin { - public static final boolean ANY_PROFILE = false; - private static final String DEFAULT_PROFILE_ID = "DefaultProfile"; //$NON-NLS-1$ private static final String LICENSE_STORAGE = "licenses.xml"; //$NON-NLS-1$ private static ProvSDKUIActivator plugin; private static BundleContext context; @@ -97,40 +93,56 @@ public class ProvSDKUIActivator extends AbstractUIPlugin { if (preferenceListener == null) { preferenceListener = new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { - updateWithPreferences(Policy.getDefault().getQueryContext()); + updateWithPreferences(getPolicy()); } }; } return preferenceListener; } + public ProvisioningUI getProvisioningUI() { + return ProvisioningUI.getDefaultUI(); + } + + private Policy getPolicy() { + return getProvisioningUI().getPolicy(); + } + + private LicenseManager getLicenseManager() { + return (LicenseManager) ServiceHelper.getService(getContext(), LicenseManager.class.getName()); + } + private void readLicenseRegistry() { + if (getLicenseManager() == null) + return; IPath location = getStateLocation().append(LICENSE_STORAGE); File f = location.toFile(); BufferedInputStream stream = null; if (f.exists()) { try { stream = new BufferedInputStream(new FileInputStream(f)); - Policy.getDefault().getLicenseManager().read(stream); + getLicenseManager().read(stream); stream.close(); } catch (IOException e) { - ProvUI.reportStatus(new Status(IStatus.ERROR, PLUGIN_ID, 0, ProvSDKMessages.ProvSDKUIActivator_LicenseManagerReadError, e), StatusManager.LOG); + StatusManager.getManager().handle(new Status(IStatus.ERROR, PLUGIN_ID, 0, ProvSDKMessages.ProvSDKUIActivator_LicenseManagerReadError, e), StatusManager.LOG); } } } private void writeLicenseRegistry() { - if (!Policy.getDefault().getLicenseManager().hasAcceptedLicenses()) + if (getLicenseManager() == null) + return; + if (!getLicenseManager().hasAcceptedLicenses()) return; IPath location = getStateLocation().append(LICENSE_STORAGE); File f = location.toFile(); BufferedOutputStream stream = null; try { stream = new BufferedOutputStream(new FileOutputStream(f, false)); - Policy.getDefault().getLicenseManager().write(stream); + getLicenseManager().write(stream); stream.close(); } catch (IOException e) { - ProvUI.reportStatus(new Status(IStatus.ERROR, PLUGIN_ID, 0, ProvSDKMessages.ProvSDKUIActivator_ErrorWritingLicenseRegistry, e), StatusManager.LOG); + StatusManager.getManager().handle(new Status(IStatus.ERROR, PLUGIN_ID, 0, ProvSDKMessages.ProvSDKUIActivator_ErrorWritingLicenseRegistry, e), StatusManager.LOG); } } @@ -148,39 +160,12 @@ public class ProvSDKUIActivator extends AbstractUIPlugin { return (IProvisioningEventBus) context.getService(busReference); } - /** - * Get the id of the profile for the running system. Throw a ProvisionException - * if no self profile is available, unless configured to answer any - * profile. Getting any profile allows testing of the - * UI even when the system is not self hosting. - */ - public static String getSelfProfileId() throws ProvisionException { - // Get the profile of the running system. - IProfile profile = ProvisioningUtil.getProfile(IProfileRegistry.SELF); - if (profile == null) { - if (ANY_PROFILE) { - ProvUI.reportStatus(getNoSelfProfileStatus(), StatusManager.LOG); - IProfile[] profiles = ProvisioningUtil.getProfiles(); - if (profiles.length > 0) - return profiles[0].getProfileId(); - return ProfileFactory.makeProfile(DEFAULT_PROFILE_ID).getProfileId(); - } - throw new ProvisionException(getNoSelfProfileStatus()); - } - return profile.getProfileId(); - } - static IStatus getNoSelfProfileStatus() { return new Status(IStatus.WARNING, PLUGIN_ID, ProvSDKMessages.ProvSDKUIActivator_NoSelfProfile); } - void updateWithPreferences(IUViewQueryContext queryContext) { - queryContext.setShowLatestVersionsOnly(getPreferenceStore().getBoolean(PreferenceConstants.PREF_SHOW_LATEST_VERSION)); - queryContext.setVisibleAvailableIUProperty(IInstallableUnit.PROP_TYPE_GROUP); - // If this ever changes, we must change AutomaticUpdateSchedule.getProfileQuery() - queryContext.setVisibleInstalledIUProperty(IInstallableUnit.PROP_PROFILE_ROOT_IU); - queryContext.setArtifactRepositoryFlags(IRepositoryManager.REPOSITORIES_NON_SYSTEM); - queryContext.setMetadataRepositoryFlags(IRepositoryManager.REPOSITORIES_NON_SYSTEM); + void updateWithPreferences(Policy policy) { + policy.setShowLatestVersionsOnly(getPreferenceStore().getBoolean(PreferenceConstants.PREF_SHOW_LATEST_VERSION)); } /* @@ -201,7 +186,7 @@ public class ProvSDKUIActivator extends AbstractUIPlugin { try { preferenceStore.save(); } catch (IOException e) { - ProvUI.handleException(e, ProvSDKMessages.ProvSDKUIActivator_ErrorSavingPrefs, StatusManager.LOG | StatusManager.SHOW); + StatusManager.getManager().handle(new Status(IStatus.ERROR, PLUGIN_ID, 0, ProvSDKMessages.ProvSDKUIActivator_ErrorSavingPrefs, e), StatusManager.LOG | StatusManager.SHOW); } } } diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/SDKPolicy.java b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/SDKPolicy.java index 9a1a02d44..e8c70626f 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/SDKPolicy.java +++ b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/SDKPolicy.java @@ -12,11 +12,11 @@ package org.eclipse.equinox.internal.p2.ui.sdk; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.ui.sdk.prefs.PreferenceConstants; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.ui.IStatusCodes; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.engine.query.UserVisibleRootQuery; +import org.eclipse.equinox.p2.metadata.query.GroupQuery; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.ui.Policy; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialogWithToggle; import org.eclipse.jface.preference.IPreferenceStore; @@ -28,67 +28,47 @@ import org.eclipse.ui.statushandlers.StatusManager; * p2 UI. The policy is declared as an OSGi service in * the policy_component.xml file. * - * @since 3.5 + * @since 3.6 */ public class SDKPolicy extends Policy { + public SDKPolicy() { - setProfileChooser(new IProfileChooser() { - public String getProfileId(Shell shell) { - try { - return ProvSDKUIActivator.getSelfProfileId(); - } catch (ProvisionException e) { - ProvUI.handleException(e, e.getStatus().getMessage(), StatusManager.LOG); - return null; - } - } - }); - setRepositoryManipulator(new ColocatedRepositoryManipulator(this, PreferenceConstants.PREF_PAGE_SITES) { - public String getManipulatorLinkLabel() { - return ProvSDKMessages.ProvSDKUIActivator_SitePrefLink; - } - }); - setPlanValidator(new PlanValidator() { - public boolean continueWorkingWithPlan(ProvisioningPlan plan, Shell shell) { - if (plan == null) - return false; - if (plan.getStatus().getSeverity() == IStatus.CANCEL) - return false; + // initialize for our values + setVisibleAvailableIUQuery(new GroupQuery()); + // If this ever changes, we must change AutomaticUpdateSchedule.getProfileQuery() + setVisibleInstalledIUQuery(new UserVisibleRootQuery()); + ProvSDKUIActivator.getDefault().updateWithPreferences(this); + } - // Special case those statuses where we would never want to open a wizard - if (plan.getStatus().getCode() == IStatusCodes.NOTHING_TO_UPDATE) { - ProvUI.reportStatus(plan.getStatus(), StatusManager.BLOCK); - return false; - } + public IStatus getNoProfileChosenStatus() { + return ProvSDKUIActivator.getNoSelfProfileStatus(); + } - // Allow the wizard to open if there is no error - if (plan.getStatus().getSeverity() != IStatus.ERROR) - return true; + public boolean continueWorkingOperation(ProfileChangeOperation operation, Shell shell) { + // don't continue if superclass has already identified problem scenarios + boolean ok = super.continueWorkingWithOperation(operation, shell); + if (!ok) + return false; - // There is an error. Check the preference to see whether to continue. - IPreferenceStore prefs = ProvSDKUIActivator.getDefault().getPreferenceStore(); - String openPlan = prefs.getString(PreferenceConstants.PREF_OPEN_WIZARD_ON_ERROR_PLAN); - if (MessageDialogWithToggle.ALWAYS.equals(openPlan)) { - return true; - } - if (MessageDialogWithToggle.NEVER.equals(openPlan)) { - ProvUI.reportStatus(plan.getStatus(), StatusManager.SHOW | StatusManager.LOG); - return false; - } - MessageDialogWithToggle dialog = MessageDialogWithToggle.openYesNoCancelQuestion(shell, ProvSDKMessages.ProvSDKUIActivator_Question, ProvSDKMessages.ProvSDKUIActivator_OpenWizardAnyway, null, false, prefs, PreferenceConstants.PREF_OPEN_WIZARD_ON_ERROR_PLAN); + IProvisioningPlan plan = operation.getProvisioningPlan(); + if (plan == null) + return false; - // Any answer but yes will stop the performance of the plan, but NO is interpreted to mean, show me the error. - if (dialog.getReturnCode() == IDialogConstants.NO_ID) - ProvUI.reportStatus(plan.getStatus(), StatusManager.SHOW | StatusManager.LOG); - return dialog.getReturnCode() == IDialogConstants.YES_ID; - } - }); - // Start with the default query context and configure some settings - IUViewQueryContext queryContext = new IUViewQueryContext(IUViewQueryContext.AVAILABLE_VIEW_BY_CATEGORY); - setQueryContext(queryContext); - ProvSDKUIActivator.getDefault().updateWithPreferences(queryContext); - } + // Check the preference to see whether to continue. + IPreferenceStore prefs = ProvSDKUIActivator.getDefault().getPreferenceStore(); + String openPlan = prefs.getString(PreferenceConstants.PREF_OPEN_WIZARD_ON_ERROR_PLAN); + if (MessageDialogWithToggle.ALWAYS.equals(openPlan)) { + return true; + } + if (MessageDialogWithToggle.NEVER.equals(openPlan)) { + StatusManager.getManager().handle(plan.getStatus(), StatusManager.SHOW | StatusManager.LOG); + return false; + } + MessageDialogWithToggle dialog = MessageDialogWithToggle.openYesNoCancelQuestion(shell, ProvSDKMessages.ProvSDKUIActivator_Question, ProvSDKMessages.ProvSDKUIActivator_OpenWizardAnyway, null, false, prefs, PreferenceConstants.PREF_OPEN_WIZARD_ON_ERROR_PLAN); - public IStatus getNoProfileChosenStatus() { - return ProvSDKUIActivator.getNoSelfProfileStatus(); + // Any answer but yes will stop the performance of the plan, but NO is interpreted to mean, show me the error. + if (dialog.getReturnCode() == IDialogConstants.NO_ID) + StatusManager.getManager().handle(plan.getStatus(), StatusManager.SHOW | StatusManager.LOG); + return dialog.getReturnCode() == IDialogConstants.YES_ID; } } diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/SimpleLicenseManager.java b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/SimpleLicenseManager.java new file mode 100644 index 000000000..a30f2d0ed --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/SimpleLicenseManager.java @@ -0,0 +1,118 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Genuitec, LLC - added license support + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.sdk; + +import java.io.*; +import java.util.*; +import javax.xml.parsers.*; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.equinox.p2.metadata.ILicense; +import org.eclipse.equinox.p2.ui.LicenseManager; +import org.eclipse.ui.statushandlers.StatusManager; +import org.w3c.dom.*; +import org.xml.sax.SAXException; + +/** + * SimpleLicenseManager is a license manager that keeps track of + * IInstallableUnit licenses by using the digests of the IU's licenses. + * It can read and write its accepted list to a stream. + * + * @since 3.4 + */ +public class SimpleLicenseManager extends LicenseManager { + java.util.Set accepted = new HashSet(); + + public boolean accept(ILicense license) { + accepted.add(license.getUUID()); + return true; + } + + public boolean reject(ILicense license) { + accepted.remove(license.getUUID()); + return true; + } + + public boolean isAccepted(ILicense license) { + return accepted.contains(license.getUUID()); + } + + public boolean hasAcceptedLicenses() { + return !accepted.isEmpty(); + } + + public void read(InputStream stream) throws IOException { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + DocumentBuilder parser = factory.newDocumentBuilder(); + Document doc = parser.parse(stream); + Node root = doc.getDocumentElement(); + processRoot(root, accepted); + } catch (ParserConfigurationException e) { + handleException(e, ProvSDKMessages.ProvUILicenseManager_ParsingError, StatusManager.LOG); + } catch (SAXException e) { + handleException(e, ProvSDKMessages.ProvUILicenseManager_ParsingError, StatusManager.LOG); + } + } + + private void handleException(Throwable t, String message, int style) { + if (message == null && t != null) { + message = t.getMessage(); + } + IStatus status = new Status(IStatus.ERROR, ProvSDKUIActivator.PLUGIN_ID, 0, message, t); + StatusManager.getManager().handle(status, style); + } + + public void write(OutputStream stream) throws IOException { + OutputStreamWriter osw = null; + PrintWriter writer = null; + try { + osw = new OutputStreamWriter(stream, "UTF8"); //$NON-NLS-1$ + writer = new PrintWriter(osw); + writer.println(""); //$NON-NLS-1$ + writer.println(""); //$NON-NLS-1$ + for (Iterator i = accepted.iterator(); i.hasNext();) { + String digest = (String) i.next(); + writer.print(" " + ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + } finally { + writer.println(""); //$NON-NLS-1$ + writer.flush(); + writer.close(); + if (osw != null) + osw.close(); + } + } + + private void processRoot(Node root, Set licenses) { + if (root.getNodeName().equals("licenses")) { //$NON-NLS-1$ + NodeList children = root.getChildNodes(); + processChildren(children, licenses); + } + } + + private void processChildren(NodeList children, Set licenses) { + for (int i = 0; i < children.getLength(); i++) { + Node child = children.item(i); + if (child.getNodeType() == Node.ELEMENT_NODE) { + if (child.getNodeName().equals("license")) { //$NON-NLS-1$ + NamedNodeMap atts = child.getAttributes(); + Node digestAtt = atts.getNamedItem("digest"); //$NON-NLS-1$ + if (digestAtt != null) { + licenses.add(digestAtt.getNodeValue()); + } + } + } + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/UpdateHandler.java b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/UpdateHandler.java index 924632b7d..df76f1d72 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/UpdateHandler.java +++ b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/UpdateHandler.java @@ -10,16 +10,10 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.sdk; -import java.util.Collection; -import java.util.Iterator; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.UpdateAction; -import org.eclipse.equinox.internal.provisional.p2.ui.model.ProfileElement; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.operations.UpdateOperation; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.viewers.*; /** * UpdateHandler invokes the check for updates UI @@ -30,59 +24,28 @@ public class UpdateHandler extends PreloadingRepositoryHandler { boolean hasNoRepos = false; - /** - * The constructor. - */ - public UpdateHandler() { - // constructor - } - - protected void doExecute(String profileId, QueryableMetadataRepositoryManager manager) { + protected void doExecute(LoadMetadataRepositoryJob job) { if (hasNoRepos) { - boolean goToSites = MessageDialog.openQuestion(getShell(), ProvSDKMessages.UpdateHandler_NoSitesTitle, ProvSDKMessages.UpdateHandler_NoSitesMessage); - if (goToSites) { - Policy.getDefault().getRepositoryManipulator().manipulateRepositories(getShell()); + if (getProvisioningUI().getPolicy().getRepositoriesVisible()) { + boolean goToSites = MessageDialog.openQuestion(getShell(), ProvSDKMessages.UpdateHandler_NoSitesTitle, ProvSDKMessages.UpdateHandler_NoSitesMessage); + if (goToSites) { + getProvisioningUI().manipulateRepositories(getShell()); + } } return; } - // get the profile roots - ElementQueryDescriptor queryDescriptor = Policy.getDefault().getQueryProvider().getQueryDescriptor(new ProfileElement(null, profileId)); - Collection collection = queryDescriptor.performQuery(null); - final IInstallableUnit[] roots = new IInstallableUnit[collection.size()]; - Iterator iter = collection.iterator(); - int i = 0; - while (iter.hasNext()) { - roots[i] = (IInstallableUnit) ProvUI.getAdapter(iter.next(), IInstallableUnit.class); - i++; + UpdateOperation operation = getProvisioningUI().getUpdateOperation(null, null); + // check for updates + operation.resolveModal(null); + if (getProvisioningUI().getPolicy().continueWorkingWithOperation(operation, getShell())) { + getProvisioningUI().openUpdateWizard(getShell(), true, operation, job); } - // now create an update action whose selection is all the roots - UpdateAction action = new UpdateAction(Policy.getDefault(), new ISelectionProvider() { - - public void addSelectionChangedListener(ISelectionChangedListener listener) { - // not dynamic - } - - public ISelection getSelection() { - return new StructuredSelection(roots); - } - - public void removeSelectionChangedListener(ISelectionChangedListener listener) { - // not dynamic - } - - public void setSelection(ISelection selection) { - // not mutable - - } - }, profileId, false); - action.setRepositoryManager(manager); - action.run(); } protected boolean preloadRepositories() { hasNoRepos = false; - RepositoryManipulator repoMan = Policy.getDefault().getRepositoryManipulator(); - if (repoMan != null && repoMan.getKnownRepositories().length == 0) { + RepositoryTracker repoMan = getProvisioningUI().getRepositoryTracker(); + if (repoMan.getKnownRepositories(getProvisioningUI().getSession()).length == 0) { hasNoRepos = true; return false; } diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/messages.properties b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/messages.properties index 3ad993dae..3431a70d8 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/messages.properties +++ b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/messages.properties @@ -9,10 +9,6 @@ # IBM Corporation - initial API and implementation ############################################################################### - -Handler_CannotLaunchUI=Cannot complete the request. This installation has not been configured properly for Software Updates. -Handler_SDKUpdateUIMessageTitle=Software Updates -InstallNewSoftwareHandler_LoadRepositoryJobLabel=Contacting Software Sites PreferenceInitializer_Error=Error accessing preferences. ProvSDKUIActivator_ErrorSavingPrefs=Error saving update preferences ProvSDKUIActivator_ErrorWritingLicenseRegistry=Error writing license registry. Accepted licenses will not be remembered. @@ -20,7 +16,6 @@ ProvSDKUIActivator_LicenseManagerReadError=Error reading license registry. Acce ProvSDKUIActivator_NoSelfProfile=Could not locate the running profile instance. The eclipse.p2.data.area and eclipse.p2.profile properties may not be set correctly in this application's config.ini file. ProvSDKUIActivator_OpenWizardAnyway=The software items you selected may not be valid with your current installation. Do you want to open the wizard anyway to review the selections? ProvSDKUIActivator_Question=Question -ProvSDKUIActivator_SitePrefLink=Find more software by working with the 'Available Software Sites' preferences. ProvisioningPreferencePage_AlwaysOpenWizard=&Open the wizard anyway to review or change selections ProvisioningPreferencePage_BrowsingPrefsGroup=Browsing for updates ProvisioningPreferencePage_ShowLatestVersions=Show only the &latest versions of available software @@ -28,5 +23,6 @@ ProvisioningPreferencePage_ShowAllVersions=Show all &versions of available softw ProvisioningPreferencePage_NeverOpenWizard=&Report the problems and do not open the wizard ProvisioningPreferencePage_OpenWizardIfInvalid=When software selected for an install wizard may not be compatible ProvisioningPreferencePage_PromptToOpenWizard=As&k me what to do when it happens +ProvUILicenseManager_ParsingError=Error parsing the accepted license registry UpdateHandler_NoSitesMessage=There are no update sites to search. Do you wish to open the "Available Software Sites" preferences? UpdateHandler_NoSitesTitle=No Updates Found \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/prefs/PreferenceInitializer.java b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/prefs/PreferenceInitializer.java index bf829f3e6..bc0369fa0 100644 --- a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/prefs/PreferenceInitializer.java +++ b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/prefs/PreferenceInitializer.java @@ -10,12 +10,13 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.sdk.prefs; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.preferences.*; import org.eclipse.equinox.internal.p2.ui.sdk.ProvSDKMessages; import org.eclipse.equinox.internal.p2.ui.sdk.ProvSDKUIActivator; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.engine.ProfileScope; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.engine.ProfileScope; import org.eclipse.jface.dialogs.MessageDialogWithToggle; import org.eclipse.ui.statushandlers.StatusManager; import org.osgi.service.prefs.BackingStoreException; @@ -39,7 +40,7 @@ public class PreferenceInitializer extends AbstractPreferenceInitializer { pref.flush(); } } catch (BackingStoreException e) { - ProvUI.handleException(e, ProvSDKMessages.PreferenceInitializer_Error, StatusManager.LOG); + StatusManager.getManager().handle(new Status(IStatus.ERROR, ProvSDKUIActivator.PLUGIN_ID, 0, ProvSDKMessages.PreferenceInitializer_Error, e), StatusManager.LOG); } } diff --git a/bundles/org.eclipse.equinox.p2.ui/.classpath b/bundles/org.eclipse.equinox.p2.ui/.classpath index ce7393340..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.ui/.classpath +++ b/bundles/org.eclipse.equinox.p2.ui/.classpath @@ -1,7 +1,7 @@ - - + + diff --git a/bundles/org.eclipse.equinox.p2.ui/.project b/bundles/org.eclipse.equinox.p2.ui/.project index 06b02bb38..1b62af1af 100644 --- a/bundles/org.eclipse.equinox.p2.ui/.project +++ b/bundles/org.eclipse.equinox.p2.ui/.project @@ -25,6 +25,11 @@ + + org.eclipse.pde.ds.core.builder + + + org.eclipse.pde.PluginNature diff --git a/bundles/org.eclipse.equinox.p2.ui/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.ui/.settings/org.eclipse.jdt.core.prefs index a6b401a0d..19b78b9fd 100644 --- a/bundles/org.eclipse.equinox.p2.ui/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.ui/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Tue Sep 18 21:22:20 EDT 2007 +#Tue Dec 22 23:22:15 CET 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.builder.cleanOutputFolder=clean org.eclipse.jdt.core.builder.duplicateResourceTask=warning @@ -7,24 +7,24 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fieldHiding=warning org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning @@ -71,7 +71,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=en org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 @@ -143,7 +143,6 @@ org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert diff --git a/bundles/org.eclipse.equinox.p2.ui/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.ui/META-INF/MANIFEST.MF index 8fec353bc..cf41929b8 100644 --- a/bundles/org.eclipse.equinox.p2.ui/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.ui/META-INF/MANIFEST.MF @@ -4,75 +4,50 @@ Bundle-Name: %bundleName Bundle-Vendor: %providerName Bundle-Localization: plugin Bundle-SymbolicName: org.eclipse.equinox.p2.ui;singleton:=true -Bundle-Version: 1.1.0.qualifier +Bundle-Version: 2.0.0.qualifier Bundle-Activator: org.eclipse.equinox.internal.p2.ui.ProvUIActivator Import-Package: com.ibm.icu.text, + javax.xml.parsers, + org.eclipse.equinox.internal.p2.artifact.repository, org.eclipse.equinox.internal.p2.core.helpers, org.eclipse.equinox.internal.p2.metadata, + org.eclipse.equinox.internal.p2.metadata.query, org.eclipse.equinox.internal.p2.metadata.repository, + org.eclipse.equinox.internal.p2.query, org.eclipse.equinox.internal.p2.repository.helpers, org.eclipse.equinox.internal.p2.rollback, org.eclipse.equinox.internal.provisional.configurator, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing, org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.core.eventbus, - org.eclipse.equinox.internal.provisional.p2.repository, org.eclipse.equinox.internal.provisional.p2.director, - org.eclipse.equinox.internal.provisional.p2.engine, - org.eclipse.equinox.internal.provisional.p2.engine.phases, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.spi.p2.repository, + org.eclipse.equinox.internal.provisional.p2.repository, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.engine.query, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.expression, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.operations, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.metadata, + org.eclipse.equinox.p2.repository.spi, org.eclipse.osgi.service.resolver;version="1.1.0", org.eclipse.osgi.util;version="1.1.0", org.osgi.framework;version="1.3.0", org.osgi.service.packageadmin;version="1.2.0", - javax.xml.parsers, org.w3c.dom, org.xml.sax -Export-Package: org.eclipse.equinox.internal.p2.ui;x-internal:=true, - org.eclipse.equinox.internal.p2.ui.dialogs;x-internal:=true, - org.eclipse.equinox.internal.p2.ui.model;x-internal:=true, - org.eclipse.equinox.internal.p2.ui.query;x-internal:=true, - org.eclipse.equinox.internal.p2.ui.viewers;x-internal:=true, - org.eclipse.equinox.internal.provisional.p2.ui; - x-friends:="org.eclipse.equinox.p2.ui.admin, - org.eclipse.equinox.p2.ui.admin.rcp, - org.eclipse.equinox.p2.ui.sdk, - org.eclipse.equinox.p2.ui.sdk.scheduler, - org.eclipse.pde.ui", - org.eclipse.equinox.internal.provisional.p2.ui.actions; - x-friends:="org.eclipse.equinox.p2.ui.admin, - org.eclipse.equinox.p2.ui.admin.rcp, - org.eclipse.equinox.p2.ui.sdk, - org.eclipse.equinox.p2.ui.sdk.scheduler, - org.eclipse.pde.ui", - org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - x-friends:="org.eclipse.equinox.p2.ui.admin, - org.eclipse.equinox.p2.ui.admin.rcp, - org.eclipse.equinox.p2.ui.sdk, - org.eclipse.equinox.p2.ui.sdk.scheduler, - org.eclipse.pde.ui", - org.eclipse.equinox.internal.provisional.p2.ui.model; - x-friends:="org.eclipse.equinox.p2.ui.admin, - org.eclipse.equinox.p2.ui.admin.rcp, - org.eclipse.equinox.p2.ui.sdk, - org.eclipse.equinox.p2.ui.sdk.scheduler", - org.eclipse.equinox.internal.provisional.p2.ui.operations; - x-friends:="org.eclipse.equinox.p2.ui.admin, - org.eclipse.equinox.p2.ui.admin.rcp, - org.eclipse.equinox.p2.ui.sdk, - org.eclipse.equinox.p2.ui.sdk.scheduler, - org.eclipse.pde.ui", - org.eclipse.equinox.internal.provisional.p2.ui.policy; - x-friends:="org.eclipse.equinox.p2.ui.admin, - org.eclipse.equinox.p2.ui.admin.rcp, - org.eclipse.equinox.p2.ui.sdk, - org.eclipse.equinox.p2.ui.sdk.scheduler, - org.eclipse.pde.ui", - org.eclipse.equinox.internal.provisional.p2.ui.viewers;x-friends:="org.eclipse.equinox.p2.ui.admin,org.eclipse.equinox.p2.ui.admin.rcp,org.eclipse.equinox.p2.ui.sdk" +Export-Package: org.eclipse.equinox.internal.p2.ui;x-friends:="org.eclipse.equinox.p2.ui.admin,org.eclipse.pde.ui", + org.eclipse.equinox.internal.p2.ui.actions;x-friends:="org.eclipse.equinox.p2.ui.admin, org.eclipse.equinox.p2.ui.sdk.scheduler", + org.eclipse.equinox.internal.p2.ui.dialogs;x-friends:="org.eclipse.equinox.p2.ui.admin, org.eclipse.equinox.p2.ui.sdk.scheduler, org.eclipse.pde.ui", + org.eclipse.equinox.internal.p2.ui.model;x-friends:="org.eclipse.equinox.p2.ui.admin, org.eclipse.equinox.p2.ui.sdk.scheduler, org.eclipse.equinox.internal.p2.ui.analysis", + org.eclipse.equinox.internal.p2.ui.query;x-friends:="org.eclipse.equinox.p2.ui.admin, org.eclipse.equinox.internal.p2.ui.analysis", + org.eclipse.equinox.internal.p2.ui.viewers;x-friends:="org.eclipse.equinox.p2.ui.admin, org.eclipse.equinox.p2.ui.sdk.scheduler", + org.eclipse.equinox.p2.ui Require-Bundle: org.eclipse.ui, org.eclipse.core.runtime, org.eclipse.core.expressions, @@ -81,5 +56,8 @@ Require-Bundle: org.eclipse.ui, org.eclipse.equinox.security.ui;bundle-version="[1.0.0,2.0.0)", org.eclipse.compare Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: J2SE-1.4, +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, CDC-1.1/Foundation-1.1 +Service-Component: OSGI-INF/serviceui_component.xml, OSGI-INF/repositoryTracker_component.xml + diff --git a/bundles/org.eclipse.equinox.p2.ui/OSGI-INF/repositoryTracker_component.xml b/bundles/org.eclipse.equinox.p2.ui/OSGI-INF/repositoryTracker_component.xml new file mode 100644 index 000000000..f4c2c7386 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/OSGI-INF/repositoryTracker_component.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/bundles/org.eclipse.equinox.p2.ui/OSGI-INF/serviceui_component.xml b/bundles/org.eclipse.equinox.p2.ui/OSGI-INF/serviceui_component.xml new file mode 100644 index 000000000..96a25d3dd --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/OSGI-INF/serviceui_component.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/bundles/org.eclipse.equinox.p2.ui/build.properties b/bundles/org.eclipse.equinox.p2.ui/build.properties index 137776701..8e36e3064 100644 --- a/bundles/org.eclipse.equinox.p2.ui/build.properties +++ b/bundles/org.eclipse.equinox.p2.ui/build.properties @@ -13,6 +13,9 @@ bin.includes = plugin.properties,\ .,\ about.html,\ META-INF/,\ - plugin.xml -src.includes = about.html + plugin.xml,\ + OSGI-INF/ +ssrc.includes = about.html source.. = src/ +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.ui/icons/tool/close.gif b/bundles/org.eclipse.equinox.p2.ui/icons/tool/close.gif deleted file mode 100644 index 1aca259db..000000000 Binary files a/bundles/org.eclipse.equinox.p2.ui/icons/tool/close.gif and /dev/null differ diff --git a/bundles/org.eclipse.equinox.p2.ui/icons/tool/close_hot.gif b/bundles/org.eclipse.equinox.p2.ui/icons/tool/close_hot.gif deleted file mode 100644 index d5360165c..000000000 Binary files a/bundles/org.eclipse.equinox.p2.ui/icons/tool/close_hot.gif and /dev/null differ diff --git a/bundles/org.eclipse.equinox.p2.ui/icons/tool/update.gif b/bundles/org.eclipse.equinox.p2.ui/icons/tool/update.gif deleted file mode 100644 index aa84ebeaa..000000000 Binary files a/bundles/org.eclipse.equinox.p2.ui/icons/tool/update.gif and /dev/null differ diff --git a/bundles/org.eclipse.equinox.p2.ui/icons/tool/update_problems.gif b/bundles/org.eclipse.equinox.p2.ui/icons/tool/update_problems.gif deleted file mode 100644 index c0cfaca34..000000000 Binary files a/bundles/org.eclipse.equinox.p2.ui/icons/tool/update_problems.gif and /dev/null differ diff --git a/bundles/org.eclipse.equinox.p2.ui/plugin.xml b/bundles/org.eclipse.equinox.p2.ui/plugin.xml index f2d82005f..6f6031e2e 100644 --- a/bundles/org.eclipse.equinox.p2.ui/plugin.xml +++ b/bundles/org.eclipse.equinox.p2.ui/plugin.xml @@ -6,12 +6,45 @@ - - - - - + + + + + - - + + + + + + + + + + + + + + + + + + + + + + diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/BatchChangeBeginningEvent.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/BatchChangeBeginningEvent.java deleted file mode 100644 index 012f9af78..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/BatchChangeBeginningEvent.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - ******************************************************************************/ - -package org.eclipse.equinox.internal.p2.ui; - -import java.util.EventObject; - -/** - * - * Event used to signify that a batch change is about - * to begin. We should ignore listeners until it is - * done. - * - * @since 3.4 - */ -public class BatchChangeBeginningEvent extends EventObject { - - private static final long serialVersionUID = -7529156836242774280L; - - /** - * Construct a new instance of this event. - * @param source the source of the event - */ - public BatchChangeBeginningEvent(Object source) { - super(source); - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/BatchChangeCompleteEvent.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/BatchChangeCompleteEvent.java deleted file mode 100644 index 33b743842..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/BatchChangeCompleteEvent.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.p2.ui; - -import java.util.EventObject; - -/** - * Internal UI event used to signify that a batch change in which - * we were ignoring listeners is done. - * - * @since 3.4 - */ -public class BatchChangeCompleteEvent extends EventObject { - - private static final long serialVersionUID = -4513769756968621852L; - - /** - * When the batch event is received, do we treat it as notification - * or ignore it? - */ - public boolean notify; - - /** - * Construct a new instance of this event. - * @param source the source of the event - */ - public BatchChangeCompleteEvent(Object source, boolean notify) { - super(source); - this.notify = notify; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ColocatedRepositoryTracker.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ColocatedRepositoryTracker.java new file mode 100644 index 000000000..20336906d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ColocatedRepositoryTracker.java @@ -0,0 +1,167 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.net.URI; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.ui.dialogs.RepositoryNameAndLocationDialog; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.window.Window; +import org.eclipse.osgi.util.NLS; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.statushandlers.StatusManager; + +/** + * Provides a repository tracker that interprets URLs as colocated + * artifact and metadata repositories. + * + * @since 2.0 + */ + +public class ColocatedRepositoryTracker extends RepositoryTracker { + + ProvisioningUI ui; + + public ColocatedRepositoryTracker() { + this(ProvisioningUI.getDefaultUI()); + } + + public ColocatedRepositoryTracker(ProvisioningUI ui) { + this.ui = ui; + setArtifactRepositoryFlags(IRepositoryManager.REPOSITORIES_NON_SYSTEM); + setMetadataRepositoryFlags(IRepositoryManager.REPOSITORIES_NON_SYSTEM); + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getKnownRepositories() + */ + public URI[] getKnownRepositories(ProvisioningSession session) { + return session.getMetadataRepositoryManager().getKnownRepositories(getMetadataRepositoryFlags()); + } + + protected IStatus validateRepositoryLocationWithManager(ProvisioningSession session, URI location, IProgressMonitor monitor) { + return session.getMetadataRepositoryManager().validateRepositoryLocation(location, monitor); + } + + public void addRepository(URI repoLocation, String nickname, ProvisioningSession session) { + ui.signalRepositoryOperationStart(); + try { + session.getMetadataRepositoryManager().addRepository(repoLocation); + session.getArtifactRepositoryManager().addRepository(repoLocation); + if (nickname != null) { + session.getMetadataRepositoryManager().setRepositoryProperty(repoLocation, IRepository.PROP_NICKNAME, nickname); + session.getArtifactRepositoryManager().setRepositoryProperty(repoLocation, IRepository.PROP_NICKNAME, nickname); + + } + } finally { + // We know that the UI only responds to metadata repo events so we cheat... + ui.signalRepositoryOperationComplete(new RepositoryEvent(repoLocation, IRepository.TYPE_METADATA, RepositoryEvent.ADDED, true), true); + } + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.RepositoryTracker#removeRepositories(java.net.URI[], org.eclipse.equinox.p2.operations.ProvisioningSession) + */ + public void removeRepositories(URI[] repoLocations, ProvisioningSession session) { + ui.signalRepositoryOperationStart(); + try { + for (int i = 0; i < repoLocations.length; i++) { + session.getMetadataRepositoryManager().removeRepository(repoLocations[i]); + session.getArtifactRepositoryManager().removeRepository(repoLocations[i]); + } + } finally { + ui.signalRepositoryOperationComplete(null, true); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.RepositoryTracker#refreshRepositories(java.net.URI[], org.eclipse.equinox.p2.operations.ProvisioningSession, org.eclipse.core.runtime.IProgressMonitor) + */ + public void refreshRepositories(URI[] locations, ProvisioningSession session, IProgressMonitor monitor) { + ui.signalRepositoryOperationStart(); + SubMonitor mon = SubMonitor.convert(monitor, locations.length * 100); + for (int i = 0; i < locations.length; i++) { + try { + session.getArtifactRepositoryManager().refreshRepository(locations[i], mon.newChild(50)); + session.getMetadataRepositoryManager().refreshRepository(locations[i], mon.newChild(50)); + } catch (ProvisionException e) { + //ignore problematic repositories when refreshing + } + } + // We have no idea how many repos may have been added/removed as a result of + // refreshing these, this one, so we do not use a specific repository event to represent it. + ui.signalRepositoryOperationComplete(null, true); + } + + public void reportLoadFailure(final URI location, ProvisionException e) { + int code = e.getStatus().getCode(); + // If the user doesn't have a way to manage repositories, then don't report failures. + if (!ui.getPolicy().getRepositoriesVisible()) { + super.reportLoadFailure(location, e); + return; + } + + // Special handling when the location is bad (not found, etc.) vs. a failure + // associated with a known repo. + if (code == ProvisionException.REPOSITORY_NOT_FOUND || code == ProvisionException.REPOSITORY_INVALID_LOCATION) { + if (!hasNotFoundStatusBeenReported(location)) { + addNotFound(location); + PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { + public void run() { + IWorkbench workbench = PlatformUI.getWorkbench(); + if (workbench.isClosing()) + return; + Shell shell = ProvUI.getDefaultParentShell(); + if (MessageDialog.openQuestion(shell, ProvUIMessages.ColocatedRepositoryTracker_SiteNotFoundTitle, NLS.bind(ProvUIMessages.ColocatedRepositoryTracker_PromptForSiteLocationEdit, URIUtil.toUnencodedString(location)))) { + RepositoryNameAndLocationDialog dialog = new RepositoryNameAndLocationDialog(shell, ui) { + protected String getInitialLocationText() { + return URIUtil.toUnencodedString(location); + } + + protected String getInitialNameText() { + String nickname = ui.getSession().getMetadataRepositoryManager().getRepositoryProperty(location, IRepository.PROP_NICKNAME); + return nickname == null ? "" : nickname; //$NON-NLS-1$ + } + }; + int ret = dialog.open(); + if (ret == Window.OK) { + URI correctedLocation = dialog.getLocation(); + if (correctedLocation != null) { + ui.signalRepositoryOperationStart(); + try { + removeRepositories(new URI[] {location}, ui.getSession()); + addRepository(correctedLocation, dialog.getName(), ui.getSession()); + } finally { + ui.signalRepositoryOperationComplete(null, true); + } + } + } + } + } + }); + } + } else { + ProvUI.handleException(e, null, StatusManager.SHOW | StatusManager.LOG); + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/DefaultMetadataURLValidator.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/DefaultMetadataURLValidator.java deleted file mode 100644 index d56c696bb..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/DefaultMetadataURLValidator.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.p2.ui; - -import java.io.File; -import java.net.URI; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.repository.helpers.RepositoryHelper; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryLocationValidator; - -/** - * @since 3.4 - * - */ -public class DefaultMetadataURLValidator extends RepositoryLocationValidator { - - protected int repoFlag; - - public DefaultMetadataURLValidator() { - repoFlag = IRepositoryManager.REPOSITORIES_ALL; - } - - public void setKnownRepositoriesFlag(int flag) { - repoFlag = flag; - } - - protected URI[] getKnownLocations() { - URI[] knownRepositories; - try { - knownRepositories = ProvisioningUtil.getMetadataRepositories(repoFlag); - } catch (ProvisionException e) { - knownRepositories = new URI[0]; - } - return knownRepositories; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.dialogs.URLValidator#validateRepositoryURL(boolean) - */ - public IStatus validateRepositoryLocation(URI location, boolean contactRepositories, IProgressMonitor monitor) { - - // First validate syntax issues - IStatus localValidationStatus = RepositoryHelper.checkRepositoryLocationSyntax(location); - if (!localValidationStatus.isOK()) { - // bad syntax, but it could just be non-absolute. - // In this case, use the helper - String locationString = URIUtil.toUnencodedString(location); - if (locationString.length() > 0 && (locationString.charAt(0) == '/' || locationString.charAt(0) == File.separatorChar)) { - location = RepositoryHelper.localRepoURIHelper(location); - localValidationStatus = RepositoryHelper.checkRepositoryLocationSyntax(location); - } - } - - if (!localValidationStatus.isOK()) - return localValidationStatus; - - // Syntax was ok, now look for duplicates - URI[] knownRepositories = getKnownLocations(); - for (int i = 0; i < knownRepositories.length; i++) { - if (knownRepositories[i].equals(location)) { - localValidationStatus = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, LOCAL_VALIDATION_ERROR, ProvUIMessages.AddRepositoryDialog_DuplicateURL, null); - break; - } - } - if (!localValidationStatus.isOK()) - return localValidationStatus; - - if (contactRepositories) - return ProvisioningUtil.validateMetadataRepositoryLocation(location, monitor); - - return localValidationStatus; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/DefaultQueryProvider.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/DefaultQueryProvider.java deleted file mode 100644 index d16e995f3..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/DefaultQueryProvider.java +++ /dev/null @@ -1,189 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * EclipseSource - ongoing development - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.ui; - -import java.net.URI; -import org.eclipse.equinox.internal.p2.ui.model.*; -import org.eclipse.equinox.internal.p2.ui.query.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IUProfilePropertyQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.model.MetadataRepositories; -import org.eclipse.equinox.internal.provisional.p2.ui.model.Updates; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; -import org.eclipse.osgi.util.NLS; -import org.eclipse.ui.statushandlers.StatusManager; - -/** - * Provides a default set of queries to drive the provisioning UI. - * - * @since 3.5 - */ - -public class DefaultQueryProvider extends QueryProvider { - - private Policy policy; - - private Query allQuery = new MatchQuery() { - public boolean isMatch(Object candidate) { - return true; - } - }; - - public DefaultQueryProvider(Policy policy) { - this.policy = policy; - } - - public ElementQueryDescriptor getQueryDescriptor(final QueriedElement element) { - // Initialize queryable, queryContext, and queryType from the element. - // In some cases we override this. - IQueryable queryable = element.getQueryable(); - int queryType = element.getQueryType(); - IUViewQueryContext context = element.getQueryContext(); - if (context == null) { - context = policy.getQueryContext(); - } - switch (queryType) { - case QueryProvider.ARTIFACT_REPOS : - queryable = new QueryableArtifactRepositoryManager(context, false); - return new ElementQueryDescriptor(queryable, new RepositoryLocationQuery(), new Collector() { - public boolean accept(Object object) { - if (object instanceof URI) - return super.accept(new ArtifactRepositoryElement(element, (URI) object)); - return true; - } - }); - - case QueryProvider.AVAILABLE_IUS : - // Things get more complicated if the user wants to filter out installed items. - // This involves setting up a secondary query for installed content that the various - // collectors will use to reject content. We can't use a compound query because the - // queryables are different (profile for installed content, repo for available content) - AvailableIUWrapper availableIUWrapper; - boolean showLatest = context.getShowLatestVersionsOnly(); - boolean hideInstalled = context.getHideAlreadyInstalled(); - IProfile targetProfile = null; - String profileId = context.getInstalledProfileId(); - if (profileId != null) { - try { - targetProfile = ProvisioningUtil.getProfile(profileId); - } catch (ProvisionException e) { - // just bail out, we won't try to query the installed - } - } - - Query topLevelQuery = new IUPropertyQuery(context.getVisibleAvailableIUProperty(), Boolean.TRUE.toString()); - Query categoryQuery = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_CATEGORY, Boolean.toString(true)); - - // Showing child IU's of a group of repositories, or of a single repository - if (element instanceof MetadataRepositories || element instanceof MetadataRepositoryElement) { - if (context.getViewType() == IUViewQueryContext.AVAILABLE_VIEW_FLAT || !context.getUseCategories()) { - AvailableIUWrapper wrapper = new AvailableIUWrapper(queryable, element, false, context.getShowAvailableChildren()); - if (showLatest) - topLevelQuery = new CompositeQuery(new Query[] {topLevelQuery, new LatestIUVersionQuery()}); - if (targetProfile != null) - wrapper.markInstalledIUs(targetProfile, hideInstalled); - return new ElementQueryDescriptor(queryable, topLevelQuery, new Collector(), wrapper); - } - // Installed content not a concern for collecting categories - return new ElementQueryDescriptor(queryable, categoryQuery, new Collector(), new CategoryElementWrapper(queryable, element)); - } - - // If it's a category or some other IUElement to drill down in, we get the requirements and show all requirements - // that are also visible in the available list. - if (element instanceof CategoryElement || (element instanceof IIUElement && ((IIUElement) element).shouldShowChildren())) { - // children of a category should drill down according to the context. If we aren't in a category, we are already drilling down and - // continue to do so. - boolean drillDown = element instanceof CategoryElement ? context.getShowAvailableChildren() : true; - Query meetsAnyRequirementQuery = new AnyRequiredCapabilityQuery(((IIUElement) element).getRequirements()); - availableIUWrapper = new AvailableIUWrapper(queryable, element, true, drillDown); - if (targetProfile != null) - availableIUWrapper.markInstalledIUs(targetProfile, hideInstalled); - // if it's a category, the metadata was specifically set up so that the requirements are the IU's that should - // be visible in the category. - if (element instanceof CategoryElement) { - if (showLatest) - meetsAnyRequirementQuery = new CompositeQuery(new Query[] {meetsAnyRequirementQuery, new LatestIUVersionQuery()}); - return new ElementQueryDescriptor(queryable, meetsAnyRequirementQuery, new Collector(), availableIUWrapper); - } - Query query = CompoundQuery.createCompoundQuery(new Query[] {topLevelQuery, meetsAnyRequirementQuery}, true); - if (showLatest) - query = new CompositeQuery(new Query[] {query, new LatestIUVersionQuery()}); - // If it's not a category, these are generic requirements and should be filtered by the visibility property (topLevelQuery) - return new ElementQueryDescriptor(queryable, query, new Collector(), availableIUWrapper); - } - return null; - - case QueryProvider.AVAILABLE_UPDATES : - // This query can be used by the automatic updater in headless cases (checking for updates). - // We traffic in IU's rather than wrapped elements - IProfile profile; - IInstallableUnit[] toUpdate = null; - if (element instanceof Updates) { - try { - profile = ProvisioningUtil.getProfile(((Updates) element).getProfileId()); - } catch (ProvisionException e) { - ProvUI.handleException(e, NLS.bind(ProvUIMessages.DefaultQueryProvider_ErrorRetrievingProfile, ((Updates) element).getProfileId()), StatusManager.LOG); - return null; - } - toUpdate = ((Updates) element).getIUs(); - } else { - profile = (IProfile) ProvUI.getAdapter(element, IProfile.class); - } - if (profile == null) - return null; - if (toUpdate == null) { - Collector collector = profile.query(new IUProfilePropertyQuery(context.getVisibleInstalledIUProperty(), Boolean.toString(true)), new Collector(), null); - toUpdate = (IInstallableUnit[]) collector.toArray(IInstallableUnit.class); - } - QueryableUpdates updateQueryable = new QueryableUpdates(toUpdate); - return new ElementQueryDescriptor(updateQueryable, context.getShowLatestVersionsOnly() ? new LatestIUVersionQuery() : allQuery, new Collector()); - - case QueryProvider.INSTALLED_IUS : - // Querying of IU's. We are drilling down into the requirements. - if (element instanceof IIUElement && context.getShowInstallChildren()) { - Query meetsAnyRequirementQuery = new AnyRequiredCapabilityQuery(((IIUElement) element).getRequirements()); - Query visibleAsAvailableQuery = new IUPropertyQuery(context.getVisibleAvailableIUProperty(), Boolean.TRUE.toString()); - return new ElementQueryDescriptor(queryable, CompoundQuery.createCompoundQuery(new Query[] {visibleAsAvailableQuery, meetsAnyRequirementQuery}, true), new Collector(), new InstalledIUElementWrapper(queryable, element)); - } - profile = (IProfile) ProvUI.getAdapter(element, IProfile.class); - if (profile == null) - return null; - return new ElementQueryDescriptor(profile, new IUProfilePropertyQuery(context.getVisibleInstalledIUProperty(), Boolean.toString(true)), new Collector(), new InstalledIUElementWrapper(profile, element)); - - case QueryProvider.METADATA_REPOS : - if (element instanceof MetadataRepositories) { - if (queryable == null) { - queryable = new QueryableMetadataRepositoryManager(context, ((MetadataRepositories) element).getIncludeDisabledRepositories()); - element.setQueryable(queryable); - } - return new ElementQueryDescriptor(element.getQueryable(), new RepositoryLocationQuery(), new Collector(), new MetadataRepositoryElementWrapper(element.getQueryable(), element)); - } - return null; - - case QueryProvider.PROFILES : - queryable = new QueryableProfileRegistry(); - return new ElementQueryDescriptor(queryable, new MatchQuery() { - public boolean isMatch(Object candidate) { - return ProvUI.getAdapter(candidate, IProfile.class) != null; - } - }, new Collector(), new ProfileElementWrapper(null, element)); - - default : - return null; - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ElementQueryDescriptor.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ElementQueryDescriptor.java new file mode 100644 index 000000000..bed3a86cd --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ElementQueryDescriptor.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * EclipseSource - ongoing development + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui; + +import java.util.Collection; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.equinox.p2.query.*; + +/** + * ElementQueryDescriptor represents everything needed to run a query, including + * the object to be queried, the query to use, and the query result. It can optionally + * wrap the query results in a UI element. + * + * @since 3.4 + */ +public class ElementQueryDescriptor { + + private IQuery query; + private Collector collector; + private IQueryable queryable; + private ElementWrapper wrapper; + + /** + * Creates an ElementQueryDescriptor to represent a Query, its collector the queryable + * on which it will run. + */ + public ElementQueryDescriptor(IQueryable queryable, IQuery query, Collector collector) { + this(queryable, query, collector, null); + } + + /** + * Creates an ElementQueryDescriptor to represent a Query, its collector the queryable + * on which it will run, and the transformer used to transform the results. + */ + @SuppressWarnings("unchecked") + public ElementQueryDescriptor(IQueryable queryable, IQuery query, Collector collector, ElementWrapper wrapper) { + this.query = (IQuery) query; + this.collector = (Collector) collector; + this.queryable = (IQueryable) queryable; + this.wrapper = wrapper; + } + + /** + * Performs the query returning a collection of results. + * @param monitor + */ + public Collection performQuery(IProgressMonitor monitor) { + Collector results = this.collector; + // If the query is completely described, perform it + if (query != null && collector != null && queryable != null) + results.addAll(this.queryable.query(this.query, monitor)); + else if (results == null) + results = new Collector(); + // Let the wrapper analyze the results, even if we didn't perform the query. + // This allows the wrapper to modify the results with explanations. + if (wrapper != null) + return wrapper.getElements(results); + return results.unmodifiableSet(); + } + + public boolean hasCollector() { + return this.collector != null; + } + + public boolean hasQueryable() { + return this.queryable != null; + } + + public boolean hasQuery() { + return this.query != null; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ElementWrapper.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ElementWrapper.java new file mode 100644 index 000000000..df4ebf7ca --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ElementWrapper.java @@ -0,0 +1,58 @@ +/******************************************************************************* +* Copyright (c) 2009 EclipseSource and others. All rights reserved. This +* program and the accompanying materials are made available under the terms of +* the Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: +* EclipseSource - initial API and implementation +* IBM Corporation - ongoing development +******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui; + +import java.util.*; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; +import org.eclipse.equinox.p2.query.Collector; + +/** + * Wraps query results inside corresponding UI elements + */ +public abstract class ElementWrapper { + + private Collection collection = null; + + /** + * Transforms a collector returned by a query to a collection + * of UI elements + */ + public Collection getElements(Collector collector) { + collection = new ArrayList(collector.size()); + Iterator iter = collector.iterator(); + while (iter.hasNext()) { + Object o = iter.next(); + if (shouldWrap(o)) + collection.add(wrap(o)); + } + return getCollection(); + } + + /** + * Gets the collection where the elements are being stored. + */ + protected Collection getCollection() { + return collection == null ? CollectionUtils.emptyList() : collection; + } + + /** + * Determines if this object should be accepted and wrapped + * by a UI element. + */ + protected boolean shouldWrap(Object o) { + return true; + } + + /** + * Wraps a single element of the query result inside a UI element. + */ + protected abstract Object wrap(Object item); +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/IProvHelpContextIds.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/IProvHelpContextIds.java new file mode 100644 index 000000000..4a11ad1e3 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/IProvHelpContextIds.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui; + + +/** + * Help context ids for the P2 UI + *

    + * This interface contains constants only; it is not intended to be implemented + * or extended. + *

    + * @since 3.4 + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + */ + +public interface IProvHelpContextIds { + public static final String PREFIX = ProvUIActivator.PLUGIN_ID + "."; //$NON-NLS-1$ + + public static final String REVERT_CONFIGURATION_WIZARD = PREFIX + "revert_configuration_wizard_context"; //$NON-NLS-1$ + + public static final String UNINSTALL_WIZARD = PREFIX + "uinstall_wizard_context"; //$NON-NLS-1$ + + public static final String UPDATE_WIZARD = PREFIX + "update_wizard_context"; //$NON-NLS-1$ + + public static final String ADD_REPOSITORY_DIALOG = PREFIX + "add_repository_dialog_context"; //$NON-NLS-1$ + + public static final String INSTALL_WIZARD = PREFIX + "install_wizard_context"; //$NON-NLS-1$ + + public static final String REPOSITORY_MANIPULATION_DIALOG = PREFIX + "repository_manipulation_dialog_context"; //$NON-NLS-1$ + + public static final String INSTALLED_SOFTWARE = PREFIX + "installed_software_context"; //$NON-NLS-1$ + + public static final String AVAILABLE_SOFTWARE = PREFIX + "available_software_context"; //$NON-NLS-1$ + +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/PlanAnalyzer.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/PlanAnalyzer.java deleted file mode 100644 index a4fed80a4..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/PlanAnalyzer.java +++ /dev/null @@ -1,179 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - ******************************************************************************/ - -package org.eclipse.equinox.internal.p2.ui; - -import java.util.Iterator; -import java.util.Map; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.PlatformUI; - -/** - * This class analyzes a profile change request and the resultant provisioning plan, - * and reports problems in a way that can be communicated to a user. - * - * @since 3.5 - */ -public class PlanAnalyzer { - - public static IStatus getStatus(int statusCode, IInstallableUnit affectedIU) { - switch (statusCode) { - case IStatusCodes.PROFILE_CHANGE_ALTERED : - return new MultiStatus(ProvUIActivator.PLUGIN_ID, statusCode, ProvUIMessages.PlanStatusHelper_RequestAltered, null); - case IStatusCodes.ALTERED_IMPLIED_UPDATE : - return new Status(IStatus.INFO, ProvUIActivator.PLUGIN_ID, statusCode, NLS.bind(ProvUIMessages.PlanStatusHelper_ImpliedUpdate, getIUString(affectedIU)), null); - case IStatusCodes.ALTERED_IGNORED_IMPLIED_UPDATE : - return new Status(IStatus.WARNING, ProvUIActivator.PLUGIN_ID, statusCode, NLS.bind(ProvUIMessages.PlanAnalyzer_LockedImpliedUpdate0, getIUString(affectedIU)), null); - case IStatusCodes.ALTERED_IGNORED_IMPLIED_DOWNGRADE : - return new Status(IStatus.WARNING, ProvUIActivator.PLUGIN_ID, statusCode, NLS.bind(ProvUIMessages.PlanStatusHelper_IgnoringImpliedDowngrade, getIUString(affectedIU)), null); - case IStatusCodes.ALTERED_IGNORED_ALREADY_INSTALLED : - return new Status(IStatus.WARNING, ProvUIActivator.PLUGIN_ID, statusCode, NLS.bind(ProvUIMessages.PlanStatusHelper_AlreadyInstalled, getIUString(affectedIU)), null); - case IStatusCodes.ALTERED_PARTIAL_INSTALL : - return new Status(IStatus.INFO, ProvUIActivator.PLUGIN_ID, statusCode, NLS.bind(ProvUIMessages.PlanAnalyzer_PartialInstall, getIUString(affectedIU)), null); - case IStatusCodes.ALTERED_PARTIAL_UNINSTALL : - return new Status(IStatus.INFO, ProvUIActivator.PLUGIN_ID, statusCode, NLS.bind(ProvUIMessages.PlanAnalyzer_PartialUninstall, getIUString(affectedIU)), null); - case IStatusCodes.UNEXPECTED_NOTHING_TO_DO : - return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, statusCode, NLS.bind(ProvUIMessages.PlanStatusHelper_NothingToDo, getIUString(affectedIU)), null); - case IStatusCodes.NOTHING_TO_UPDATE : - return new Status(IStatus.INFO, ProvUIActivator.PLUGIN_ID, statusCode, ProvUIMessages.UpdateOperation_NothingToUpdate, null); - case IStatusCodes.OPERATION_ALREADY_IN_PROGRESS : - return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, statusCode, ProvUIMessages.PlanStatusHelper_AnotherOperationInProgress, null); - default : - return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, statusCode, NLS.bind(ProvUIMessages.PlanStatusHelper_UnexpectedError, new Integer(statusCode), getIUString(affectedIU)), null); - } - } - - public static MultiStatus getProfileChangeAlteredStatus() { - return (MultiStatus) getStatus(IStatusCodes.PROFILE_CHANGE_ALTERED, null); - } - - public static ResolutionResult computeResolutionResult(ProfileChangeRequest originalRequest, ProvisioningPlan plan, MultiStatus originalStatus) { - Assert.isNotNull(originalRequest); - Assert.isNotNull(plan); - Assert.isNotNull(originalStatus); - - ResolutionResult report = new ResolutionResult(); - - // If the plan was canceled, no further analysis is needed - if (plan.getStatus().getSeverity() == IStatus.CANCEL) { - report.addSummaryStatus(plan.getStatus()); - return report; - } - - // If the plan requires install handler support, we want to open the old update UI and - // cancel this operation - if (UpdateManagerCompatibility.requiresInstallHandlerSupport(plan)) { - PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { - public void run() { - Shell shell = ProvUI.getDefaultParentShell(); - MessageDialog dialog = new MessageDialog(shell, ProvUIMessages.PlanStatusHelper_UpdateManagerPromptTitle, null, ProvUIMessages.PlanStatusHelper_PromptForUpdateManagerUI, MessageDialog.WARNING, new String[] {ProvUIMessages.PlanStatusHelper_Launch, IDialogConstants.CANCEL_LABEL}, 0); - if (dialog.open() == 0) - BusyIndicator.showWhile(shell.getDisplay(), new Runnable() { - public void run() { - UpdateManagerCompatibility.openInstaller(); - } - }); - } - }); - report.addSummaryStatus(new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.PlanStatusHelper_RequiresUpdateManager)); - } - - if (nothingToDo(originalRequest)) { - report.addSummaryStatus(getStatus(IStatusCodes.UNEXPECTED_NOTHING_TO_DO, null)); - IStatus[] details = originalStatus.getChildren(); - for (int i = 0; i < details.length; i++) - report.addSummaryStatus(details[i]); - return report; - } - - // If there was already some status supplied before resolution, this should get included - // with the report. For example, this might contain information about the profile request - // being altered before resolution began. - if (originalStatus != null && originalStatus.getChildren().length > 0) { - report.addSummaryStatus(originalStatus); - } - - // If the overall plan had a non-OK status, capture that in the report. - if (!plan.getStatus().isOK()) - report.addSummaryStatus(plan.getStatus()); - - // Now we compare what was requested with what is going to happen. - // In the long run, when a RequestStatus can provide actual explanation/status - // about failures, we might want to add this information to the overall status. - // As it stands now, if the provisioning plan is in error, that info is more detailed - // than the request status. So we will only add request status info to the overall - // status when the overall status is not in error. - if (plan.getStatus().getSeverity() != IStatus.ERROR) { - IInstallableUnit[] iusAdded = originalRequest.getAddedInstallableUnits(); - for (int i = 0; i < iusAdded.length; i++) { - RequestStatus rs = plan.getRequestStatus(iusAdded[i]); - if (rs.getSeverity() == IStatus.ERROR) { - // This is a serious error so it must also appear in the overall status - IStatus fail = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, IStatusCodes.ALTERED_IGNORED_INSTALL_REQUEST, NLS.bind(ProvUIMessages.PlanAnalyzer_IgnoringInstall, getIUString(iusAdded[i])), null); - report.addStatus(iusAdded[i], fail); - report.addSummaryStatus(fail); - } - } - IInstallableUnit[] iusRemoved = originalRequest.getRemovedInstallableUnits(); - for (int i = 0; i < iusRemoved.length; i++) { - RequestStatus rs = plan.getRequestStatus(iusRemoved[i]); - if (rs.getSeverity() == IStatus.ERROR) { - // TODO see https://bugs.eclipse.org/bugs/show_bug.cgi?id=255984 - // We are making assumptions here about why the planner chose to ignore an uninstall. - // Assume it could not be uninstalled because of some other dependency, yet the planner did not view - // this as an error. So we inform the user that we can only uninstall parts of it. The root property will be - // removed per the original change request. - IStatus fail = new Status(IStatus.INFO, ProvUIActivator.PLUGIN_ID, IStatusCodes.ALTERED_PARTIAL_UNINSTALL, NLS.bind(ProvUIMessages.PlanAnalyzer_PartialUninstall, getIUString(iusRemoved[i])), null); - report.addStatus(iusRemoved[i], fail); - report.addSummaryStatus(fail); - } - } - } - - // Now process the side effects - Map sideEffects = plan.getSideEffectChanges(); - Iterator iusWithSideEffects = sideEffects.keySet().iterator(); - while (iusWithSideEffects.hasNext()) { - IInstallableUnit iu = (IInstallableUnit) iusWithSideEffects.next(); - RequestStatus rs = (RequestStatus) sideEffects.get(iu); - if (rs.getInitialRequestType() == RequestStatus.ADDED) { - report.addStatus(iu, new Status(rs.getSeverity(), ProvUIActivator.PLUGIN_ID, IStatusCodes.ALTERED_SIDE_EFFECT_INSTALL, NLS.bind(ProvUIMessages.PlanAnalyzer_SideEffectInstall, getIUString(iu)), null)); - } else { - report.addStatus(iu, new Status(rs.getSeverity(), ProvUIActivator.PLUGIN_ID, IStatusCodes.ALTERED_SIDE_EFFECT_REMOVE, NLS.bind(ProvUIMessages.PlanAnalyzer_SideEffectUninstall, getIUString(iu)), null)); - } - } - - return report; - - } - - private static String getIUString(IInstallableUnit iu) { - if (iu == null) - return ProvUIMessages.PlanStatusHelper_Items; - // Get the iu name in the default locale - String name = IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_NAME); - if (name != null) - return name; - return iu.getId(); - } - - private static boolean nothingToDo(ProfileChangeRequest request) { - return request.getAddedInstallableUnits().length == 0 && request.getRemovedInstallableUnits().length == 0 && request.getInstallableUnitProfilePropertiesToAdd().size() == 0 && request.getInstallableUnitProfilePropertiesToRemove().size() == 0; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUI.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUI.java new file mode 100644 index 000000000..d8417a094 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUI.java @@ -0,0 +1,248 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui; + +import org.eclipse.core.commands.*; +import org.eclipse.core.commands.common.NotDefinedException; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.ui.dialogs.ILayoutConstants; +import org.eclipse.equinox.internal.p2.ui.query.IUViewQueryContext; +import org.eclipse.equinox.internal.p2.ui.viewers.IUColumnConfig; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.CategoryQuery; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.ui.Policy; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.*; +import org.eclipse.ui.commands.ICommandService; +import org.eclipse.ui.handlers.IHandlerService; +import org.eclipse.ui.statushandlers.StatusManager; + +/** + * Generic provisioning UI utility and policy methods. + * + * @since 3.4 + */ +public class ProvUI { + + // Public constants for common command and tooltip names + public static final String INSTALL_COMMAND_LABEL = ProvUIMessages.InstallIUCommandLabel; + public static final String INSTALL_COMMAND_TOOLTIP = ProvUIMessages.InstallIUCommandTooltip; + public static final String UNINSTALL_COMMAND_LABEL = ProvUIMessages.UninstallIUCommandLabel; + public static final String UNINSTALL_COMMAND_TOOLTIP = ProvUIMessages.UninstallIUCommandTooltip; + public static final String UPDATE_COMMAND_LABEL = ProvUIMessages.UpdateIUCommandLabel; + public static final String UPDATE_COMMAND_TOOLTIP = ProvUIMessages.UpdateIUCommandTooltip; + public static final String REVERT_COMMAND_LABEL = ProvUIMessages.RevertIUCommandLabel; + public static final String REVERT_COMMAND_TOOLTIP = ProvUIMessages.RevertIUCommandTooltip; + + private static IUColumnConfig[] columnConfig; + private static QueryProvider queryProvider; + + // These values rely on the command markup in org.eclipse.ui.ide that defines the update commands + private static final String UPDATE_MANAGER_FIND_AND_INSTALL = "org.eclipse.ui.update.findAndInstallUpdates"; //$NON-NLS-1$ + private static final String UPDATE_MANAGER_MANAGE_CONFIGURATION = "org.eclipse.ui.update.manageConfiguration"; //$NON-NLS-1$ + // This value relies on the command markup in org.eclipse.ui + private static final String INSTALLATION_DIALOG = "org.eclipse.ui.help.installationDialog"; //$NON-NLS-1$ + + public static IStatus handleException(Throwable t, String message, int style) { + if (message == null && t != null) { + message = t.getMessage(); + } + IStatus status = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, 0, message, t); + StatusManager.getManager().handle(status, style); + return status; + } + + public static void reportStatus(IStatus status, int style) { + // workaround for + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=211933 + // Note we'd rather have a proper looking dialog than get the + // blocking right. + if ((style & StatusManager.BLOCK) == StatusManager.BLOCK || (style & StatusManager.SHOW) == StatusManager.SHOW) { + if (status.getSeverity() == IStatus.INFO) { + MessageDialog.openInformation(ProvUI.getDefaultParentShell(), ProvUIMessages.ProvUI_InformationTitle, status.getMessage()); + // unset the dialog bits + style = style & ~StatusManager.BLOCK; + style = style & ~StatusManager.SHOW; + // unset logging for statuses that should never be logged. + // Ideally the caller would do this but this bug keeps coming back. + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=274074 + if (status.getCode() == ProvisioningSession.STATUS_NOTHING_TO_UPDATE) + style = 0; + } else if (status.getSeverity() == IStatus.WARNING) { + MessageDialog.openWarning(ProvUI.getDefaultParentShell(), ProvUIMessages.ProvUI_WarningTitle, status.getMessage()); + // unset the dialog bits + style = style & ~StatusManager.BLOCK; + style = style & ~StatusManager.SHOW; + } + } + if (style != 0) + StatusManager.getManager().handle(status, style); + } + + public static IUColumnConfig[] getIUColumnConfig() { + if (columnConfig == null) + columnConfig = new IUColumnConfig[] {new IUColumnConfig(ProvUIMessages.ProvUI_NameColumnTitle, IUColumnConfig.COLUMN_NAME, ILayoutConstants.DEFAULT_PRIMARY_COLUMN_WIDTH), new IUColumnConfig(ProvUIMessages.ProvUI_VersionColumnTitle, IUColumnConfig.COLUMN_VERSION, ILayoutConstants.DEFAULT_COLUMN_WIDTH)}; + return columnConfig; + + } + + public static IUViewQueryContext getQueryContext(Policy policy) { + IUViewQueryContext queryContext = new IUViewQueryContext(policy.getGroupByCategory() ? IUViewQueryContext.AVAILABLE_VIEW_BY_CATEGORY : IUViewQueryContext.AVAILABLE_VIEW_FLAT); + queryContext.setShowLatestVersionsOnly(policy.getShowLatestVersionsOnly()); + queryContext.setShowInstallChildren(policy.getShowDrilldownRequirements()); + queryContext.setShowProvisioningPlanChildren(policy.getShowDrilldownRequirements()); + queryContext.setUseCategories(policy.getGroupByCategory()); + return queryContext; + } + + @SuppressWarnings("unchecked") + public static T getAdapter(Object object, Class adapterType) { + if (object == null) + return null; + if (adapterType.isInstance(object)) + // Ideally, we would use Class.cast here but it was introduced in Java 1.5 + return (T) object; + if (object instanceof IAdaptable) + // Ideally, we would use Class.cast here but it was introduced in Java 1.5 + return (T) ((IAdaptable) object).getAdapter(adapterType); + return null; + } + + /** + * Returns a shell that is appropriate to use as the parent + * for a modal dialog. This returns the existing modal dialog, if any, + * or a workbench window if no modal dialogs open. Returns null + * if there is no appropriate default parent. + * + * This method is copied from ProgressManagerUtil#getDefaultParent() + */ + public static Shell getDefaultParentShell() { + IWorkbench workbench = PlatformUI.getWorkbench(); + + //look first for the topmost modal shell + Shell shell = getDefaultParentShell(workbench.getDisplay().getShells()); + + if (shell != null) { + return shell; + } + + //try the active workbench window + IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); + if (window != null) + return window.getShell(); + IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows(); + if (windows.length > 0) + return windows[0].getShell(); + //there is no modal shell and no active window, so just return a null parent shell + return null; + } + + /** + * Return the modal shell that is currently open. If there isn't one then + * return null. + * + * @param shells shells to search for modal children + * @return the most specific modal child, or null if none + * + * This method is copied from ProgressManagerUtil#getDefaultParent() + */ + + private static Shell getDefaultParentShell(Shell[] shells) { + //first look for a modal shell + for (int i = shells.length - 1; i >= 0; i--) { + Shell shell = shells[i]; + + // Check if this shell has a modal child + Shell modalChild = getDefaultParentShell(shell.getShells()); + if (modalChild != null) { + return modalChild; + } + + // Do not worry about shells that will not block the user. + if (shell.isVisible()) { + int modal = SWT.APPLICATION_MODAL | SWT.SYSTEM_MODAL | SWT.PRIMARY_MODAL; + if ((shell.getStyle() & modal) != 0) { + return shell; + } + } + } + return null; + } + + public static void addProvisioningListener(ProvUIProvisioningListener listener) { + ProvUIActivator.getDefault().addProvisioningListener(listener); + } + + public static void removeProvisioningListener(ProvUIProvisioningListener listener) { + ProvUIActivator.getDefault().removeProvisioningListener(listener); + } + + public static void openUpdateManagerInstaller(Event event) { + runCommand(UPDATE_MANAGER_FIND_AND_INSTALL, ProvUIMessages.UpdateManagerCompatibility_UnableToOpenFindAndInstall, event); + } + + public static void openUpdateManagerConfigurationManager(Event event) { + runCommand(UPDATE_MANAGER_MANAGE_CONFIGURATION, ProvUIMessages.UpdateManagerCompatibility_UnableToOpenManageConfiguration, event); + } + + public static void openInstallationDialog(Event event) { + runCommand(INSTALLATION_DIALOG, ProvUIMessages.ProvUI_InstallDialogError, event); + } + + public static QueryProvider getQueryProvider() { + if (queryProvider == null) + queryProvider = new QueryProvider(ProvUIActivator.getDefault().getProvisioningUI()); + return queryProvider; + } + + private static void runCommand(String commandId, String errorMessage, Event event) { + ICommandService commandService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class); + Command command = commandService.getCommand(commandId); + if (!command.isDefined()) { + return; + } + IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); + try { + handlerService.executeCommand(commandId, event); + } catch (ExecutionException e) { + reportFail(errorMessage, e); + } catch (NotDefinedException e) { + reportFail(errorMessage, e); + } catch (NotEnabledException e) { + reportFail(errorMessage, e); + } catch (NotHandledException e) { + reportFail(errorMessage, e); + } + } + + public static boolean isCategory(IInstallableUnit iu) { + return CategoryQuery.isCategory(iu); + } + + private static void reportFail(String message, Throwable t) { + Status failStatus = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, message, t); + reportStatus(failStatus, StatusManager.BLOCK | StatusManager.LOG); + } + + /** + * For testing only + * @noreference + * @param provider + */ + public static void setQueryProvider(QueryProvider provider) { + queryProvider = provider; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIActivator.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIActivator.java index 04a5498d2..f049f96ce 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIActivator.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIActivator.java @@ -11,14 +11,15 @@ package org.eclipse.equinox.internal.p2.ui; import java.net.URL; -import java.util.EventObject; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.core.eventbus.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.ui.Policy; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.ui.plugin.AbstractUIPlugin; @@ -36,10 +37,11 @@ public class ProvUIActivator extends AbstractUIPlugin { private static PackageAdmin packageAdmin = null; private static ServiceReference packageAdminRef = null; private static ProvUIActivator plugin; - private ProvisioningListener profileChangeListener; - public static final String PLUGIN_ID = "org.eclipse.equinox.p2.ui"; //$NON-NLS-1$ + private ProvisioningSession session; + private ProvisioningUI ui; + public static BundleContext getContext() { return context; } @@ -85,71 +87,41 @@ public class ProvUIActivator extends AbstractUIPlugin { packageAdminRef = bundleContext.getServiceReference(PackageAdmin.class.getName()); packageAdmin = (PackageAdmin) bundleContext.getService(packageAdminRef); + initializeProvisioningUI(); + } + + private void initializeProvisioningUI() { // TODO for now we need to manually start up the provisioning infrastructure // because the Eclipse Application launch config won't let me specify bundles to start. - getBundle("org.eclipse.equinox.p2.exemplarysetup").start(Bundle.START_TRANSIENT); //$NON-NLS-1$ - getBundle("org.eclipse.equinox.frameworkadmin.equinox").start(Bundle.START_TRANSIENT); //$NON-NLS-1$ - getBundle("org.eclipse.equinox.simpleconfigurator.manipulator").start(Bundle.START_TRANSIENT); //$NON-NLS-1$ + try { + getBundle("org.eclipse.equinox.p2.exemplarysetup").start(Bundle.START_TRANSIENT); //$NON-NLS-1$ + } catch (BundleException e) { + ProvUI.handleException(e, "Error initializing provisioning UI", StatusManager.LOG); //$NON-NLS-1$ + } + IProvisioningAgent agent = (IProvisioningAgent) ServiceHelper.getService(getContext(), IProvisioningAgent.class.getName()); + session = new ProvisioningSession(agent); - addProfileChangeListener(); + Policy policy = (Policy) ServiceHelper.getService(ProvUIActivator.getContext(), Policy.class.getName()); + if (policy == null) + policy = new Policy(); + + ui = new ProvisioningUI(session, IProfileRegistry.SELF, policy); } public void stop(BundleContext bundleContext) throws Exception { try { - removeProfileChangeListener(); plugin = null; ProvUIActivator.context = null; + ui = null; } finally { super.stop(bundleContext); } } - private void addProfileChangeListener() { - if (profileChangeListener == null) { - profileChangeListener = new SynchronousProvisioningListener() { - public void notify(EventObject o) { - if (o instanceof ProfileEvent) { - ProfileEvent event = (ProfileEvent) o; - try { - IProfile selfProfile = ProvisioningUtil.getProfile(IProfileRegistry.SELF); - if (selfProfile != null && (selfProfile.getProfileId().equals(event.getProfileId()))) { - if (event.getReason() == ProfileEvent.CHANGED) - ProvisioningOperationRunner.requestRestart(false); - - } - } catch (ProvisionException e) { - ProvUI.handleException(e, ProvUIMessages.ProvUIActivator_ExceptionDuringProfileChange, StatusManager.LOG); - - } - } - } - }; - } - IProvisioningEventBus bus = getProvisioningEventBus(); - if (bus != null) - bus.addListener(profileChangeListener); - } - - private void removeProfileChangeListener() { - if (profileChangeListener != null) { - IProvisioningEventBus bus = getProvisioningEventBus(); - if (bus != null) - bus.removeListener(profileChangeListener); - } - } - public void addProvisioningListener(ProvUIProvisioningListener listener) { getProvisioningEventBus().addListener(listener); } - public void signalBatchOperationStart() { - getProvisioningEventBus().publishEvent(new BatchChangeBeginningEvent(this)); - } - - public void signalBatchOperationComplete(boolean notify) { - getProvisioningEventBus().publishEvent(new BatchChangeCompleteEvent(this, notify)); - } - public IProvisioningEventBus getProvisioningEventBus() { ServiceReference busReference = context.getServiceReference(IProvisioningEventBus.SERVICE_NAME); if (busReference == null) @@ -169,10 +141,6 @@ public class ProvUIActivator extends AbstractUIPlugin { createImageDescriptor(ProvUIImages.IMG_UPDATED_IU, reg); createImageDescriptor(ProvUIImages.IMG_CATEGORY, reg); createImageDescriptor(ProvUIImages.IMG_PROFILE, reg); - createImageDescriptor(ProvUIImages.IMG_TOOL_UPDATE, reg); - createImageDescriptor(ProvUIImages.IMG_TOOL_UPDATE_PROBLEMS, reg); - createImageDescriptor(ProvUIImages.IMG_TOOL_CLOSE, reg); - createImageDescriptor(ProvUIImages.IMG_TOOL_CLOSE_HOT, reg); createImageDescriptor(ProvUIImages.WIZARD_BANNER_INSTALL, reg); createImageDescriptor(ProvUIImages.WIZARD_BANNER_REVERT, reg); createImageDescriptor(ProvUIImages.WIZARD_BANNER_UNINSTALL, reg); @@ -187,4 +155,12 @@ public class ProvUIActivator extends AbstractUIPlugin { ImageDescriptor desc = ImageDescriptor.createFromURL(url); reg.put(id, desc); } + + public ProvisioningUI getProvisioningUI() { + return ui; + } + + public ProvisioningSession getSession() { + return session; + } } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIAdapterFactory.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIAdapterFactory.java index 729dad386..922e7390d 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIAdapterFactory.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIAdapterFactory.java @@ -11,12 +11,11 @@ package org.eclipse.equinox.internal.p2.ui; import org.eclipse.core.runtime.IAdapterFactory; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; /** * Adapter factory for provisioning elements @@ -26,13 +25,14 @@ import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; */ public class ProvUIAdapterFactory implements IAdapterFactory { - private static final Class[] CLASSES = new Class[] {IInstallableUnit.class, IProfile.class, IRepository.class, IMetadataRepository.class, IArtifactRepository.class}; + private static final Class[] CLASSES = new Class[] {IInstallableUnit.class, IProfile.class, IRepository.class, IMetadataRepository.class, IArtifactRepository.class}; + @SuppressWarnings({"rawtypes", "unchecked"}) public Object getAdapter(Object adaptableObject, Class adapterType) { return ProvUI.getAdapter(adaptableObject, adapterType); } - public Class[] getAdapterList() { + public Class[] getAdapterList() { return CLASSES; } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIImages.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIImages.java new file mode 100644 index 000000000..40ab3feb6 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIImages.java @@ -0,0 +1,75 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.graphics.Image; + +/** + * ProvUIImages provides convenience methods for accessing shared images + * provided by the org.eclipse.equinox.internal.provisional.p2.ui plug-in. + *

    + * This class provides ImageDescriptors for each named image in + * {@link ProvUIImages}. All Image objects created from the + * provided descriptors are managed the caller and must be disposed + * appropriately. + *

    + *

    + * This class is not intended to be subclassed or instantiated by clients + * + * @since 3.4 + * @noextend This class is not intended to be subclassed by clients. + * @noinstantiate This class is not intended to be instantiated by clients. + */ +public class ProvUIImages { + + // bundle-relative icon path + public final static String ICON_PATH = "$nl$/icons/"; //$NON-NLS-1$ + //objects + public final static String IMG_ARTIFACT_REPOSITORY = "obj/artifact_repo_obj.gif"; //$NON-NLS-1$ + public final static String IMG_METADATA_REPOSITORY = "obj/metadata_repo_obj.gif"; //$NON-NLS-1$ + public final static String IMG_IU = "obj/iu_obj.gif"; //$NON-NLS-1$ + public final static String IMG_DISABLED_IU = "obj/iu_disabled_obj.gif"; //$NON-NLS-1$ + public final static String IMG_UPDATED_IU = "obj/iu_update_obj.gif"; //$NON-NLS-1$ + public final static String IMG_PROFILE = "obj/profile_obj.gif"; //$NON-NLS-1$ + public final static String IMG_CATEGORY = "obj/category_obj.gif"; //$NON-NLS-1$ + + // wizard graphics + public final static String WIZARD_BANNER_INSTALL = "wizban/install_wiz.gif"; //$NON-NLS-1$ + public final static String WIZARD_BANNER_UNINSTALL = "wizban/uninstall_wiz.gif"; //$NON-NLS-1$ + public final static String WIZARD_BANNER_UPDATE = "wizban/update_wiz.gif"; //$NON-NLS-1$ + public final static String WIZARD_BANNER_REVERT = "wizban/revert_wiz.gif"; //$NON-NLS-1$ + + /** + * Returns the image descriptor for the given image ID. Returns + * null if there is no such image. + * + * @param id + * the identifier for the image to retrieve + * @return the image descriptor associated with the given ID + */ + public static ImageDescriptor getImageDescriptor(String id) { + return ProvUIActivator.getDefault().getImageRegistry().getDescriptor(id); + } + + /** + * Returns the image for the given image ID. Returns null if + * there is no such image. + * + * @param id + * the identifier for the image to retrieve + * @return the image associated with the given ID. This image is managed in + * an image registry and should not be freed by the client. + */ + public static Image getImage(String id) { + return ProvUIActivator.getDefault().getImageRegistry().get(id); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIMessages.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIMessages.java index f7f9ac8d3..f8d6d1035 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIMessages.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIMessages.java @@ -38,10 +38,11 @@ public class ProvUIMessages extends NLS { public static String AcceptLicensesWizardPage_Title; public static String ApplicationInRestartDialog; public static String ApplyProfileChangesDialog_ApplyChanges; + public static String ApplyProfileChangesDialog_Restart; + public static String ApplyProfileChangesDialog_NotYet; public static String ColocatedRepositoryManipulator_AddSiteOperationLabel; - public static String ColocatedRepositoryManipulator_GotoPrefs; - public static String ColocatedRepositoryManipulator_ManageSites; - public static String ColocatedRepositoryManipulator_RemoveSiteOperationLabel; + public static String ColocatedRepositoryTracker_PromptForSiteLocationEdit; + public static String ColocatedRepositoryTracker_SiteNotFoundTitle; public static String RevertProfilePage_ConfirmDeleteMultipleConfigs; public static String RevertProfilePage_ConfirmDeleteSingleConfig; public static String RevertProfilePage_Delete; @@ -69,24 +70,9 @@ public class ProvUIMessages extends NLS { public static String IUGeneralInfoPropertyPage_VersionLabel; public static String IULicensePropertyPage_NoLicense; public static String IULicensePropertyPage_ViewLicenseLabel; - public static String ProfileChangeRequestBuildingRequest; - public static String ProfileElement_InvalidProfile; public static String ProfileModificationAction_InvalidSelections; - public static String ProfileModificationAction_NoChangeRequestProvided; - public static String ProfileModificationAction_NoExplanationProvided; - public static String ProfileModificationAction_ResolutionOperationLabel; public static String ProfileModificationWizardPage_DetailsLabel; - public static String ProfileModificationWizardPage_ResolutionOperationLabel; - public static String ProfileModificationWizardPage_UnexpectedError; public static String ProfileSnapshots_Label; - public static String ProvisioningUtil_InstallPlanConfigurationError; - // utility error messages - public static String ProvisioningUtil_NoRepositoryManager; - public static String ProvisioningUtil_LoadRepositoryFailure; - public static String ProvisioningUtil_NoProfileRegistryFound; - public static String ProvisioningUtil_NoPlannerFound; - public static String ProvisioningUtil_NoDirectorFound; - public static String ProvisioningUtil_NoEngineFound; // viewer support public static String ProvDropAdapter_InvalidDropTarget; @@ -96,13 +82,12 @@ public class ProvUIMessages extends NLS { // Provisioning operations public static String ProvisioningOperationRunner_CannotApplyChanges; - public static String ProvisioningOperationRunner_ErrorExecutingOperation; + public static String ProvisioningOperationWizard_UnexpectedFailureToResolve; public static String InstalledSoftwarePage_NoProfile; public static String InstallIUOperationLabel; public static String InstallIUOperationTask; public static String InstallIUCommandLabel; public static String InstallIUCommandTooltip; - public static String InstallIUProgress; public static String InstallWizardPage_NoCheckboxDescription; public static String InstallWizardPage_Title; public static String PreselectedIUInstallWizard_Title; @@ -123,7 +108,6 @@ public class ProvUIMessages extends NLS { public static String RefreshAction_Label; public static String RefreshAction_Tooltip; public static String RemoveColocatedRepositoryAction_Label; - public static String RemoveColocatedRepositoryAction_OperationLabel; public static String RemoveColocatedRepositoryAction_Tooltip; public static String RevertIUCommandLabel; public static String RevertIUCommandTooltip; @@ -164,19 +148,19 @@ public class ProvUIMessages extends NLS { public static String RepositoryManipulatorDropTarget_DragSourceNotValid; public static String RepositoryNameAndLocationDialog_Title; - public static String ResolutionReport_SummaryStatus; + public static String RepositorySelectionGroup_GenericSiteLinkTitle; + public static String RepositorySelectionGroup_PrefPageLink; + public static String RepositorySelectionGroup_PrefPageName; public static String ResolutionWizardPage_Canceled; public static String ResolutionWizardPage_ErrorStatus; public static String ResolutionWizardPage_NoSelections; public static String ResolutionWizardPage_WarningInfoStatus; // Dialogs - public static String AddRepositoryDialog_DuplicateURL; public static String AddRepositoryDialog_InvalidURL; public static String AddRepositoryDialog_LocationLabel; public static String AddRepositoryDialog_NameLabel; public static String AddRepositoryDialog_Title; - public static String AvailableIUElement_ProfileNotFound; public static String AvailableIUGroup_LoadingRepository; public static String AvailableIUGroup_NoSitesConfiguredDescription; public static String AvailableIUGroup_NoSitesConfiguredExplanation; @@ -200,47 +184,28 @@ public class ProvUIMessages extends NLS { public static String AvailableIUsPage_Title; public static String AvailableIUWrapper_AllAreInstalled; public static String IUViewQueryContext_AllAreInstalledDescription; - public static String DefaultQueryProvider_ErrorRetrievingProfile; public static String DeferredFetchFilteredTree_RetrievingList; public static String ElementUtils_UpdateJobTitle; public static String Label_Profiles; public static String Label_Repositories; + public static String LaunchUpdateManagerButton; + public static String LoadMetadataRepositoryJob_ContactSitesProgress; + public static String LoadMetadataRepositoryJob_SitesMissingError; public static String MetadataRepositoryElement_NotFound; public static String MetadataRepositoryElement_RepositoryLoadError; public static String UpdateAction_UpdatesAvailableMessage; public static String UpdateAction_UpdatesAvailableTitle; - public static String PlanAnalyzer_IgnoringInstall; - public static String PlanAnalyzer_LockedImpliedUpdate0; - public static String PlanAnalyzer_PartialInstall; - public static String PlanAnalyzer_PartialUninstall; - public static String PlanAnalyzer_SideEffectInstall; - public static String PlanAnalyzer_SideEffectUninstall; - public static String PlannerResolutionOperation_UnexpectedError; - public static String PlanStatusHelper_IgnoringImpliedDowngrade; - public static String PlanStatusHelper_ImpliedUpdate; - public static String PlanStatusHelper_Items; - public static String PlanStatusHelper_NothingToDo; - public static String PlanStatusHelper_AlreadyInstalled; - public static String PlanStatusHelper_AnotherOperationInProgress; - public static String PlanStatusHelper_Launch; - public static String PlanStatusHelper_RequestAltered; - public static String PlanStatusHelper_RequiresUpdateManager; - public static String PlanStatusHelper_UnexpectedError; - public static String PlanStatusHelper_UpdateManagerPromptTitle; - public static String PlanStatusHelper_PromptForUpdateManagerUI; public static String PlatformUpdateTitle; public static String PlatformRestartMessage; + public static String Policy_RequiresUpdateManagerMessage; + public static String Policy_RequiresUpdateManagerTitle; public static String ProvUI_ErrorDuringApplyConfig; public static String ProvUI_InformationTitle; public static String ProvUI_InstallDialogError; public static String ProvUI_NameColumnTitle; public static String ProvUI_IdColumnTitle; - public static String ProvUI_LoadErrorTitle; - public static String ProvUI_PromptForSiteEdit; public static String ProvUI_VersionColumnTitle; public static String ProvUI_WarningTitle; - public static String ProvUIActivator_ExceptionDuringProfileChange; - public static String ProvUILicenseManager_ParsingError; public static String ProvUIMessages_NotAccepted_EnterFor_0; public static String ProvUIMessages_SavedNotAccepted_EnterFor_0; public static String OptionalPlatformRestartMessage; @@ -248,38 +213,33 @@ public class ProvUIMessages extends NLS { public static String QueriedElementWrapper_NoCategorizedItemsExplanation; public static String QueriedElementWrapper_NoItemsExplanation; public static String QueriedElementWrapper_SiteNotFound; - public static String ColocatedRepositoryManipulator_SiteNotFoundDescription; public static String QueryableMetadataRepositoryManager_LoadRepositoryProgress; public static String QueryableMetadataRepositoryManager_MultipleRepositoriesNotFound; public static String QueryableProfileRegistry_QueryProfileProgress; + public static String QueryableRepositoryManager_LoadFailure; public static String QueryableUpdates_UpdateListProgress; public static String SizeComputingWizardPage_SizeJobTitle; - public static String SizingPhaseSet_PhaseSetName; public static String RevertDialog_ConfigContentsLabel; public static String RevertDialog_ConfigsLabel; public static String RevertDialog_ConfirmRestartMessage; public static String RevertDialog_RevertOperationLabel; public static String RevertDialog_Title; public static String RollbackProfileElement_CurrentInstallation; - public static String RollbackProfileElement_InvalidSnapshot; public static String SelectableIUsPage_Select_All; public static String SelectableIUsPage_Deselect_All; public static String TrustCertificateDialog_Details; public static String TrustCertificateDialog_Title; // Operations - public static String URLValidator_UnrecognizedURL; public static String UpdateManagerCompatibility_ExportSitesTitle; public static String UpdateManagerCompatibility_ImportSitesTitle; public static String UpdateManagerCompatibility_InvalidSiteFileMessage; public static String UpdateManagerCompatibility_InvalidSitesTitle; public static String UpdateManagerCompatibility_UnableToOpenFindAndInstall; public static String UpdateManagerCompatibility_UnableToOpenManageConfiguration; - public static String UpdateOperation_NothingToUpdate; public static String ServiceUI_LoginDetails; public static String ServiceUI_LoginRequired; public static String ServiceUI_unsigned_message; - public static String ServiceUI_unsigned_title; public static String ServiceUI_warning_title; public static String UpdateOrInstallWizardPage_Size; public static String Updates_Label; diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIProvisioningListener.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIProvisioningListener.java new file mode 100644 index 000000000..fa88b20bc --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvUIProvisioningListener.java @@ -0,0 +1,196 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui; + +import java.util.EventObject; +import org.eclipse.equinox.internal.provisional.p2.core.eventbus.SynchronousProvisioningListener; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.engine.ProfileEvent; +import org.eclipse.equinox.p2.repository.IRepository; + +/** + * ProvisioningListener which handles event batching and other + * extensions to the provisioning event framework that are used by + * the UI. + * + * @since 3.5 + */ +public abstract class ProvUIProvisioningListener implements SynchronousProvisioningListener { + + public static final int PROV_EVENT_METADATA_REPOSITORY = 0x0001; + public static final int PROV_EVENT_IU = 0x0002; + public static final int PROV_EVENT_PROFILE = 0x0004; + public static final int PROV_EVENT_ARTIFACT_REPOSITORY = 0x0008; + + int eventTypes = 0; + int batchCount = 0; + + public ProvUIProvisioningListener(int eventTypes) { + this.eventTypes = eventTypes; + } + + public void notify(EventObject o) { + if (o instanceof RepositoryOperationBeginningEvent) { + batchCount++; + } else if (o instanceof RepositoryOperationEndingEvent) { + batchCount--; + // A batch operation completed. Refresh. + if (batchCount <= 0) { + RepositoryOperationEndingEvent event = (RepositoryOperationEndingEvent) o; + if (event.getEvent() == null && event.update()) + refreshAll(); + else if (event.update()) + notify(event.getEvent()); + } + } else if (batchCount > 0) { + // We are in the middle of a batch operation + return; + } else if (o instanceof ProfileEvent && (((eventTypes & PROV_EVENT_IU) == PROV_EVENT_IU) || ((eventTypes & PROV_EVENT_PROFILE) == PROV_EVENT_PROFILE))) { + ProfileEvent event = (ProfileEvent) o; + if (event.getReason() == ProfileEvent.CHANGED) { + profileChanged(event.getProfileId()); + } else if (event.getReason() == ProfileEvent.ADDED) { + profileAdded(event.getProfileId()); + } else if (event.getReason() == ProfileEvent.REMOVED) { + profileRemoved(event.getProfileId()); + } + } else if (o instanceof RepositoryEvent) { + RepositoryEvent event = (RepositoryEvent) o; + // Do not handle unless this is the type of repo that we are interested in + if ((event.getRepositoryType() == IRepository.TYPE_METADATA && (eventTypes & PROV_EVENT_METADATA_REPOSITORY) == PROV_EVENT_METADATA_REPOSITORY) || (event.getRepositoryType() == IRepository.TYPE_ARTIFACT && (eventTypes & PROV_EVENT_ARTIFACT_REPOSITORY) == PROV_EVENT_ARTIFACT_REPOSITORY)) { + if (event.getKind() == RepositoryEvent.ADDED && event.isRepositoryEnabled()) { + repositoryAdded(event); + } else if (event.getKind() == RepositoryEvent.REMOVED && event.isRepositoryEnabled()) { + repositoryRemoved(event); + } else if (event.getKind() == RepositoryEvent.DISCOVERED) { + repositoryDiscovered(event); + } else if (event.getKind() == RepositoryEvent.CHANGED) { + repositoryChanged(event); + } else if (event.getKind() == RepositoryEvent.ENABLEMENT) { + repositoryEnablement(event); + } + } + } + } + + /** + * A repository has been added. Subclasses may override. May be called + * from a non-UI thread. + * + * @param event the RepositoryEvent describing the details + */ + protected void repositoryAdded(RepositoryEvent event) { + // Do nothing. This method is not abstract because subclasses + // may not be interested in repository events at all and should + // not have to implement it. + } + + /** + * A repository has been removed. Subclasses may override. May be called + * from a non-UI thread. + * + * @param event the RepositoryEvent describing the details + */ + protected void repositoryRemoved(RepositoryEvent event) { + // Do nothing. This method is not abstract because subclasses + // may not be interested in repository events at all and should + // not have to implement it. + } + + /** + * A repository has been discovered. Subclasses may override. May be called + * from a non-UI thread. + * + * @param event the RepositoryEvent describing the details + */ + protected void repositoryDiscovered(RepositoryEvent event) { + // Do nothing. This method is not abstract because subclasses + // may not be interested in repository events at all and should + // not have to implement it. + } + + /** + * A repository has changed. Subclasses may override. May be called + * from a non-UI thread. + * + * @param event the RepositoryEvent describing the details + */ + protected void repositoryChanged(RepositoryEvent event) { + // Do nothing. This method is not abstract because subclasses + // may not be interested in repository events at all and should + // not have to implement it. + } + + /** + * A repository's enablement state has changed. This is treated + * as repository addition or removal by default. Subclasses may + * override. May be called from a non-UI thread. + * @param event + */ + protected void repositoryEnablement(RepositoryEvent event) { + // We treat enablement of a repository as if one were added. + if (event.isRepositoryEnabled()) + repositoryAdded(event); + else + repositoryRemoved(event); + } + + /** + * The specified profile has changed. Subclasses may override. May be called + * from a non-UI thread. + * + * @param profileId the id of the profile that changed. + */ + protected void profileChanged(final String profileId) { + // Do nothing. This method is not abstract because subclasses + // may not be interested in profile events at all and should + // not have to implement it. + } + + /** + * The specified profile has been added. Subclasses may override. May be called + * from a non-UI thread. + * + * @param profileId the id of the profile that has been added. + */ + protected void profileAdded(final String profileId) { + // Do nothing. This method is not abstract because subclasses + // may not be interested in profile events at all and should + // not have to implement it. + } + + /** + * The specified profile has been removed. Subclasses may override. May be called + * from a non-UI thread. + * + * @param profileId the id of the profile that has been removed. + */ + protected void profileRemoved(final String profileId) { + // Do nothing. This method is not abstract because subclasses + // may not be interested in profile events at all and should + // not have to implement it. + } + + /** + * An event requiring a complete refresh of the listener's state has + * been received. This is used, for example, when a batch change has + * completed. Subclasses may override. May be called from a non-UI + * thread. + */ + protected void refreshAll() { + // Do nothing by default. + } + + public int getEventTypes() { + return eventTypes; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvisioningOperationRunner.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvisioningOperationRunner.java new file mode 100644 index 000000000..65b907823 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ProvisioningOperationRunner.java @@ -0,0 +1,143 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui; + +import java.io.IOException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.*; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.internal.p2.ui.dialogs.ApplyProfileChangesDialog; +import org.eclipse.equinox.internal.provisional.configurator.Configurator; +import org.eclipse.equinox.p2.operations.ProvisioningJob; +import org.eclipse.equinox.p2.ui.Policy; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.progress.IProgressConstants; +import org.eclipse.ui.statushandlers.StatusManager; + +/** + * Utility methods for running provisioning operations. Operations can either + * be run synchronously or in a job. When scheduled as a job, the operation + * determines whether the job is run in + * the background or in the UI. + * + * @since 3.4 + */ +public class ProvisioningOperationRunner { + + boolean suppressRestart = false; + ProvisioningUI ui; + + public ProvisioningOperationRunner(ProvisioningUI ui) { + this.ui = ui; + } + + /** + * Schedule a job to execute the supplied ProvisioningOperation. + * + * @param job The operation to execute + * @param errorStyle the flags passed to the StatusManager for error reporting + */ + public void schedule(final ProvisioningJob job, final int errorStyle) { + final boolean noPrompt = (errorStyle & (StatusManager.BLOCK | StatusManager.SHOW)) == 0; + if (noPrompt) { + job.setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); + job.setProperty(IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE); + } + job.setProperty(IProgressConstants.ICON_PROPERTY, ProvUIImages.getImageDescriptor(ProvUIImages.IMG_PROFILE)); + manageJob(job, job.getRestartPolicy()); + job.schedule(); + } + + /** + * Request a restart of the platform according to the specified + * restart policy. + * + * @param restartPolicy + */ + private void requestRestart(final int restartPolicy) { + // Global override of restart (used in test cases). + if (suppressRestart) + return; + if (restartPolicy == Policy.RESTART_POLICY_FORCE) { + PlatformUI.getWorkbench().restart(); + return; + } + if (restartPolicy == Policy.RESTART_POLICY_FORCE_APPLY) { + applyProfileChanges(); + return; + } + + PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { + public void run() { + if (PlatformUI.getWorkbench().isClosing()) + return; + int retCode = ApplyProfileChangesDialog.promptForRestart(ProvUI.getDefaultParentShell(), restartPolicy == Policy.RESTART_POLICY_PROMPT); + if (retCode == ApplyProfileChangesDialog.PROFILE_APPLYCHANGES) { + applyProfileChanges(); + } else if (retCode == ApplyProfileChangesDialog.PROFILE_RESTART) { + PlatformUI.getWorkbench().restart(); + } + } + }); + } + + void applyProfileChanges() { + Configurator configurator = (Configurator) ServiceHelper.getService(ProvUIActivator.getContext(), Configurator.class.getName()); + try { + configurator.applyConfiguration(); + } catch (IOException e) { + ProvUI.handleException(e, ProvUIMessages.ProvUI_ErrorDuringApplyConfig, StatusManager.LOG | StatusManager.BLOCK); + } catch (IllegalStateException e) { + IStatus illegalApplyStatus = new Status(IStatus.WARNING, ProvUIActivator.PLUGIN_ID, 0, ProvUIMessages.ProvisioningOperationRunner_CannotApplyChanges, e); + ProvUI.reportStatus(illegalApplyStatus, StatusManager.LOG | StatusManager.BLOCK); + } + } + + public void manageJob(Job job, final int jobRestartPolicy) { + ui.getSession().rememberJob(job); + job.addJobChangeListener(new JobChangeAdapter() { + public void done(IJobChangeEvent event) { + int severity = event.getResult().getSeverity(); + // If the job finished without error, see if restart is needed + if (severity != IStatus.CANCEL && severity != IStatus.ERROR) { + if (jobRestartPolicy == ProvisioningJob.RESTART_NONE) { + return; + } + int globalRestartPolicy = ui.getPolicy().getRestartPolicy(); + // If the global policy allows apply changes, check the job policy to see if it supports it. + if (globalRestartPolicy == Policy.RESTART_POLICY_PROMPT_RESTART_OR_APPLY) { + if (jobRestartPolicy == ProvisioningJob.RESTART_OR_APPLY) + requestRestart(Policy.RESTART_POLICY_PROMPT_RESTART_OR_APPLY); + else + requestRestart(Policy.RESTART_POLICY_PROMPT); + } else + requestRestart(globalRestartPolicy); + } + } + }); + } + + /** + * This method is provided for use in automated test case. It should + * no longer be needed to be used by clients. + * + * @param suppress true to suppress all restarts and false + * to stop suppressing restarts. + * + * @noreference This method is not intended to be referenced by clients. + */ + public void suppressRestart(boolean suppress) { + suppressRestart = suppress; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryProvider.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryProvider.java new file mode 100644 index 000000000..51e516a01 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryProvider.java @@ -0,0 +1,200 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * EclipseSource - ongoing development + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui; + +import java.net.URI; +import java.util.Collection; +import org.eclipse.equinox.internal.p2.metadata.query.LatestIUVersionQuery; +import org.eclipse.equinox.internal.p2.ui.model.*; +import org.eclipse.equinox.internal.p2.ui.query.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; +import org.eclipse.equinox.p2.metadata.expression.*; +import org.eclipse.equinox.p2.metadata.query.*; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.artifact.ArtifactKeyQuery; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.ui.Policy; +import org.eclipse.equinox.p2.ui.ProvisioningUI; + +/** + * Provides a default set of queries to drive the provisioning UI. + * + * @since 3.5 + */ + +public class QueryProvider { + + private ProvisioningUI ui; + + public static final int METADATA_REPOS = 1; + public static final int ARTIFACT_REPOS = 2; + public static final int PROFILES = 3; + public static final int AVAILABLE_IUS = 4; + public static final int AVAILABLE_UPDATES = 5; + public static final int INSTALLED_IUS = 6; + public static final int AVAILABLE_ARTIFACTS = 7; + + private IQuery allQuery = new MatchQuery() { + public boolean isMatch(IInstallableUnit candidate) { + return true; + } + }; + + public QueryProvider(ProvisioningUI ui) { + this.ui = ui; + } + + public ElementQueryDescriptor getQueryDescriptor(final QueriedElement element) { + // Initialize queryable, queryContext, and queryType from the element. + // In some cases we override this. + Policy policy = ui.getPolicy(); + IQueryable queryable = element.getQueryable(); + int queryType = element.getQueryType(); + IUViewQueryContext context = element.getQueryContext(); + if (context == null) { + context = ProvUI.getQueryContext(policy); + } + RepositoryTracker tracker = ui.getRepositoryTracker(); + switch (queryType) { + case ARTIFACT_REPOS : + queryable = new QueryableArtifactRepositoryManager(ui, false).locationsQueriable(); + return new ElementQueryDescriptor(queryable, new RepositoryLocationQuery(), new Collector(), new ArtifactRepositoryElementWrapper(null, element)); + + case AVAILABLE_IUS : + // Things get more complicated if the user wants to filter out installed items. + // This involves setting up a secondary query for installed content that the various + // collectors will use to reject content. We can't use a compound query because the + // queryables are different (profile for installed content, repo for available content) + AvailableIUWrapper availableIUWrapper; + boolean showLatest = context.getShowLatestVersionsOnly(); + boolean hideInstalled = context.getHideAlreadyInstalled(); + IProfile targetProfile = null; + String profileId = context.getInstalledProfileId(); + if (profileId != null) { + targetProfile = ui.getSession().getProfileRegistry().getProfile(profileId); + } + + IQuery topLevelQuery = policy.getVisibleAvailableIUQuery(); + IQuery categoryQuery = new CategoryQuery(); + + // Showing child IU's of a group of repositories, or of a single repository + if (element instanceof MetadataRepositories || element instanceof MetadataRepositoryElement) { + if (context.getViewType() == IUViewQueryContext.AVAILABLE_VIEW_FLAT || !context.getUseCategories()) { + AvailableIUWrapper wrapper = new AvailableIUWrapper(queryable, element, false, context.getShowAvailableChildren()); + if (showLatest) + topLevelQuery = new PipedQuery(topLevelQuery, new LatestIUVersionQuery()); + if (targetProfile != null) + wrapper.markInstalledIUs(targetProfile, hideInstalled); + return new ElementQueryDescriptor(queryable, topLevelQuery, new Collector(), wrapper); + } + // Installed content not a concern for collecting categories + return new ElementQueryDescriptor(queryable, categoryQuery, new Collector(), new CategoryElementWrapper(queryable, element)); + } + + // If it's a category or some other IUElement to drill down in, we get the requirements and show all requirements + // that are also visible in the available list. + if (element instanceof CategoryElement || (element instanceof IIUElement && ((IIUElement) element).shouldShowChildren())) { + // children of a category should drill down according to the context. If we aren't in a category, we are already drilling down and + // continue to do so. + boolean drillDown = element instanceof CategoryElement ? context.getShowAvailableChildren() : true; + IQuery memberOfCategoryQuery = new CategoryMemberQuery(((IIUElement) element).getIU()); + availableIUWrapper = new AvailableIUWrapper(queryable, element, true, drillDown); + if (targetProfile != null) + availableIUWrapper.markInstalledIUs(targetProfile, hideInstalled); + // if it's a category, the metadata was specifically set up so that the requirements are the IU's that should + // be visible in the category. + if (element instanceof CategoryElement) { + if (showLatest) + memberOfCategoryQuery = new PipedQuery(memberOfCategoryQuery, new LatestIUVersionQuery()); + return new ElementQueryDescriptor(queryable, memberOfCategoryQuery, new Collector(), availableIUWrapper); + } + @SuppressWarnings("unchecked") + IQuery query = CompoundQuery.createCompoundQuery(new IQuery[] {topLevelQuery, memberOfCategoryQuery}, true); + if (showLatest) + query = new PipedQuery(query, new LatestIUVersionQuery()); + // If it's not a category, these are generic requirements and should be filtered by the visibility property (topLevelQuery) + return new ElementQueryDescriptor(queryable, query, new Collector(), availableIUWrapper); + } + return null; + + case AVAILABLE_UPDATES : + // This query can be used by the automatic updater in headless cases (checking for updates). + // We traffic in IU's rather than wrapped elements + IProfile profile; + IInstallableUnit[] toUpdate = null; + if (element instanceof Updates) { + profile = ui.getSession().getProfileRegistry().getProfile(((Updates) element).getProfileId()); + toUpdate = ((Updates) element).getIUs(); + } else { + profile = ProvUI.getAdapter(element, IProfile.class); + } + if (profile == null) + return null; + if (toUpdate == null) { + IQueryResult queryResult = profile.query(policy.getVisibleInstalledIUQuery(), null); + toUpdate = queryResult.toArray(IInstallableUnit.class); + } + QueryableUpdates updateQueryable = new QueryableUpdates(ui, toUpdate); + return new ElementQueryDescriptor(updateQueryable, context.getShowLatestVersionsOnly() ? new LatestIUVersionQuery() : allQuery, new Collector()); + + case INSTALLED_IUS : + // Querying of IU's. We are drilling down into the requirements. + if (element instanceof IIUElement && context.getShowInstallChildren()) { + Collection reqs = ((IIUElement) element).getRequirements(); + IExpression[] requirementExpressions = new IExpression[reqs.size()]; + int i = 0; + for (IRequirement req : reqs) { + requirementExpressions[i++] = req.getMatches(); + } + IExpressionFactory factory = ExpressionUtil.getFactory(); + IQuery meetsAnyRequirementQuery = new ExpressionQuery(IInstallableUnit.class, factory.or(requirementExpressions)); + IQuery visibleAsAvailableQuery = policy.getVisibleAvailableIUQuery(); + @SuppressWarnings("unchecked") + CompoundQuery createCompoundQuery = CompoundQuery.createCompoundQuery(new IQuery[] {visibleAsAvailableQuery, meetsAnyRequirementQuery}, true); + return new ElementQueryDescriptor(queryable, createCompoundQuery, new Collector(), new InstalledIUElementWrapper(queryable, element)); + } + profile = ProvUI.getAdapter(element, IProfile.class); + if (profile == null) + return null; + return new ElementQueryDescriptor(profile, policy.getVisibleInstalledIUQuery(), new Collector(), new InstalledIUElementWrapper(profile, element)); + + case METADATA_REPOS : + if (element instanceof MetadataRepositories) { + if (queryable == null) { + queryable = new QueryableMetadataRepositoryManager(ui, ((MetadataRepositories) element).getIncludeDisabledRepositories()).locationsQueriable(); + element.setQueryable(queryable); + } + return new ElementQueryDescriptor(element.getQueryable(), new RepositoryLocationQuery(), new Collector(), new MetadataRepositoryElementWrapper(null, element)); + } + return null; + + case PROFILES : + queryable = new QueryableProfileRegistry(ui); + return new ElementQueryDescriptor(queryable, new MatchQuery() { + public boolean isMatch(Object candidate) { + return ProvUI.getAdapter(candidate, IProfile.class) != null; + } + }, new Collector(), new ProfileElementWrapper(null, element)); + + case AVAILABLE_ARTIFACTS : + if (!(queryable instanceof IArtifactRepository)) + return null; + return new ElementQueryDescriptor(queryable, ArtifactKeyQuery.ALL_KEYS, new Collector(), new ArtifactKeyWrapper((IArtifactRepository) queryable, element)); + + default : + return null; + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryableArtifactRepositoryManager.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryableArtifactRepositoryManager.java new file mode 100644 index 000000000..2ddade3c7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryableArtifactRepositoryManager.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * EclipseSource - ongoing development + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.net.URI; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.equinox.internal.p2.artifact.repository.ArtifactRepositoryManager; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.ui.ProvisioningUI; + +/** + * An object that queries a particular set of artifact repositories. + */ +public class QueryableArtifactRepositoryManager extends QueryableRepositoryManager { + + public QueryableArtifactRepositoryManager(ProvisioningUI ui, boolean includeDisabledRepos) { + super(ui, includeDisabledRepos); + } + + protected IArtifactRepositoryManager getRepositoryManager() { + return getSession().getArtifactRepositoryManager(); + } + + protected IArtifactRepository doLoadRepository(IRepositoryManager manager, URI location, IProgressMonitor monitor) throws ProvisionException { + return ui.loadArtifactRepository(location, false, monitor); + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.QueryableRepositoryManager#getRepositoryFlags(org.eclipse.equinox.p2.ui.RepositoryManipulator) + */ + protected int getRepositoryFlags(RepositoryTracker repositoryManipulator) { + return repositoryManipulator.getArtifactRepositoryFlags(); + } + + protected IArtifactRepository getRepository(IRepositoryManager manager, URI location) { + // note the use of ArtifactRepositoryManager (the concrete implementation). + if (manager instanceof ArtifactRepositoryManager) { + return ((ArtifactRepositoryManager) manager).getRepository(location); + } + return null; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryableMetadataRepositoryManager.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryableMetadataRepositoryManager.java new file mode 100644 index 000000000..ce65c8cce --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryableMetadataRepositoryManager.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.net.URI; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.ui.ProvisioningUI; + +/** + * An object that queries a particular set of metadata repositories. + */ +public class QueryableMetadataRepositoryManager extends QueryableRepositoryManager { + + public QueryableMetadataRepositoryManager(ProvisioningUI ui, boolean includeDisabledRepos) { + super(ui, includeDisabledRepos); + } + + protected IMetadataRepository getRepository(IRepositoryManager manager, URI location) { + // note the use of MetadataRepositoryManager (the concrete implementation). + if (manager instanceof MetadataRepositoryManager) { + return ((MetadataRepositoryManager) manager).getRepository(location); + } + return null; + } + + protected IMetadataRepositoryManager getRepositoryManager() { + return getSession().getMetadataRepositoryManager(); + } + + protected IMetadataRepository doLoadRepository(IRepositoryManager manager, URI location, IProgressMonitor monitor) throws ProvisionException { + return ui.loadMetadataRepository(location, false, monitor); + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.QueryableRepositoryManager#getRepositoryFlags(org.eclipse.equinox.p2.ui.RepositoryManipulator) + */ + protected int getRepositoryFlags(RepositoryTracker repositoryManipulator) { + return repositoryManipulator.getMetadataRepositoryFlags(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryableRepositoryManager.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryableRepositoryManager.java new file mode 100644 index 000000000..e26c67842 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/QueryableRepositoryManager.java @@ -0,0 +1,172 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui; + +import java.net.URI; +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.osgi.util.NLS; + +/** + * An object that provides query support for a specified + * set of repositories. The repository tracker flags determine which repositories + * are included in the query. Callers interested in only the resulting repository URIs + * should specify a {@link RepositoryLocationQuery}, in which case the + * query is performed over the URI's. Otherwise the repositories are loaded and + * the query is performed over the repositories themselves. + */ +public abstract class QueryableRepositoryManager implements IQueryable { + private ProvisioningSession session; + protected boolean includeDisabledRepos; + protected RepositoryTracker tracker; + protected int repositoryFlags; + protected ProvisioningUI ui; + + public QueryableRepositoryManager(ProvisioningUI ui, boolean includeDisabledRepos) { + this.includeDisabledRepos = includeDisabledRepos; + this.ui = ui; + this.tracker = ui.getRepositoryTracker(); + this.session = ui.getSession(); + repositoryFlags = getRepositoryFlags(tracker); + } + + protected ProvisioningSession getSession() { + return session; + } + + /** + * Iterates over the repositories configured in this queryable. + * For most queries, the query is run on each repository, passing any objects that satisfy the + * query. + *

    + * This method is long-running; progress and cancellation are provided + * by the given progress monitor. + *

    + * + * @param query The query to perform.. + * @param monitor a progress monitor, or null if progress + * reporting is not desired + * @return The QueryResult argument + */ + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + IRepositoryManager manager = getRepositoryManager(); + if (monitor == null) + monitor = new NullProgressMonitor(); + return query(getRepoLocations(manager), query, monitor); + } + + public IQueryable locationsQueriable() { + return new IQueryable() { + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return query.perform(Arrays.asList(getRepoLocations(getRepositoryManager())).iterator()); + } + }; + } + + protected URI[] getRepoLocations(IRepositoryManager manager) { + Set locations = new HashSet(); + locations.addAll(Arrays.asList(manager.getKnownRepositories(repositoryFlags))); + if (includeDisabledRepos) { + locations.addAll(Arrays.asList(manager.getKnownRepositories(IRepositoryManager.REPOSITORIES_DISABLED | repositoryFlags))); + } + return locations.toArray(new URI[locations.size()]); + } + + /** + * Return a boolean indicating whether all the repositories that + * can be queried by the receiver are already loaded. If a repository + * is not loaded because it was not found, this will not return false, + * because this repository cannot be queried. + * + * @return true if all repositories to be queried by the + * receiver are loaded, false if they + * are not. + */ + public boolean areRepositoriesLoaded() { + IRepositoryManager mgr = getRepositoryManager(); + if (mgr == null) + return false; + URI[] repoURIs = getRepoLocations(mgr); + for (int i = 0; i < repoURIs.length; i++) { + IRepository repo = getRepository(mgr, repoURIs[i]); + // A not-loaded repo doesn't count if it's considered missing (not found) + if (repo == null && !tracker.hasNotFoundStatusBeenReported(repoURIs[i])) + return false; + } + return true; + } + + protected abstract IRepository getRepository(IRepositoryManager manager, URI location); + + protected IRepository loadRepository(IRepositoryManager manager, URI location, IProgressMonitor monitor) throws ProvisionException { + monitor.setTaskName(NLS.bind(ProvUIMessages.QueryableMetadataRepositoryManager_LoadRepositoryProgress, URIUtil.toUnencodedString(location))); + IRepository repo = doLoadRepository(manager, location, monitor); + return repo; + } + + /** + * Return the appropriate repository manager, or null if none could be found. + * @return the repository manager + */ + protected abstract IRepositoryManager getRepositoryManager(); + + /** + * Return the flags that should be used to access repositories given the + * manipulator. + */ + protected abstract int getRepositoryFlags(RepositoryTracker repositoryManipulator); + + /** + * Load the repository located at the specified location. + * + * @param manager the manager + * @param location the repository location + * @param monitor the progress monitor + * @return the repository that was loaded, or null if no repository could + * be found at that location. + */ + protected abstract IRepository doLoadRepository(IRepositoryManager manager, URI location, IProgressMonitor monitor) throws ProvisionException; + + protected IQueryResult query(URI uris[], IQuery query, IProgressMonitor monitor) { + SubMonitor sub = SubMonitor.convert(monitor, (uris.length + 1) * 100); + ArrayList> loadedRepos = new ArrayList>(uris.length); + for (int i = 0; i < uris.length; i++) { + IRepository repo = null; + try { + repo = loadRepository(getRepositoryManager(), uris[i], sub.newChild(100)); + } catch (ProvisionException e) { + tracker.reportLoadFailure(uris[i], e); + } catch (OperationCanceledException e) { + // user has canceled + repo = null; + } + if (repo != null) + loadedRepos.add(repo); + } + if (loadedRepos.size() > 0) { + return new CompoundQueryable(loadedRepos).query(query, sub.newChild(100)); + } + return Collector.emptyCollector(); + } + + public void setRespositoryFlags(int flags) { + this.repositoryFlags = flags; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/RepositoryLocationQuery.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/RepositoryLocationQuery.java new file mode 100644 index 000000000..778da7710 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/RepositoryLocationQuery.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui; + +import java.net.URI; +import java.util.Iterator; +import org.eclipse.equinox.internal.p2.query.QueryHelpers; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepository; + +/** + * RepositoryLocationQuery is a query that gathers repository + * locations rather than repositories. It is used when composing + * queries against a QueryableRepositoryManager to indicate that the + * repository need not be loaded to run the query. + * + * @since 3.5 + */ +public class RepositoryLocationQuery implements IQuery { + + /** + * Gets the ID for this Query. + */ + public String getId() { + return QueryHelpers.getId(this); + } + + /** + * Gets a particular property of the query. + * @param property The property to retrieve + */ + public Object getProperty(String property) { + return QueryHelpers.getProperty(this, property); + } + + public IQueryResult perform(Iterator iterator) { + Collector result = new Collector(); + while (iterator.hasNext()) { + Object candidate = iterator.next(); + URI location = getLocation(candidate); + if (location != null) + if (!result.accept(location)) + break; + } + return result; + } + + private URI getLocation(Object o) { + if (o instanceof URI) + return (URI) o; + if (o instanceof IRepository) + return ((IRepository) o).getLocation(); + return null; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/RepositoryOperationBeginningEvent.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/RepositoryOperationBeginningEvent.java new file mode 100644 index 000000000..66aca16db --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/RepositoryOperationBeginningEvent.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui; + +import java.util.EventObject; + +/** + * Event used to signal that a repository operation is about + * to begin. This event can be used to ignore lower-level repository events + * until the operation is complete. + * + * @since 2.0 + */ +public class RepositoryOperationBeginningEvent extends EventObject { + + private static final long serialVersionUID = -7529156836242774280L; + + /** + * Construct a new instance of this event. + * @param source the source of the event + */ + public RepositoryOperationBeginningEvent(Object source) { + super(source); + } + +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/RepositoryOperationEndingEvent.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/RepositoryOperationEndingEvent.java new file mode 100644 index 000000000..ec3b13a91 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/RepositoryOperationEndingEvent.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui; + +import java.util.EventObject; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; + +/** + * Event used to signal that a repository operation has completed. + * + * @since 2.0 + */ +public class RepositoryOperationEndingEvent extends EventObject { + + private static final long serialVersionUID = -4513769756968621852L; + + /** + * A repository event describing the nature of the operation. + */ + private RepositoryEvent event; + + /** + * A boolean indicating whether the UI should be updated in response + * to this event. + */ + private boolean update; + + /** + * Construct a new instance of this event. + * + * @param source the source of the event + * @param update a boolean indicating whether the UI should be updated in response + * to this event. + * @param event a {@link RepositoryEvent} describing the underlying event, or null + * if no single event can describe the operation. This event may be used by clients to determine + * what should be updated after an operation completes. + */ + public RepositoryOperationEndingEvent(Object source, boolean update, RepositoryEvent event) { + super(source); + this.update = update; + this.event = event; + } + + /** + * Return a {@link RepositoryEvent} that reflects the operation that + * occurred. A null return value indicates that there + * was not a single underlying repository operation. + * + * @return the {@link RepositoryEvent} that was involved in the operation. May be + * null. This event may be used by clients to determine + * what should be updated after an operation completes. + + */ + public RepositoryEvent getEvent() { + return event; + } + + /** + * Return a boolean that indicates whether the client should update the UI in response + * to this event. + * event. + * + * @return true if clients should update to reflect to this event, false + * if the client should ignore the entire operation. + */ + public boolean update() { + return update; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/SimpleLicenseManager.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/SimpleLicenseManager.java deleted file mode 100644 index b92674ad8..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/SimpleLicenseManager.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Genuitec, LLC - added license support - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.ui; - -import java.io.*; -import java.math.BigInteger; -import java.util.*; -import javax.xml.parsers.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.ILicense; -import org.eclipse.equinox.internal.provisional.p2.ui.IUPropertyUtils; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.LicenseManager; -import org.eclipse.ui.statushandlers.StatusManager; -import org.w3c.dom.*; -import org.xml.sax.SAXException; - -/** - * SimpleLicenseManager is a license manager that keeps track of - * IInstallableUnit licenses by using the digests of the IU's licenses. - * It can read and write its accepted list to a stream. - * - * @since 3.4 - */ -public class SimpleLicenseManager extends LicenseManager { - java.util.Set accepted = new HashSet(); - - public boolean accept(IInstallableUnit iu) { - ILicense license = IUPropertyUtils.getLicense(iu); - if (license != null) - accepted.add(license.getDigest()); - return true; - } - - public boolean reject(IInstallableUnit iu) { - ILicense license = IUPropertyUtils.getLicense(iu); - if (license != null) - accepted.remove(license.getDigest()); - return true; - } - - public boolean isAccepted(IInstallableUnit iu) { - ILicense license = IUPropertyUtils.getLicense(iu); - if (license == null) - return true; - return accepted.contains(license.getDigest()); - } - - public boolean hasAcceptedLicenses() { - return !accepted.isEmpty(); - } - - public void read(InputStream stream) throws IOException { - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - DocumentBuilder parser = factory.newDocumentBuilder(); - Document doc = parser.parse(stream); - Node root = doc.getDocumentElement(); - processRoot(root, accepted); - } catch (ParserConfigurationException e) { - ProvUI.handleException(e, ProvUIMessages.ProvUILicenseManager_ParsingError, StatusManager.LOG); - } catch (SAXException e) { - ProvUI.handleException(e, ProvUIMessages.ProvUILicenseManager_ParsingError, StatusManager.LOG); - } - } - - public void write(OutputStream stream) throws IOException { - OutputStreamWriter osw = null; - PrintWriter writer = null; - try { - osw = new OutputStreamWriter(stream, "UTF8"); //$NON-NLS-1$ - writer = new PrintWriter(osw); - writer.println(""); //$NON-NLS-1$ - writer.println(""); //$NON-NLS-1$ - for (Iterator i = accepted.iterator(); i.hasNext();) { - BigInteger digest = (BigInteger) i.next(); - writer.print(" " + ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - } finally { - writer.println(""); //$NON-NLS-1$ - writer.flush(); - writer.close(); - if (osw != null) - osw.close(); - } - } - - private void processRoot(Node root, Set licenses) { - if (root.getNodeName().equals("licenses")) { //$NON-NLS-1$ - NodeList children = root.getChildNodes(); - processChildren(children, licenses); - } - } - - private void processChildren(NodeList children, Set licenses) { - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - if (child.getNodeType() == Node.ELEMENT_NODE) { - if (child.getNodeName().equals("license")) { //$NON-NLS-1$ - NamedNodeMap atts = child.getAttributes(); - Node digestAtt = atts.getNamedItem("digest"); //$NON-NLS-1$ - if (digestAtt != null) { - BigInteger digest = new BigInteger(digestAtt.getNodeValue(), 16); - licenses.add(digest); - } - } - } - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/UIRepositoryEvent.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/UIRepositoryEvent.java deleted file mode 100644 index 2d4bea23c..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/UIRepositoryEvent.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.p2.ui; - -import java.net.URI; -import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; - -/** - * UIMetadataRepositoryEvent is used to distinguish those metadata repository - * events of concern to the end user from those that are internal. - * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=236485 - * - * @since 3.5 - * - */ -public class UIRepositoryEvent extends RepositoryEvent { - - private static final long serialVersionUID = 820293103398960019L; - - /** - * @param location - */ - public UIRepositoryEvent(URI location, int type, int kind) { - super(location, type, kind, true); - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/UpdateManagerCompatibility.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/UpdateManagerCompatibility.java new file mode 100644 index 000000000..20ae28288 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/UpdateManagerCompatibility.java @@ -0,0 +1,291 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui; + +import java.io.*; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Iterator; +import java.util.Vector; +import javax.xml.parsers.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.statushandlers.StatusManager; +import org.w3c.dom.*; +import org.xml.sax.SAXException; + +/** + * Utility methods involving compatibility with the Eclipse Update Manager. + * + * @since 3.4 + * + */ +public class UpdateManagerCompatibility { + + // This value was copied from MetadataGeneratorHelper. Must be the same. + private static final String ECLIPSE_INSTALL_HANDLER_PROP = "org.eclipse.update.installHandler"; //$NON-NLS-1$ + private static final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + + private static void parse(String fileName, Vector bookmarks) { + File file = new File(fileName); + if (!file.exists()) + return; + + try { + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder parser = documentBuilderFactory.newDocumentBuilder(); + Document doc = parser.parse(file); + Node root = doc.getDocumentElement(); + processRoot(root, bookmarks); + } catch (ParserConfigurationException e) { + logFail(e); + } catch (SAXException e) { + logFail(e); + } catch (IOException e) { + logFail(e); + } + } + + private static MetadataRepositoryElement[] getSites(Vector bookmarks) { + return bookmarks.toArray(new MetadataRepositoryElement[bookmarks.size()]); + } + + private static void processRoot(Node root, Vector bookmarks) { + if (root.getNodeName().equals("bookmarks")) { //$NON-NLS-1$ + NodeList children = root.getChildNodes(); + processChildren(children, bookmarks); + } + } + + private static void processChildren(NodeList children, Vector bookmarks) { + for (int i = 0; i < children.getLength(); i++) { + Node child = children.item(i); + if (child.getNodeType() == Node.ELEMENT_NODE) { + if (child.getNodeName().equals("site")) { //$NON-NLS-1$ + createSite(child, bookmarks); + } else if (child.getNodeName().equals("folder")) { //$NON-NLS-1$ + createFolder(child, bookmarks); + } + } + } + } + + private static void createSite(Node child, Vector bookmarks) { + URI uri = null; + try { + uri = URIUtil.fromString((getAttribute(child, "url"))); //$NON-NLS-1$ + } catch (URISyntaxException e) { + logFail(e); + return; + } + + String sel = getAttribute(child, "selected"); //$NON-NLS-1$ + boolean selected = (sel != null && sel.equals("true")); //$NON-NLS-1$ + + MetadataRepositoryElement element = new MetadataRepositoryElement(null, uri, selected); + String nickname = getAttribute(child, "name"); //$NON-NLS-1$ + if (nickname != null && nickname.length() > 0) + element.setNickname(nickname); + bookmarks.add(element); + } + + private static void createFolder(Node child, Vector bookmarks) { + if (child.hasChildNodes()) + processChildren(child.getChildNodes(), bookmarks); + } + + private static String getAttribute(Node node, String name) { + NamedNodeMap atts = node.getAttributes(); + Node att = atts.getNamedItem(name); + if (att != null) { + return att.getNodeValue(); + } + return ""; //$NON-NLS-1$ + } + + private static void store(String fileName, Vector bookmarks) { + FileOutputStream fos = null; + OutputStreamWriter osw = null; + PrintWriter writer = null; + try { + fos = new FileOutputStream(fileName); + osw = new OutputStreamWriter(fos, "UTF8"); //$NON-NLS-1$ + writer = new PrintWriter(osw); + writer.println(""); //$NON-NLS-1$ + writer.println(""); //$NON-NLS-1$ + for (int i = 0; i < bookmarks.size(); i++) { + Object obj = bookmarks.get(i); + writeObject(" ", obj, writer); //$NON-NLS-1$ + } + } catch (IOException e) { + logFail(e); + } finally { + if (writer != null) { + writer.println(""); //$NON-NLS-1$ + writer.flush(); + writer.close(); + } + try { + if (osw != null) + osw.close(); + } catch (IOException e1) { + logFail(e1); + } + try { + if (fos != null) + fos.close(); + } catch (IOException e2) { + logFail(e2); + } + } + } + + private static void writeObject(String indent, Object obj, PrintWriter writer) { + if (obj instanceof MetadataRepositoryElement) { + MetadataRepositoryElement element = (MetadataRepositoryElement) obj; + String sel = element.isEnabled() ? "true" : "false"; //$NON-NLS-1$ //$NON-NLS-2$ + String name = element.getName(); + writer.print(indent + ""); //$NON-NLS-1$ + } + } + + public static boolean requiresInstallHandlerSupport(IProvisioningPlan plan) { + IQueryResult result = plan.getAdditions().query(InstallableUnitQuery.ANY, null); + for (Iterator iterator = result.iterator(); iterator.hasNext();) { + IInstallableUnit iu = iterator.next(); + if (iu != null && iu.getProperty(ECLIPSE_INSTALL_HANDLER_PROP) != null) + return true; + } + return false; + + } + + /** + * Prompt the user for a file and import the sites specified in that + * file. Return the collection of repo elements in the import. + * @param shell the shell used to parent any dialogs used. + */ + public static MetadataRepositoryElement[] importSites(Shell shell) { + FileDialog dialog = new FileDialog(shell); + dialog.setText(ProvUIMessages.UpdateManagerCompatibility_ImportSitesTitle); + dialog.setFilterExtensions(new String[] {"*.xml", "*"}); //$NON-NLS-1$ //$NON-NLS-2$ + + MetadataRepositoryElement[] sites = null; + + String bookmarksFile = dialog.open(); + while (bookmarksFile != null && sites == null) { + File file = new File(bookmarksFile); + sites = readBookmarkFile(file); + if (sites == null || sites.length == 0) { + MessageDialog.openInformation(shell, ProvUIMessages.UpdateManagerCompatibility_InvalidSitesTitle, ProvUIMessages.UpdateManagerCompatibility_InvalidSiteFileMessage); + bookmarksFile = dialog.open(); + } + } + return sites == null ? new MetadataRepositoryElement[0] : sites; + } + + public static MetadataRepositoryElement[] readBookmarkFile(File file) { + Vector bookmarks = new Vector(); + parse(file.getAbsolutePath(), bookmarks); + return getSites(bookmarks); + } + + public static void writeBookmarkFile(String filename, MetadataRepositoryElement[] sites) { + Vector bookmarks = new Vector(sites.length); + for (int i = 0; i < sites.length; i++) + bookmarks.add(sites[i]); + store(filename, bookmarks); + + } + + /** + * Export the specified list of sites to a bookmarks file that + * can be read later. + * + * @param shell the shell used to parent the export dialog + * @param sites the sites to export + */ + + public static void exportSites(Shell shell, MetadataRepositoryElement[] sites) { + FileDialog dialog = new FileDialog(shell, SWT.SAVE); + dialog.setText(ProvUIMessages.UpdateManagerCompatibility_ExportSitesTitle); + dialog.setFileName("bookmarks.xml"); //$NON-NLS-1$ + dialog.setFilterExtensions(new String[] {"*.xml", "*"}); //$NON-NLS-1$ //$NON-NLS-2$ + + String bookmarksFile = dialog.open(); + if (bookmarksFile == null) + return; + + writeBookmarkFile(bookmarksFile, sites); + } + + /** + * Open the old UpdateManager installer UI using the specified shell. + * We do not call the UpdateManagerUI class directly because we want to be able to be configured + * without requiring those plug-ins. Instead, we invoke a known command. + */ + public static void openInstaller() { + ProvUI.openUpdateManagerInstaller(null); + } + + /** + * Open the old UpdateManager configuration manager UI using the specified shell. + * We do not call the UpdateManagerUI class directly because we want to be able to be configured + * without requiring those plug-ins. Instead, we invoke a known command. + */ + public static void openConfigurationManager() { + ProvUI.openUpdateManagerConfigurationManager(null); + } + + private static void logFail(Throwable t) { + Status failStatus = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, t.getLocalizedMessage(), t); + ProvUI.reportStatus(failStatus, StatusManager.LOG); + } + + private static String getWritableXMLString(String value) { + StringBuffer buf = new StringBuffer(); + if (value == null) + return buf.toString(); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + switch (c) { + case '&' : + buf.append("&"); //$NON-NLS-1$ + break; + case '<' : + buf.append("<"); //$NON-NLS-1$ + break; + case '>' : + buf.append(">"); //$NON-NLS-1$ + break; + case '\'' : + buf.append("'"); //$NON-NLS-1$ + break; + case '\"' : + buf.append("""); //$NON-NLS-1$ + break; + default : + buf.append(c); + break; + } + } + return buf.toString(); + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ValidationDialogServiceUI.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ValidationDialogServiceUI.java new file mode 100644 index 000000000..cd5a5f492 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/ValidationDialogServiceUI.java @@ -0,0 +1,189 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui; + +import java.security.cert.Certificate; +import org.eclipse.core.runtime.*; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.equinox.internal.p2.ui.dialogs.TrustCertificateDialog; +import org.eclipse.equinox.internal.p2.ui.dialogs.UserValidationDialog; +import org.eclipse.equinox.internal.p2.ui.viewers.CertificateLabelProvider; +import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; +import org.eclipse.jface.dialogs.ErrorDialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.viewers.*; +import org.eclipse.jface.window.Window; +import org.eclipse.osgi.util.NLS; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.PlatformUI; + +/** + * The default GUI-based implementation of {@link IServiceUI}. + * The service declaration is made in the serviceui_component.xml file. + + */ +public class ValidationDialogServiceUI implements IServiceUI { + /** + * Subclassed to add a cancel button to the error dialog. + */ + static class OkCancelErrorDialog extends ErrorDialog { + + public OkCancelErrorDialog(Shell parentShell, String dialogTitle, String message, IStatus status, int displayMask) { + super(parentShell, dialogTitle, message, status, displayMask); + } + + protected void createButtonsForButtonBar(Composite parent) { + // create OK and Details buttons + createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); + createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, true); + createDetailsButton(parent); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.core.IServiceUI#getUsernamePassword(java.lang.String) + */ + public AuthenticationInfo getUsernamePassword(final String location) { + + final AuthenticationInfo[] result = new AuthenticationInfo[1]; + if (!suppressAuthentication() && !isHeadless()) { + PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { + public void run() { + Shell shell = ProvUI.getDefaultParentShell(); + String message = NLS.bind(ProvUIMessages.ServiceUI_LoginDetails, location); + UserValidationDialog dialog = new UserValidationDialog(shell, ProvUIMessages.ServiceUI_LoginRequired, null, message); + if (dialog.open() == Window.OK) { + result[0] = dialog.getResult(); + } + } + + }); + } + return result[0]; + } + + private boolean suppressAuthentication() { + Job job = Job.getJobManager().currentJob(); + if (job != null) { + return job.getProperty(LoadMetadataRepositoryJob.SUPPRESS_AUTHENTICATION_JOB_MARKER) != null; + } + return false; + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.core.IServiceUI#showCertificates(java.lang.Object) + */ + public TrustInfo getTrustInfo(Certificate[][] untrustedChains, final String[] unsignedDetail) { + boolean trustUnsigned = true; + boolean persistTrust = false; + Certificate[] trusted = new Certificate[0]; + // Some day we may summarize all of this in one UI, or perhaps we'll have a preference to honor regarding + // unsigned content. For now we prompt separately first as to whether unsigned detail should be trusted + if (!isHeadless() && unsignedDetail != null && unsignedDetail.length > 0) { + final boolean[] result = new boolean[] {false}; + PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { + public void run() { + Shell shell = ProvUI.getDefaultParentShell(); + OkCancelErrorDialog dialog = new OkCancelErrorDialog(shell, ProvUIMessages.ServiceUI_warning_title, null, createStatus(), IStatus.WARNING); + result[0] = dialog.open() == IDialogConstants.OK_ID; + } + + private IStatus createStatus() { + MultiStatus parent = new MultiStatus(ProvUIActivator.PLUGIN_ID, 0, ProvUIMessages.ServiceUI_unsigned_message, null); + for (int i = 0; i < unsignedDetail.length; i++) { + parent.add(new Status(IStatus.WARNING, ProvUIActivator.PLUGIN_ID, unsignedDetail[i])); + } + return parent; + } + }); + trustUnsigned = result[0]; + } + // For now, there is no need to show certificates if there was unsigned content and we don't trust it. + if (!trustUnsigned) + return new TrustInfo(trusted, persistTrust, trustUnsigned); + + // We've established trust for unsigned content, now examine the untrusted chains + if (!isHeadless() && untrustedChains != null && untrustedChains.length > 0) { + + final Object[] result = new Object[1]; + final TreeNode[] input = createTreeNodes(untrustedChains); + + PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { + public void run() { + Shell shell = ProvUI.getDefaultParentShell(); + ILabelProvider labelProvider = new CertificateLabelProvider(); + TreeNodeContentProvider contentProvider = new TreeNodeContentProvider(); + TrustCertificateDialog trustCertificateDialog = new TrustCertificateDialog(shell, input, labelProvider, contentProvider); + trustCertificateDialog.open(); + Certificate[] values = new Certificate[trustCertificateDialog.getResult() == null ? 0 : trustCertificateDialog.getResult().length]; + for (int i = 0; i < values.length; i++) { + values[i] = (Certificate) ((TreeNode) trustCertificateDialog.getResult()[i]).getValue(); + } + result[0] = values; + } + }); + persistTrust = true; + trusted = (Certificate[]) result[0]; + } + return new TrustInfo(trusted, persistTrust, trustUnsigned); + } + + private TreeNode[] createTreeNodes(Certificate[][] certificates) { + TreeNode[] children = new TreeNode[certificates.length]; + for (int i = 0; i < certificates.length; i++) { + TreeNode head = new TreeNode(certificates[i][0]); + TreeNode parent = head; + children[i] = head; + for (int j = 0; j < certificates[i].length; j++) { + TreeNode node = new TreeNode(certificates[i][j]); + node.setParent(parent); + parent.setChildren(new TreeNode[] {node}); + parent = node; + } + } + return children; + } + + public AuthenticationInfo getUsernamePassword(final String location, final AuthenticationInfo previousInfo) { + + final AuthenticationInfo[] result = new AuthenticationInfo[1]; + if (!suppressAuthentication() && !isHeadless()) { + PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { + public void run() { + Shell shell = ProvUI.getDefaultParentShell(); + String message = null; + if (previousInfo.saveResult()) + message = NLS.bind(ProvUIMessages.ProvUIMessages_SavedNotAccepted_EnterFor_0, location); + else + message = NLS.bind(ProvUIMessages.ProvUIMessages_NotAccepted_EnterFor_0, location); + + UserValidationDialog dialog = new UserValidationDialog(previousInfo, shell, ProvUIMessages.ServiceUI_LoginRequired, null, message); + if (dialog.open() == Window.OK) { + result[0] = dialog.getResult(); + } + } + + }); + } + return result[0]; + } + + private boolean isHeadless() { + // If there is no UI available and we are still the IServiceUI, + // assume that the operation should proceed. See + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=291049 + return !PlatformUI.isWorkbenchRunning(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ColocatedRepositoryAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ColocatedRepositoryAction.java new file mode 100644 index 000000000..2bbcacca5 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ColocatedRepositoryAction.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (c) 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.actions; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.viewers.ISelectionProvider; + +public abstract class ColocatedRepositoryAction extends ProvisioningAction { + + public ColocatedRepositoryAction(ProvisioningUI ui, String label, String tooltipText, ISelectionProvider selectionProvider) { + super(ui, label, selectionProvider); + setToolTipText(tooltipText); + init(); + } + + protected URI[] getSelectedLocations(Object[] selectionArray) { + List urls = new ArrayList(); + for (int i = 0; i < selectionArray.length; i++) { + if (selectionArray[i] instanceof MetadataRepositoryElement) + urls.add(((MetadataRepositoryElement) selectionArray[i]).getLocation()); + } + return urls.toArray(new URI[urls.size()]); + } + + protected void checkEnablement(Object[] selectionArray) { + setEnabled(getSelectedLocations(selectionArray).length > 0); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ExistingIUInProfileAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ExistingIUInProfileAction.java new file mode 100644 index 000000000..6f2431b0e --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ExistingIUInProfileAction.java @@ -0,0 +1,97 @@ +/******************************************************************************* + * Copyright (c) 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.actions; + +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.internal.p2.ui.model.IIUElement; +import org.eclipse.equinox.internal.p2.ui.model.InstalledIUElement; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.PipedQuery; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.viewers.ISelectionProvider; + +/** + * + * Abstract class that implements the enablement rules for actions that + * affect IU's already in a profile. The action only enables when all of the + * IU's involved are top level IU's from the same profile. + * + * @since 3.5 + * + */ +public abstract class ExistingIUInProfileAction extends ProfileModificationAction { + + public ExistingIUInProfileAction(ProvisioningUI ui, String label, ISelectionProvider selectionProvider, String profileId) { + super(ui, label, selectionProvider, profileId); + } + + protected boolean isEnabledFor(Object[] selectionArray) { + Object parent = null; + // We don't want to prompt for a profile during validation, + // so we only consider the profile id that was set, or the profile + // referred to by the element itself.. + IProfile profile = getProfile(); + if (selectionArray.length > 0) { + for (int i = 0; i < selectionArray.length; i++) { + if (selectionArray[i] instanceof InstalledIUElement) { + InstalledIUElement element = (InstalledIUElement) selectionArray[i]; + // If the parents are different, then they are either from + // different profiles or are nested in different parts of the tree. + // Either way, this makes the selection invalid. + if (parent == null) { + parent = element.getParent(element); + } else if (parent != element.getParent(element)) { + return false; + } + // Now consider the validity of the element on its own + if (!isSelectable(element.getIU(), profile)) + return false; + } else { + IInstallableUnit iu = ProvUI.getAdapter(selectionArray[i], IInstallableUnit.class); + if (iu == null || !isSelectable(iu)) + return false; + } + } + return true; + } + return false; + } + + protected boolean isSelectable(IIUElement element) { + if (!super.isSelectable(element)) + return false; + Object parent = element.getParent(element); + if (parent != null) { + IProfile profile = ProvUI.getAdapter(parent, IProfile.class); + if (profile != null) + return isSelectable(element.getIU(), profile); + } + return false; + } + + protected boolean isSelectable(IInstallableUnit iu) { + if (!super.isSelectable(iu)) + return false; + return isSelectable(iu, getProfile()); + } + + private boolean isSelectable(IInstallableUnit iu, IProfile profile) { + int lock = getLock(profile, iu); + if ((lock & getLockConstant()) == getLockConstant()) + return false; + return !profile.query(new PipedQuery(new InstallableUnitQuery(iu), getPolicy().getVisibleInstalledIUQuery()), null).isEmpty(); + } + + protected abstract int getLockConstant(); +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/InstallAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/InstallAction.java new file mode 100644 index 000000000..c74f19f66 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/InstallAction.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.actions; + +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.internal.p2.ui.model.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.InstallOperation; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.viewers.ISelectionProvider; + +public class InstallAction extends ProfileModificationAction { + + public InstallAction(ProvisioningUI ui, ISelectionProvider selectionProvider, String profileId) { + super(ui, ProvUI.INSTALL_COMMAND_LABEL, selectionProvider, profileId); + setToolTipText(ProvUI.INSTALL_COMMAND_TOOLTIP); + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.ui.actions.ProfileModificationAction#isEnabledFor(java.lang.Object[]) + */ + protected boolean isEnabledFor(Object[] selectionArray) { + if (selectionArray.length == 0) + return false; + // We allow non-IU's to be selected at this point, but there + // must be at least one installable unit selected that is + // selectable + for (int i = 0; i < selectionArray.length; i++) { + if (selectionArray[i] instanceof InstalledIUElement && isSelectable((IIUElement) selectionArray[i])) + return true; + IInstallableUnit iu = ProvUI.getAdapter(selectionArray[i], IInstallableUnit.class); + if (iu != null && isSelectable(iu)) + return true; + } + return false; + } + + /* + * Overridden to reject categories and nested IU's (parent is a non-category IU) + * (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.ui.actions.ProfileModificationAction#isSelectable(org.eclipse.equinox.internal.p2.ui.model.IUElement) + */ + protected boolean isSelectable(IIUElement element) { + return super.isSelectable(element) && !(element.getParent(element) instanceof AvailableIUElement); + } + + protected int performAction(ProfileChangeOperation operation, IInstallableUnit[] ius) { + return getProvisioningUI().openInstallWizard(getShell(), ius, (InstallOperation) operation, null); + } + + protected ProfileChangeOperation getProfileChangeOperation(IInstallableUnit[] ius) { + InstallOperation op = new InstallOperation(getSession(), ius); + op.setProfileId(profileId); + // op.setRootMarkerKey(getPolicy().getQueryContext().getVisibleInstalledIUProperty()); + return op; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ProfileModificationAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ProfileModificationAction.java new file mode 100644 index 000000000..70b4ba85d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ProfileModificationAction.java @@ -0,0 +1,212 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.actions; + +import org.eclipse.equinox.p2.ui.LicenseManager; + +import java.util.ArrayList; +import java.util.List; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.IJobChangeEvent; +import org.eclipse.core.runtime.jobs.JobChangeAdapter; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.model.CategoryElement; +import org.eclipse.equinox.internal.p2.ui.model.IIUElement; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.operations.ProvisioningJob; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.window.Window; +import org.eclipse.osgi.util.NLS; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.statushandlers.StatusManager; + +public abstract class ProfileModificationAction extends ProvisioningAction { + public static final int ACTION_NOT_RUN = -1; + String profileId; + String userChosenProfileId; + int result = ACTION_NOT_RUN; + + protected ProfileModificationAction(ProvisioningUI ui, String text, ISelectionProvider selectionProvider, String profileId) { + super(ui, text, selectionProvider); + this.ui = ui; + this.profileId = profileId; + init(); + } + + public void run() { + IInstallableUnit[] ius = getSelectedIUs(); + // No ius or no profile? + if (profileId == null || ius.length == 0) { + ProvUI.reportStatus(getNoProfileOrSelectionStatus(profileId, ius), StatusManager.BLOCK); + runCanceled(); + return; + } + run(ius, profileId); + } + + public IProfile getProfile() { + String id = profileId == null ? ui.getProfileId() : profileId; + return ui.getSession().getProfileRegistry().getProfile(id); + } + + protected IStatus getNoProfileOrSelectionStatus(String id, IInstallableUnit[] ius) { + return new Status(IStatus.WARNING, ProvUIActivator.PLUGIN_ID, NLS.bind(ProvUIMessages.ProfileModificationAction_InvalidSelections, id, new Integer(ius.length))); + } + + protected abstract ProfileChangeOperation getProfileChangeOperation(IInstallableUnit[] ius); + + protected void run(final IInstallableUnit[] ius, final String id) { + final ProfileChangeOperation operation = getProfileChangeOperation(ius); + ProvisioningJob job = operation.getResolveJob(null); + if (job == null) { + ProvUI.reportStatus(operation.getResolutionResult(), StatusManager.SHOW); + } else { + job.addJobChangeListener(new JobChangeAdapter() { + public void done(IJobChangeEvent event) { + + if (PlatformUI.isWorkbenchRunning()) { + PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { + public void run() { + if (validateOperation(operation)) + performAction(operation, ius); + userChosenProfileId = null; + } + }); + } + + } + + }); + getProvisioningUI().schedule(job, StatusManager.SHOW | StatusManager.LOG); + } + // Since we are resolving asynchronously, our job is done. Setting this allows + // callers to decide to close the launching window. + // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=236495 + result = Window.OK; + } + + /** + * Get the integer return code returned by any wizards launched by this + * action. If the action has not been run, return ACTION_NOT_RUN. If the + * action does not open a wizard, return Window.OK if the operation was performed, + * and Window.CANCEL if it was canceled. + * + * @return integer return code + */ + public int getReturnCode() { + return result; + } + + /** + * Validate the operation and return true if the operation should + * be performed with plan. Report any errors to the user before returning false. + * @param operation + * @return a boolean indicating whether the operation should be used in a + * provisioning operation. + */ + protected boolean validateOperation(ProfileChangeOperation operation) { + if (operation != null) { + return getPolicy().continueWorkingWithOperation(operation, getShell()); + } + return false; + } + + protected abstract int performAction(ProfileChangeOperation operation, IInstallableUnit[] ius); + + protected IInstallableUnit getIU(Object element) { + return ProvUI.getAdapter(element, IInstallableUnit.class); + + } + + /** + * Return an array of the selected and valid installable units. + * The number of IInstallableUnits in the array may be different than + * the actual number of selections in the action's selection provider. + * That is, if the action is disabled due to invalid selections, + * this method will return those selections that were valid. + * + * @return an array of selected IInstallableUnit that meet the + * enablement criteria for the action. + */ + protected IInstallableUnit[] getSelectedIUs() { + List elements = getStructuredSelection().toList(); + List iusList = new ArrayList(elements.size()); + + for (int i = 0; i < elements.size(); i++) { + if (elements.get(i) instanceof IIUElement) { + IIUElement element = (IIUElement) elements.get(i); + if (isSelectable(element)) + iusList.add(getIU(element)); + } else { + IInstallableUnit iu = ProvUI.getAdapter(elements.get(i), IInstallableUnit.class); + if (iu != null && isSelectable(iu)) + iusList.add(iu); + } + } + return iusList.toArray(new IInstallableUnit[iusList.size()]); + } + + protected boolean isSelectable(IIUElement element) { + return !(element instanceof CategoryElement); + } + + protected boolean isSelectable(IInstallableUnit iu) { + return !ProvUI.isCategory(iu); + } + + protected LicenseManager getLicenseManager() { + return getProvisioningUI().getLicenseManager(); + } + + protected QueryProvider getQueryProvider() { + return ProvUI.getQueryProvider(); + } + + protected final void checkEnablement(Object[] selections) { + if (isEnabledFor(selections)) { + setEnabled(!getProvisioningUI().hasScheduledOperations()); + } else + setEnabled(false); + } + + protected abstract boolean isEnabledFor(Object[] selections); + + protected int getLock(IProfile profile, IInstallableUnit iu) { + if (profile == null) + return IProfile.LOCK_NONE; + try { + String value = profile.getInstallableUnitProperty(iu, IProfile.PROP_PROFILE_LOCKED_IU); + if (value != null) + return Integer.parseInt(value); + } catch (NumberFormatException e) { + // ignore and assume no lock + } + return IProfile.LOCK_NONE; + } + + protected String getProfileProperty(IProfile profile, IInstallableUnit iu, String propertyName) { + if (profile == null || iu == null) + return null; + return profile.getInstallableUnitProperty(iu, propertyName); + } + + private void runCanceled() { + // The action was canceled, do any cleanup needed before + // it is run again. + userChosenProfileId = null; + result = Window.CANCEL; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/PropertyDialogAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/PropertyDialogAction.java new file mode 100644 index 000000000..b521e1796 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/PropertyDialogAction.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.actions; + +import org.eclipse.jface.viewers.*; +import org.eclipse.jface.window.IShellProvider; + +/** + * PropertyDialogAction which sets its enablement on construction. + * + * @since 3.4 + * + */ + +public class PropertyDialogAction extends org.eclipse.ui.dialogs.PropertyDialogAction { + public PropertyDialogAction(IShellProvider shell, ISelectionProvider provider) { + super(shell, provider); + // prime the selection validation + ISelection selection = provider.getSelection(); + if (selection instanceof IStructuredSelection) { + selectionChanged((IStructuredSelection) selection); + } else { + selectionChanged(selection); + } + + } + +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ProvisioningAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ProvisioningAction.java new file mode 100644 index 000000000..00a40e2d9 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/ProvisioningAction.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.actions; + +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.ui.Policy; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.viewers.*; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.actions.SelectionProviderAction; + +public abstract class ProvisioningAction extends SelectionProviderAction { + ProvisioningUI ui; + + protected ProvisioningAction(ProvisioningUI ui, String text, ISelectionProvider selectionProvider) { + super(selectionProvider, text); + this.ui = ui; + } + + /* + * perform initialization that should be done after creation. + */ + protected void init() { + // prime the selection validation + ISelection selection = getSelection(); + if (selection instanceof IStructuredSelection) { + selectionChanged((IStructuredSelection) selection); + } else { + selectionChanged(selection); + } + } + + protected Shell getShell() { + return ProvUI.getDefaultParentShell(); + } + + /* + * Overridden to use the selection from the selection provider, not the one + * from the triggering event. Some selection providers reinterpret the raw selections + * (non-Javadoc) + * @see org.eclipse.ui.actions.SelectionProviderAction#selectionChanged(org.eclipse.jface.viewers.IStructuredSelection) + */ + public final void selectionChanged(IStructuredSelection selection) { + ISelection providerSelection = getSelectionProvider().getSelection(); + if (providerSelection instanceof IStructuredSelection) { + checkEnablement(((IStructuredSelection) providerSelection).toArray()); + } else { + // shouldn't really happen, but a provider could decide to de-structure the selection + selectionChanged(providerSelection); + } + } + + protected void checkEnablement(Object[] selections) { + // Default is to nothing + } + + /** + * Recheck the enablement. Called by clients when some condition outside of + * the action that may effect its enablement should be changed. + */ + public final void checkEnablement() { + ISelection selection = getSelection(); + if (selection instanceof IStructuredSelection) { + checkEnablement(((IStructuredSelection) selection).toArray()); + } else { + selectionChanged(selection); + } + } + + protected ProvisioningSession getSession() { + return ui.getSession(); + } + + protected Policy getPolicy() { + return ui.getPolicy(); + } + + protected ProvisioningUI getProvisioningUI() { + return ui; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/RefreshAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/RefreshAction.java new file mode 100644 index 000000000..d3061acaf --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/RefreshAction.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * Copyright (c) 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.actions; + +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyAdapter; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.widgets.Control; + +/** + * @since 3.4 + * + */ +public abstract class RefreshAction extends ProvisioningAction { + + /** + */ + public RefreshAction(ProvisioningUI ui, ISelectionProvider selectionProvider, Control control) { + super(ui, ProvUIMessages.RefreshAction_Label, selectionProvider); + setToolTipText(ProvUIMessages.RefreshAction_Tooltip); + hookKeyListener(control); + init(); + } + + private void hookKeyListener(Control control) { + control.addKeyListener(new KeyAdapter() { + public void keyReleased(KeyEvent e) { + handleKeyReleased(e); + } + }); + } + + public void run() { + refresh(); + } + + protected abstract void refresh(); + + /** + * Handle a key released event. Used internally and also + * made available so that clients can watch key events from + * any other controls and dispatch to this action. + * + * @param event the key event + */ + public void handleKeyReleased(KeyEvent event) { + if (event.keyCode == SWT.F5 && event.stateMask == 0) { + refresh(); + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/RemoveColocatedRepositoryAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/RemoveColocatedRepositoryAction.java new file mode 100644 index 000000000..f794bb9a6 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/RemoveColocatedRepositoryAction.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.actions; + +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.viewers.ISelectionProvider; + +public class RemoveColocatedRepositoryAction extends ColocatedRepositoryAction { + + public RemoveColocatedRepositoryAction(ProvisioningUI ui, ISelectionProvider selectionProvider) { + super(ui, ProvUIMessages.RemoveColocatedRepositoryAction_Label, ProvUIMessages.RemoveColocatedRepositoryAction_Tooltip, selectionProvider); + + } + + public void run() { + ui.getRepositoryTracker().removeRepositories(getSelectedLocations(getStructuredSelection().toArray()), ui.getSession()); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/UninstallAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/UninstallAction.java new file mode 100644 index 000000000..6ee186140 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/UninstallAction.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.actions; + +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.operations.UninstallOperation; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.viewers.ISelectionProvider; + +public class UninstallAction extends ExistingIUInProfileAction { + + public UninstallAction(ProvisioningUI ui, ISelectionProvider selectionProvider, String profileId) { + super(ui, ProvUI.UNINSTALL_COMMAND_LABEL, selectionProvider, profileId); + setToolTipText(ProvUI.UNINSTALL_COMMAND_TOOLTIP); + } + + protected String getTaskName() { + return ProvUIMessages.UninstallIUProgress; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.ui.actions.AlterExistingProfileIUAction#getLockConstant() + */ + protected int getLockConstant() { + return IProfile.LOCK_UNINSTALL; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.actions.ProfileModificationAction#getProfileChangeOperation(org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit[]) + */ + protected ProfileChangeOperation getProfileChangeOperation(IInstallableUnit[] ius) { + return ui.getUninstallOperation(ius, null); + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.actions.ProfileModificationAction#performAction(org.eclipse.equinox.p2.operations.ProfileChangeOperation, org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit[]) + */ + protected int performAction(ProfileChangeOperation operation, IInstallableUnit[] ius) { + return ui.openUninstallWizard(getShell(), ius, (UninstallOperation) operation, null); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/UpdateAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/UpdateAction.java new file mode 100644 index 000000000..4b848e5f8 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/actions/UpdateAction.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.actions; + +import java.util.ArrayList; +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.operations.UpdateOperation; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.viewers.ISelectionProvider; + +public class UpdateAction extends ExistingIUInProfileAction { + + protected IUElementListRoot root; // root that will be used to seed the wizard + protected ArrayList initialSelections; // the elements that should be selected in the wizard + boolean resolveIsVisible = true; + boolean skipSelectionPage = false; + + public UpdateAction(ProvisioningUI ui, ISelectionProvider selectionProvider, String profileId, boolean resolveIsVisible) { + super(ui, ProvUI.UPDATE_COMMAND_LABEL, selectionProvider, profileId); + setToolTipText(ProvUI.UPDATE_COMMAND_TOOLTIP); + this.resolveIsVisible = resolveIsVisible; + } + + public void setSkipSelectionPage(boolean skipSelectionPage) { + this.skipSelectionPage = skipSelectionPage; + } + + protected String getTaskName() { + return ProvUIMessages.UpdateIUProgress; + } + + protected boolean isResolveUserVisible() { + return resolveIsVisible; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.ui.actions.AlterExistingProfileIUAction#getLockConstant() + */ + protected int getLockConstant() { + return IProfile.LOCK_UPDATE; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.actions.ProfileModificationAction#getProfileChangeOperation(org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit[]) + */ + protected ProfileChangeOperation getProfileChangeOperation(IInstallableUnit[] ius) { + return ui.getUpdateOperation(ius, null); + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.actions.ProfileModificationAction#performAction(org.eclipse.equinox.p2.operations.ProfileChangeOperation, org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit[]) + */ + protected int performAction(ProfileChangeOperation operation, IInstallableUnit[] ius) { + return ui.openUpdateWizard(getShell(), skipSelectionPage, (UpdateOperation) operation, null); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AddRepositoryDialog.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AddRepositoryDialog.java new file mode 100644 index 000000000..4f3fc876d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AddRepositoryDialog.java @@ -0,0 +1,146 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.dialogs; + +import java.net.URI; +import java.net.URISyntaxException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.URIUtil; +import org.eclipse.equinox.internal.p2.repository.helpers.RepositoryHelper; +import org.eclipse.equinox.internal.p2.ui.IProvHelpContextIds; +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.p2.ui.Policy; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.*; +import org.eclipse.ui.PlatformUI; + +/** + * Abstract dialog class for adding repositories of different types. This class + * assumes the user view of a repository is a name and URI. Individual subclasses + * will dictate what kind of repository and how it's created. + * + * @since 3.4 + * + */ +public abstract class AddRepositoryDialog extends RepositoryNameAndLocationDialog { + + URI addedLocation; + static final String[] ARCHIVE_EXTENSIONS = new String[] {"*.jar;*.zip"}; //$NON-NLS-1$ + static String lastLocalLocation = null; + static String lastArchiveLocation = null; + Policy policy; + + public AddRepositoryDialog(Shell parentShell, ProvisioningUI ui) { + super(parentShell, ui); + setTitle(ProvUIMessages.AddRepositoryDialog_Title); + PlatformUI.getWorkbench().getHelpSystem().setHelp(parentShell, IProvHelpContextIds.ADD_REPOSITORY_DIALOG); + } + + protected Control createDialogArea(Composite parent) { + Composite comp = new Composite(parent, SWT.NONE); + initializeDialogUnits(comp); + GridLayout layout = new GridLayout(); + layout.numColumns = 3; + layout.marginTop = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + + comp.setLayout(layout); + GridData data = new GridData(); + comp.setLayoutData(data); + + // Name: [] + nickname = createNameField(comp); + + Button localButton = new Button(comp, SWT.PUSH); + localButton.setText(ProvUIMessages.RepositoryGroup_LocalRepoBrowseButton); + localButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.APPLICATION_MODAL); + dialog.setMessage(ProvUIMessages.RepositoryGroup_SelectRepositoryDirectory); + dialog.setFilterPath(lastLocalLocation); + String path = dialog.open(); + if (path != null) { + lastLocalLocation = path; + url.setText(makeLocalURIString(path)); + validateRepositoryURL(false); + } + } + }); + setButtonLayoutData(localButton); + + // Location: [] + url = createLocationField(comp); + + Button archiveButton = new Button(comp, SWT.PUSH); + archiveButton.setText(ProvUIMessages.RepositoryGroup_ArchivedRepoBrowseButton); + archiveButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + FileDialog dialog = new FileDialog(getShell(), SWT.APPLICATION_MODAL); + dialog.setText(ProvUIMessages.RepositoryGroup_RepositoryFile); + dialog.setFilterExtensions(ARCHIVE_EXTENSIONS); + dialog.setFileName(lastArchiveLocation); + String path = dialog.open(); + if (path != null) { + lastArchiveLocation = path; + url.setText(makeLocalURIString(path)); + validateRepositoryURL(false); + } + } + }); + setButtonLayoutData(archiveButton); + comp.setTabList(new Control[] {nickname, url, localButton, archiveButton}); + Dialog.applyDialogFont(comp); + return comp; + } + + String makeLocalURIString(String path) { + try { + URI localURI = URIUtil.fromString(path); + return URIUtil.toUnencodedString(RepositoryHelper.localRepoURIHelper(localURI)); + } catch (URISyntaxException e) { + return path; + } + } + + protected boolean handleOk() { + IStatus status = addRepository(); + return status.isOK(); + } + + /** + * Get the location of the repository that was added by this dialog. Return null + * if the dialog has not yet added a repository location. + * + * @return the location of the repository that has been added by this dialog, or null + * if no repository has been added. + */ + public URI getAddedLocation() { + return addedLocation; + } + + protected IStatus addRepository() { + IStatus status = validateRepositoryURL(false); + if (status.isOK()) { + addedLocation = getUserLocation(); + String nick = nickname.getText().trim(); + if (nick.length() == 0) + nick = null; + getRepositoryTracker().addRepository(addedLocation, nick, getProvisioningUI().getSession()); + } + return status; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ApplyProfileChangesDialog.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ApplyProfileChangesDialog.java index 9e8eb8411..57cd024cf 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ApplyProfileChangesDialog.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ApplyProfileChangesDialog.java @@ -29,7 +29,7 @@ public class ApplyProfileChangesDialog extends MessageDialog { public static final int PROFILE_APPLYCHANGES = 1; public static final int PROFILE_RESTART = 2; private final static String[] yesNo = new String[] {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL}; - private final static String[] yesNoApply = new String[] {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, ProvUIMessages.ApplyProfileChangesDialog_ApplyChanges}; + private final static String[] yesNoApply = new String[] {ProvUIMessages.ApplyProfileChangesDialog_Restart, ProvUIMessages.ApplyProfileChangesDialog_NotYet, ProvUIMessages.ApplyProfileChangesDialog_ApplyChanges}; private int returnCode = PROFILE_IGNORE; diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AvailableIUGroup.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AvailableIUGroup.java new file mode 100644 index 000000000..1a9eae71b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AvailableIUGroup.java @@ -0,0 +1,475 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.dialogs; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.net.URI; +import java.util.ArrayList; +import org.eclipse.core.runtime.*; +import org.eclipse.core.runtime.jobs.*; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.model.*; +import org.eclipse.equinox.internal.p2.ui.query.IUViewQueryContext; +import org.eclipse.equinox.internal.p2.ui.viewers.*; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.viewers.*; +import org.eclipse.osgi.util.NLS; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.BusyIndicator; +import org.eclipse.swt.events.*; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.*; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.PlatformUI; + +/** + * An AvailableIUGroup is a reusable UI component that displays the + * IU's available for installation. By default, content from all available + * repositories is shown. + * + * @since 3.4 + */ +public class AvailableIUGroup extends StructuredIUGroup { + + /** + * Show contents from all repositories + */ + public static final int AVAILABLE_ALL = 1; + + /** + * Don't show any repository content + */ + public static final int AVAILABLE_NONE = 2; + + /** + * Show local repository content + */ + public static final int AVAILABLE_LOCAL = 3; + + /** + * Show content for a specific repository + */ + public static final int AVAILABLE_SPECIFIED = 4; + + IUViewQueryContext queryContext; + int filterConstant = AVAILABLE_ALL; + URI repositoryFilter; + QueryableMetadataRepositoryManager queryableManager; + // We restrict the type of the filter used because PatternFilter does + // unnecessary accesses of children that cause problems with the deferred + // tree. + AvailableIUPatternFilter filter; + private boolean useBold = false; + private IUDetailsLabelProvider labelProvider; + private int repoFlags; + Display display; + DelayedFilterCheckboxTree filteredTree; + Job lastRequestedLoadJob; + + /** + * Create a group that represents the available IU's from all available + * repositories. The default policy controls the visibility flags for + * repositories and IU's. + * + * @param parent the parent composite for the group + */ + public AvailableIUGroup(ProvisioningUI ui, final Composite parent) { + this(ui, parent, parent.getFont(), null, getDefaultColumnConfig(), AVAILABLE_ALL); + } + + private static IUColumnConfig[] getDefaultColumnConfig() { + // increase primary column width because we might be nesting names under categories and require more space than a flat list + IUColumnConfig nameColumn = new IUColumnConfig(ProvUIMessages.ProvUI_NameColumnTitle, IUColumnConfig.COLUMN_NAME, ILayoutConstants.DEFAULT_PRIMARY_COLUMN_WIDTH + 15); + IUColumnConfig versionColumn = new IUColumnConfig(ProvUIMessages.ProvUI_VersionColumnTitle, IUColumnConfig.COLUMN_VERSION, ILayoutConstants.DEFAULT_COLUMN_WIDTH); + return new IUColumnConfig[] {nameColumn, versionColumn}; + } + + /** + * Create a group that represents the available IU's. + * + * @param ui the policy to use for deciding what should be shown + * @param parent the parent composite for the group + * @param font The font to use for calculating pixel sizes. This font is + * not managed by the receiver. + * @param queryContext the IUViewQueryContext that determines additional + * information about what is shown, such as the visible repositories + * @param columnConfig the description of the columns that should be shown. If null, a default + * will be used. + * @param filterConstant a constant specifying which repositories are used when showing content + */ + public AvailableIUGroup(ProvisioningUI ui, final Composite parent, Font font, IUViewQueryContext queryContext, IUColumnConfig[] columnConfig, int filterConstant) { + super(ui, parent, font, columnConfig); + this.display = parent.getDisplay(); + if (queryContext == null) + this.queryContext = ProvUI.getQueryContext(getPolicy()); + else + this.queryContext = queryContext; + repoFlags = ui.getRepositoryTracker().getMetadataRepositoryFlags(); + this.queryableManager = new QueryableMetadataRepositoryManager(ui, false); + this.filterConstant = filterConstant; + this.filter = new AvailableIUPatternFilter(getColumnConfig()); + this.filter.setIncludeLeadingWildcard(true); + createGroupComposite(parent); + } + + protected StructuredViewer createViewer(Composite parent) { + // Table of available IU's + filteredTree = new DelayedFilterCheckboxTree(parent, SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER, filter); + final TreeViewer availableIUViewer = filteredTree.getViewer(); + + // If the user expanded or collapsed anything while we were loading a repo + // in the background, we would not want to disrupt their work by making + // a newly loaded visible and expanding it. Setting the load job to null + // will take care of this. + availableIUViewer.getTree().addTreeListener(new TreeListener() { + public void treeCollapsed(TreeEvent e) { + lastRequestedLoadJob = null; + } + + public void treeExpanded(TreeEvent e) { + lastRequestedLoadJob = null; + } + }); + + labelProvider = new IUDetailsLabelProvider(filteredTree, getColumnConfig(), getShell()); + labelProvider.setUseBoldFontForFilteredItems(useBold); + labelProvider.setToolTipProperty(IInstallableUnit.PROP_DESCRIPTION); + + // Filters and sorters before establishing content, so we don't refresh unnecessarily. + IUComparator comparator = new IUComparator(IUComparator.IU_NAME); + comparator.useColumnConfig(getColumnConfig()); + availableIUViewer.setComparator(comparator); + availableIUViewer.setComparer(new ProvElementComparer()); + + // Now the content provider. + DeferredQueryContentProvider contentProvider = new DeferredQueryContentProvider(); + availableIUViewer.setContentProvider(contentProvider); + + // Now the presentation, columns before label provider. + setTreeColumns(availableIUViewer.getTree()); + availableIUViewer.setLabelProvider(labelProvider); + + // Notify the filtered tree so that it can hook listeners on the + // content provider. This is needed so that filtering is only allowed + // after content has been retrieved. + filteredTree.contentProviderSet(contentProvider); + + final StructuredViewerProvisioningListener listener = new StructuredViewerProvisioningListener(availableIUViewer, ProvUIProvisioningListener.PROV_EVENT_METADATA_REPOSITORY) { + protected void repositoryAdded(final RepositoryEvent event) { + makeRepositoryVisible(event.getRepositoryLocation()); + } + + protected void refreshViewer() { + final TreeViewer treeViewer = filteredTree.getViewer(); + final Tree tree = treeViewer.getTree(); + IWorkbench workbench = PlatformUI.getWorkbench(); + if (workbench.isClosing()) + return; + if (tree != null && !tree.isDisposed()) { + updateAvailableViewState(); + } + + } + }; + ProvUIActivator.getDefault().addProvisioningListener(listener); + + availableIUViewer.getControl().addDisposeListener(new DisposeListener() { + public void widgetDisposed(DisposeEvent e) { + ProvUIActivator.getDefault().removeProvisioningListener(listener); + } + }); + updateAvailableViewState(); + return availableIUViewer; + } + + private void setTreeColumns(Tree tree) { + tree.setHeaderVisible(true); + + IUColumnConfig[] cols = getColumnConfig(); + for (int i = 0; i < cols.length; i++) { + TreeColumn tc = new TreeColumn(tree, SWT.NONE, i); + tc.setResizable(true); + tc.setText(cols[i].getColumnTitle()); + tc.setWidth(cols[i].getWidthInPixels(tree)); + } + } + + Object getNewInput() { + if (repositoryFilter != null) { + return new MetadataRepositoryElement(queryContext, getProvisioningUI(), repositoryFilter, true); + } else if (filterConstant == AVAILABLE_NONE) { + // Dummy object that explains empty site list + return new ProvElement(null) { + public Object[] getChildren(Object o) { + String description; + String name; + int severity; + if (!getPolicy().getRepositoriesVisible()) { + // shouldn't get here ideally. No sites and no way to add any. + severity = IStatus.ERROR; + name = ProvUIMessages.AvailableIUGroup_NoSitesConfiguredExplanation; + description = ProvUIMessages.AvailableIUGroup_NoSitesConfiguredDescription; + } else { + severity = IStatus.INFO; + name = ProvUIMessages.AvailableIUGroup_NoSitesExplanation; + description = ProvUIMessages.ColocatedRepositoryManipulator_NoContentExplanation; + } + return new Object[] {new EmptyElementExplanation(null, severity, name, description)}; + } + + public String getLabel(Object o) { + // Label not needed for input + return null; + } + }; + } else { + queryableManager.setRespositoryFlags(repoFlags); + return new MetadataRepositories(queryContext, getProvisioningUI(), queryableManager); + } + } + + /** + * Set a boolean indicating whether a bold font should be used when + * showing filtered items. This method does not refresh the tree or + * labels, so that must be done explicitly by the caller. + * @param useBoldFont + */ + public void setUseBoldFontForFilteredItems(boolean useBoldFont) { + if (labelProvider != null) + labelProvider.setUseBoldFontForFilteredItems(useBoldFont); + } + + /** + * Return the composite that contains the controls in this group. + * @return the composite + */ + public Composite getComposite() { + return super.getComposite(); + } + + /** + * Get the viewer used to represent the available IU's + * @return the viewer + */ + public StructuredViewer getStructuredViewer() { + return super.getStructuredViewer(); + } + + /** + * Get the selected IU's + * @return the array of selected IU's + */ + // overridden for visibility in the public package + public IInstallableUnit[] getSelectedIUs() { + return super.getSelectedIUs(); + } + + // overridden to weed out non-IU elements, such as repositories or empty explanations + public Object[] getSelectedIUElements() { + Object[] elements = ((IStructuredSelection) viewer.getSelection()).toArray(); + ArrayList list = new ArrayList(elements.length); + for (int i = 0; i < elements.length; i++) + if (ElementUtils.getIU(elements[i]) != null) + list.add(elements[i]); + return list.toArray(); + } + + public CheckboxTreeViewer getCheckboxTreeViewer() { + return filteredTree.getCheckboxTreeViewer(); + } + + /** + * Get the selected IU's + * @return the array of checked IU's + */ + public IInstallableUnit[] getCheckedLeafIUs() { + Object[] selections = filteredTree.getCheckboxTreeViewer().getCheckedElements(); + if (selections.length == 0) + return new IInstallableUnit[0]; + ArrayList leaves = new ArrayList(selections.length); + for (int i = 0; i < selections.length; i++) { + if (!getCheckboxTreeViewer().getGrayed(selections[i])) { + IInstallableUnit iu = ProvUI.getAdapter(selections[i], IInstallableUnit.class); + if (iu != null && !ProvUI.isCategory(iu) && !leaves.contains(iu)) + leaves.add(iu); + } + } + return leaves.toArray(new IInstallableUnit[leaves.size()]); + } + + public Tree getTree() { + if (viewer == null) + return null; + return ((TreeViewer) viewer).getTree(); + } + + /* + * Make the repository with the specified location visible in the viewer. + */ + void makeRepositoryVisible(final URI location) { + // If we are viewing by anything other than site, there is no specific way + // to make a repo visible. + if (!(queryContext.getViewType() == IUViewQueryContext.AVAILABLE_VIEW_BY_REPO)) { + if (Display.getCurrent() == null) + display.asyncExec(new Runnable() { + public void run() { + updateAvailableViewState(); + } + }); + else + updateAvailableViewState(); + return; + } + // First reset the input so that the new repo shows up + Runnable runnable = new Runnable() { + public void run() { + final TreeViewer treeViewer = filteredTree.getViewer(); + final Tree tree = treeViewer.getTree(); + IWorkbench workbench = PlatformUI.getWorkbench(); + if (workbench.isClosing()) + return; + if (tree != null && !tree.isDisposed()) { + updateAvailableViewState(); + } + } + }; + if (Display.getCurrent() == null) + display.asyncExec(runnable); + else + runnable.run(); + // We don't know if loading will be a fast or slow operation. + // We do it in a job to be safe, and when it's done, we update + // the UI. + Job job = new Job(NLS.bind(ProvUIMessages.AvailableIUGroup_LoadingRepository, URIUtil.toUnencodedString(location))) { + protected IStatus run(IProgressMonitor monitor) { + try { + getProvisioningUI().loadMetadataRepository(location, true, monitor); + return Status.OK_STATUS; + } catch (ProvisionException e) { + return e.getStatus(); + } catch (OperationCanceledException e) { + return Status.CANCEL_STATUS; + } + } + }; + job.setPriority(Job.LONG); + job.setSystem(true); + job.setUser(false); + job.addJobChangeListener(new JobChangeAdapter() { + public void done(final IJobChangeEvent event) { + if (event.getResult().isOK()) + display.asyncExec(new Runnable() { + public void run() { + final TreeViewer treeViewer = filteredTree.getViewer(); + IWorkbench workbench = PlatformUI.getWorkbench(); + if (workbench.isClosing()) + return; + // Expand only if there have been no other jobs started for other repos. + if (event.getJob() == lastRequestedLoadJob) { + final Tree tree = treeViewer.getTree(); + if (tree != null && !tree.isDisposed()) { + TreeItem[] items = tree.getItems(); + for (int i = 0; i < items.length; i++) { + if (items[i].getData() instanceof IRepositoryElement) { + URI url = ((IRepositoryElement) items[i].getData()).getLocation(); + if (url.equals(location)) { + treeViewer.expandToLevel(items[i].getData(), AbstractTreeViewer.ALL_LEVELS); + tree.select(items[i]); + return; + } + } + } + } + } + } + }); + } + }); + lastRequestedLoadJob = job; + job.schedule(); + } + + public void updateAvailableViewState() { + if (getTree() == null || getTree().isDisposed()) + return; + final Composite parent = getComposite().getParent(); + setUseBoldFontForFilteredItems(queryContext.getViewType() != IUViewQueryContext.AVAILABLE_VIEW_FLAT); + + BusyIndicator.showWhile(display, new Runnable() { + public void run() { + parent.setRedraw(false); + getCheckboxTreeViewer().setInput(getNewInput()); + parent.layout(true); + parent.setRedraw(true); + } + }); + } + + public Control getDefaultFocusControl() { + if (filteredTree != null) + return filteredTree.getFilterControl(); + return null; + } + + protected GridData getViewerGridData() { + GridData data = super.getViewerGridData(); + data.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_HEIGHT); + return data; + } + + /** + * Set the checked elements to the specified selections. This method + * does not force visibility/expansion of the checked elements. If they are not + * visible, they will not be checked. + * @param selections + */ + public void setChecked(Object[] selections) { + filteredTree.getCheckboxTreeViewer().setCheckedElements(selections); + // Relying on knowledge that DelayedFilterCheckbox doesn't care which element is in the listener + Object element = selections.length > 0 ? selections[0] : new Object(); + filteredTree.getCheckboxTreeViewer().fireCheckStateChanged(element, true); + } + + public void setRepositoryFilter(int filterFlag, URI repoLocation) { + // If there has been no change, don't do anything. We will be + // clearing out selection caches in this method and should not do + // so if there's really no change. + if (filterConstant == filterFlag) { + if (filterConstant != AVAILABLE_SPECIFIED) + return; + if (repoLocation != null && repoLocation.equals(repositoryFilter)) + return; + } + filterConstant = filterFlag; + + switch (filterFlag) { + case AVAILABLE_ALL : + case AVAILABLE_NONE : + repositoryFilter = null; + repoFlags &= ~IRepositoryManager.REPOSITORIES_LOCAL; + break; + case AVAILABLE_LOCAL : + repositoryFilter = null; + repoFlags |= IRepositoryManager.REPOSITORIES_LOCAL; + break; + default : + repositoryFilter = repoLocation; + break; + } + updateAvailableViewState(); + filteredTree.clearCheckStateCache(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AvailableIUPatternFilter.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AvailableIUPatternFilter.java index 90d29f16b..502f86aeb 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AvailableIUPatternFilter.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AvailableIUPatternFilter.java @@ -12,9 +12,8 @@ package org.eclipse.equinox.internal.p2.ui.dialogs; import org.eclipse.equinox.internal.p2.ui.model.CategoryElement; import org.eclipse.equinox.internal.p2.ui.model.IIUElement; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.IUPropertyUtils; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.IUColumnConfig; +import org.eclipse.equinox.internal.p2.ui.viewers.IUColumnConfig; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.dialogs.PatternFilter; @@ -91,7 +90,7 @@ public class AvailableIUPatternFilter extends PatternFilter { IInstallableUnit iu = ((IIUElement) element).getIU(); if (checkName) { // Get the iu name in the default locale - text = IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_NAME); + text = iu.getProperty(IInstallableUnit.PROP_NAME, null); if (text != null && wordMatches(text)) return true; } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AvailableIUsPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AvailableIUsPage.java index 5abc0cfc7..fee436ce4 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AvailableIUsPage.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/AvailableIUsPage.java @@ -12,18 +12,13 @@ package org.eclipse.equinox.internal.p2.ui.dialogs; import java.net.URI; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.internal.p2.ui.*; import org.eclipse.equinox.internal.p2.ui.model.EmptyElementExplanation; -import org.eclipse.equinox.internal.p2.ui.viewers.IUDetailsLabelProvider; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.*; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.IUViewQueryContext; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.IUColumnConfig; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.StructuredViewerProvisioningListener; +import org.eclipse.equinox.internal.p2.ui.query.IUViewQueryContext; +import org.eclipse.equinox.internal.p2.ui.viewers.*; +import org.eclipse.equinox.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.IDialogConstants; @@ -50,10 +45,7 @@ public class AvailableIUsPage extends ProvisioningWizardPage implements ISelecta private static final String DETAILS_WEIGHT = "AvailableDetailsSashWeight"; //$NON-NLS-1$ private static final String LINKACTION = "linkAction"; //$NON-NLS-1$ - String profileId; - Policy policy; Object[] initialSelections; - QueryableMetadataRepositoryManager manager; IUViewQueryContext queryContext; AvailableIUGroup availableIUGroup; Composite availableIUButtonBar; @@ -67,11 +59,8 @@ public class AvailableIUsPage extends ProvisioningWizardPage implements ISelecta RepositorySelectionGroup repoSelector; IUDetailsGroup iuDetailsGroup; - public AvailableIUsPage(Policy policy, String profileId, QueryableMetadataRepositoryManager manager) { - super("AvailableSoftwarePage"); //$NON-NLS-1$ - this.policy = policy; - this.profileId = profileId; - this.manager = manager; + public AvailableIUsPage(ProvisioningUI ui, ProvisioningOperationWizard wizard) { + super("AvailableSoftwarePage", ui, wizard); //$NON-NLS-1$ makeQueryContext(); setTitle(ProvUIMessages.AvailableIUsPage_Title); setDescription(ProvUIMessages.AvailableIUsPage_Description); @@ -103,15 +92,15 @@ public class AvailableIUsPage extends ProvisioningWizardPage implements ISelecta sashForm.setLayoutData(data); // Now the available group - // If we have a repository manipulator, we want to default to showing no repos. Otherwise all. + // If repositories are visible, we want to default to showing no repos. Otherwise all. int filterConstant = AvailableIUGroup.AVAILABLE_NONE; - if (policy.getRepositoryManipulator() == null) + if (!getPolicy().getRepositoriesVisible()) filterConstant = AvailableIUGroup.AVAILABLE_ALL; nameColumn = new IUColumnConfig(ProvUIMessages.ProvUI_NameColumnTitle, IUColumnConfig.COLUMN_NAME, ILayoutConstants.DEFAULT_PRIMARY_COLUMN_WIDTH + 15); versionColumn = new IUColumnConfig(ProvUIMessages.ProvUI_VersionColumnTitle, IUColumnConfig.COLUMN_VERSION, ILayoutConstants.DEFAULT_COLUMN_WIDTH); getColumnWidthsFromSettings(); - availableIUGroup = new AvailableIUGroup(policy, sashForm, JFaceResources.getDialogFont(), manager, queryContext, new IUColumnConfig[] {nameColumn, versionColumn}, filterConstant); + availableIUGroup = new AvailableIUGroup(getProvisioningUI(), sashForm, JFaceResources.getDialogFont(), queryContext, new IUColumnConfig[] {nameColumn, versionColumn}, filterConstant); // Selection listeners must be registered on both the normal selection // events and the check mark events. Must be done after buttons @@ -216,7 +205,7 @@ public class AvailableIUsPage extends ProvisioningWizardPage implements ISelecta }, ProvUIMessages.AvailableIUsPage_GotoInstallInfo); installLink.setLayoutData(gd); - if (policy.getRepositoryManipulator() != null) { + if (getPolicy().getRepositoriesVisible()) { // Checkbox resolveAllCheckbox = new Button(parent, SWT.CHECK); resolveAllCheckbox.setText(ProvUIMessages.AvailableIUsPage_ResolveAllCheckbox); @@ -229,8 +218,8 @@ public class AvailableIUsPage extends ProvisioningWizardPage implements ISelecta private void createRepoArea(Composite parent) { // Site controls are only available if a repository manipulator // is specified. - if (policy.getRepositoryManipulator() != null) { - repoSelector = new RepositorySelectionGroup(getContainer(), parent, policy, queryContext); + if (getPolicy().getRepositoriesVisible()) { + repoSelector = new RepositorySelectionGroup(getProvisioningUI(), getContainer(), parent, queryContext); repoSelector.addRepositorySelectionListener(new IRepositorySelectionListener() { public void repositorySelectionChanged(int repoChoice, URI repoLocation) { repoComboSelectionChanged(repoChoice, repoLocation); @@ -256,10 +245,10 @@ public class AvailableIUsPage extends ProvisioningWizardPage implements ISelecta void updateQueryContext() { queryContext.setShowLatestVersionsOnly(showLatestVersionsCheckbox.getSelection()); if (hideInstalledCheckbox.getSelection()) - queryContext.hideAlreadyInstalled(profileId); + queryContext.hideAlreadyInstalled(getProfileId()); else { queryContext.showAlreadyInstalled(); - queryContext.setInstalledProfileId(profileId); + queryContext.setInstalledProfileId(getProfileId()); } if (useCategoriesCheckbox.getSelection()) queryContext.setViewType(IUViewQueryContext.AVAILABLE_VIEW_BY_CATEGORY); @@ -293,10 +282,10 @@ public class AvailableIUsPage extends ProvisioningWizardPage implements ISelecta } private void setDropTarget(Control control) { - if (policy.getRepositoryManipulator() != null) { + if (getPolicy().getRepositoriesVisible()) { DropTarget target = new DropTarget(control, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK); target.setTransfer(new Transfer[] {URLTransfer.getInstance(), FileTransfer.getInstance()}); - target.addDropListener(new RepositoryManipulatorDropTarget(policy.getRepositoryManipulator(), control)); + target.addDropListener(new RepositoryManipulatorDropTarget(getProvisioningUI(), control)); } } @@ -342,18 +331,14 @@ public class AvailableIUsPage extends ProvisioningWizardPage implements ISelecta private void makeQueryContext() { // Make a local query context that is based on the default. - IUViewQueryContext defaultQueryContext = policy.getQueryContext(); + IUViewQueryContext defaultQueryContext = ProvUI.getQueryContext(getPolicy()); queryContext = new IUViewQueryContext(defaultQueryContext.getViewType()); - queryContext.setArtifactRepositoryFlags(defaultQueryContext.getArtifactRepositoryFlags()); - queryContext.setMetadataRepositoryFlags(defaultQueryContext.getMetadataRepositoryFlags()); if (defaultQueryContext.getHideAlreadyInstalled()) { - queryContext.hideAlreadyInstalled(profileId); + queryContext.hideAlreadyInstalled(getProfileId()); } else { - queryContext.setInstalledProfileId(profileId); + queryContext.setInstalledProfileId(getProfileId()); } queryContext.setShowLatestVersionsOnly(defaultQueryContext.getShowLatestVersionsOnly()); - queryContext.setVisibleAvailableIUProperty(defaultQueryContext.getVisibleAvailableIUProperty()); - queryContext.setVisibleInstalledIUProperty(defaultQueryContext.getVisibleInstalledIUProperty()); // Now check for saved away dialog settings IDialogSettings settings = ProvUIActivator.getDefault().getDialogSettings(); IDialogSettings section = settings.getSection(DIALOG_SETTINGS_SECTION); @@ -377,9 +362,9 @@ public class AvailableIUsPage extends ProvisioningWizardPage implements ISelecta // Hide installed content boolean hideContent = section.getBoolean(HIDE_INSTALLED_IUS); if (hideContent) - queryContext.hideAlreadyInstalled(profileId); + queryContext.hideAlreadyInstalled(getProfileId()); else { - queryContext.setInstalledProfileId(profileId); + queryContext.setInstalledProfileId(getProfileId()); queryContext.showAlreadyInstalled(); } } @@ -459,11 +444,11 @@ public class AvailableIUsPage extends ProvisioningWizardPage implements ISelecta IInstallableUnit[] selected = getSelectedIUs(); if (selected.length == 1) { StringBuffer result = new StringBuffer(); - String description = IUPropertyUtils.getIUProperty(selected[0], IInstallableUnit.PROP_DESCRIPTION); + String description = selected[0].getProperty(IInstallableUnit.PROP_DESCRIPTION, null); if (description != null) { result.append(description); } else { - String name = IUPropertyUtils.getIUProperty(selected[0], IInstallableUnit.PROP_NAME); + String name = selected[0].getProperty(IInstallableUnit.PROP_NAME, null); if (name != null) result.append(name); else @@ -547,8 +532,8 @@ public class AvailableIUsPage extends ProvisioningWizardPage implements ISelecta } protected void profileChanged(String id) { - if (id.equals(profileId)) { - asyncRefresh(); + if (id.equals(getProfileId())) { + safeRefresh(); } } }; @@ -572,7 +557,7 @@ public class AvailableIUsPage extends ProvisioningWizardPage implements ISelecta public ProvisioningContext getProvisioningContext() { // If the user can't manipulate repos, always resolve against everything - if (policy.getRepositoryManipulator() == null || repoSelector == null) { + if (!getPolicy().getRepositoriesVisible() || repoSelector == null) { return new ProvisioningContext(); } // Consult the checkbox to see if we should resolve against everything, diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ComboAutoCompleteField.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ComboAutoCompleteField.java index 34cb29a84..62d1124ee 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ComboAutoCompleteField.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ComboAutoCompleteField.java @@ -54,7 +54,7 @@ public class ComboAutoCompleteField { if (contents.length() == 0 || items.length == 0) return new IContentProposal[0]; StringMatcher matcher = new StringMatcher("*" + contents + "*", true, false); //$NON-NLS-1$ //$NON-NLS-2$ - ArrayList matches = new ArrayList(); + ArrayList matches = new ArrayList(); for (int i = 0; i < items.length; i++) if (matcher.match(items[i])) matches.add(items[i]); @@ -63,7 +63,7 @@ public class ComboAutoCompleteField { // what is in the combo. This prevents the popup from // opening when the user is merely scrolling through the combo values or // has accepted a combo value. - if (matches.size() == 1 && ((String) matches.get(0)).equals(combo.getText())) + if (matches.size() == 1 && matches.get(0).equals(combo.getText())) return new IContentProposal[0]; if (matches.isEmpty()) @@ -72,7 +72,7 @@ public class ComboAutoCompleteField { // Make the proposals IContentProposal[] proposals = new IContentProposal[matches.size()]; for (int i = 0; i < matches.size(); i++) { - final String proposal = (String) matches.get(i); + final String proposal = matches.get(i); proposals[i] = new IContentProposal() { public String getContent() { @@ -367,7 +367,7 @@ public class ComboAutoCompleteField { } } - Vector temp = new Vector(); + Vector temp = new Vector(); int pos = 0; StringBuffer buf = new StringBuffer(); diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ContainerCheckedTreeViewer.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ContainerCheckedTreeViewer.java index b130cf45b..fef8274d3 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ContainerCheckedTreeViewer.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ContainerCheckedTreeViewer.java @@ -52,7 +52,7 @@ import org.eclipse.swt.widgets.*; public class ContainerCheckedTreeViewer extends CheckboxTreeViewer { private boolean rippleCheckMarks = true; - private ArrayList savedCheckState; + private ArrayList savedCheckState; /** * Constructor for ContainerCheckedTreeViewer. @@ -219,7 +219,7 @@ public class ContainerCheckedTreeViewer extends CheckboxTreeViewer { public Object[] getCheckedElements() { Object[] checked = super.getCheckedElements(); // add all items that are children of a checked node but not created yet - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList(); for (int i = 0; i < checked.length; i++) { Object curr = checked[i]; result.add(curr); @@ -241,7 +241,7 @@ public class ContainerCheckedTreeViewer extends CheckboxTreeViewer { * @param element * @param result */ - private void collectChildren(Object element, ArrayList result) { + private void collectChildren(Object element, ArrayList result) { Object[] filteredChildren = getFilteredChildren(element); for (int i = 0; i < filteredChildren.length; i++) { Object curr = filteredChildren[i]; @@ -276,7 +276,7 @@ public class ContainerCheckedTreeViewer extends CheckboxTreeViewer { // problem. private void saveCheckedState() { Object[] checked = getCheckedElements(); - savedCheckState = new ArrayList(checked.length); + savedCheckState = new ArrayList(checked.length); for (int i = 0; i < checked.length; i++) if (!isExpandable(checked[i]) && !getGrayed(checked[i])) savedCheckState.add(checked[i]); @@ -288,7 +288,7 @@ public class ContainerCheckedTreeViewer extends CheckboxTreeViewer { setGrayedElements(new Object[0]); Object element = null; // We are assuming that once a leaf, always a leaf. - Iterator iter = savedCheckState.iterator(); + Iterator iter = savedCheckState.iterator(); while (iter.hasNext()) { element = iter.next(); setChecked(element, true); diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/CopyHandler.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/CopyHandler.java index 1337a8d73..65025680f 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/CopyHandler.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/CopyHandler.java @@ -13,6 +13,7 @@ package org.eclipse.equinox.internal.p2.ui.dialogs; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.equinox.p2.ui.ICopyable; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.ISources; import org.eclipse.ui.handlers.HandlerUtil; diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/CopyPopup.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/CopyPopup.java index 98cf8248a..daa80f769 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/CopyPopup.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/CopyPopup.java @@ -11,6 +11,7 @@ package org.eclipse.equinox.internal.p2.ui.dialogs; +import org.eclipse.equinox.p2.ui.ICopyable; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/CopyUtils.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/CopyUtils.java index b34874a66..d3e03e5e9 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/CopyUtils.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/CopyUtils.java @@ -14,6 +14,7 @@ package org.eclipse.equinox.internal.p2.ui.dialogs; import org.eclipse.core.expressions.*; import org.eclipse.equinox.internal.p2.ui.model.ProvElement; import org.eclipse.equinox.internal.p2.ui.viewers.IUDetailsLabelProvider; +import org.eclipse.equinox.p2.ui.ICopyable; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.widgets.Control; diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/DelayedFilterCheckboxTree.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/DelayedFilterCheckboxTree.java index 56de63a8d..7ab3f775d 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/DelayedFilterCheckboxTree.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/DelayedFilterCheckboxTree.java @@ -11,14 +11,12 @@ package org.eclipse.equinox.internal.p2.ui.dialogs; import java.util.*; -import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.*; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.model.QueriedElement; +import org.eclipse.equinox.internal.p2.ui.model.RootElement; import org.eclipse.equinox.internal.p2.ui.viewers.DeferredQueryContentProvider; import org.eclipse.equinox.internal.p2.ui.viewers.IInputChangeListener; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner; -import org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.viewers.*; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; @@ -39,7 +37,6 @@ import org.eclipse.ui.progress.WorkbenchJob; */ public class DelayedFilterCheckboxTree extends FilteredTree { - private static final String LOAD_JOB_NAME = ProvUIMessages.DeferredFetchFilteredTree_RetrievingList; private static final long FILTER_DELAY = 400; ToolBar toolBar; @@ -51,8 +48,8 @@ public class DelayedFilterCheckboxTree extends FilteredTree { WorkbenchJob filterJob; boolean ignoreFiltering = true; Object viewerInput; - ArrayList checkState = new ArrayList(); - Set expanded = new HashSet(); + ArrayList checkState = new ArrayList(); + Set expanded = new HashSet(); ContainerCheckedTreeViewer checkboxViewer; public DelayedFilterCheckboxTree(Composite parent, int treeStyle, PatternFilter filter) { @@ -69,10 +66,8 @@ public class DelayedFilterCheckboxTree extends FilteredTree { // We use an additive check state cache so we need to remove // previously checked items if the user unchecked them. if (!event.getChecked() && checkState != null) { - Iterator iter = checkState.iterator(); - ArrayList toRemove = new ArrayList(1); - while (iter.hasNext()) { - Object element = iter.next(); + ArrayList toRemove = new ArrayList(1); + for (Object element : checkState) { if (checkboxViewer.getComparer().equals(element, event.getElement())) { toRemove.add(element); // Do not break out of the loop. We may have duplicate equal @@ -122,6 +117,8 @@ public class DelayedFilterCheckboxTree extends FilteredTree { checkboxViewer.getTree().setRedraw(false); display.asyncExec(new Runnable() { public void run() { + if (checkboxViewer.getTree().isDisposed()) + return; rememberExpansions(); restoreLeafCheckState(); rememberExpansions(); @@ -195,6 +192,9 @@ public class DelayedFilterCheckboxTree extends FilteredTree { if (event.getResult().isOK()) { display.asyncExec(new Runnable() { public void run() { + if (checkboxViewer.getTree().isDisposed()) + return; + checkboxViewer.getTree().setRedraw(false); // remember things expanded by the filter rememberExpansions(); @@ -214,22 +214,12 @@ public class DelayedFilterCheckboxTree extends FilteredTree { void scheduleLoadJob() { if (loadJob != null) return; - loadJob = new Job(LOAD_JOB_NAME) { - protected IStatus run(IProgressMonitor monitor) { - QueryableMetadataRepositoryManager q = null; - if (viewerInput instanceof QueryableMetadataRepositoryManager) - q = (QueryableMetadataRepositoryManager) viewerInput; - else if (viewerInput instanceof QueriedElement && ((QueriedElement) viewerInput).getQueryable() instanceof QueryableMetadataRepositoryManager) - q = (QueryableMetadataRepositoryManager) ((QueriedElement) viewerInput).getQueryable(); - if (q != null) { - q.loadAll(monitor); - q.reportAccumulatedStatus(); - } - if (monitor.isCanceled()) - return Status.CANCEL_STATUS; - return Status.OK_STATUS; - } - }; + ProvisioningUI ui; + if (viewerInput instanceof RootElement) + ui = ((RootElement) viewerInput).getProvisioningUI(); + else + ui = ProvisioningUI.getDefaultUI(); + loadJob = new LoadMetadataRepositoryJob(ui); loadJob.addJobChangeListener(new JobChangeAdapter() { public void done(IJobChangeEvent event) { if (event.getResult().isOK()) { @@ -243,9 +233,6 @@ public class DelayedFilterCheckboxTree extends FilteredTree { }); loadJob.setSystem(true); loadJob.setUser(false); - // Telling the operation runner about it ensures that listeners know we are running - // a provisioning-related job. - ProvisioningOperationRunner.manageJob(loadJob); loadJob.schedule(); } @@ -267,7 +254,7 @@ public class DelayedFilterCheckboxTree extends FilteredTree { ContainerCheckedTreeViewer v = (ContainerCheckedTreeViewer) getViewer(); Object[] checked = v.getCheckedElements(); if (checkState == null) - checkState = new ArrayList(checked.length); + checkState = new ArrayList(checked.length); for (int i = 0; i < checked.length; i++) if (!v.getGrayed(checked[i]) && contentProvider.getChildren(checked[i]).length == 0) if (!checkState.contains(checked[i])) @@ -284,7 +271,7 @@ public class DelayedFilterCheckboxTree extends FilteredTree { checkboxViewer.setGrayedElements(new Object[0]); // Now we are only going to set the check state of the leaf nodes // and rely on our container checked code to update the parents properly. - Iterator iter = checkState.iterator(); + Iterator iter = checkState.iterator(); Object element = null; if (iter.hasNext()) checkboxViewer.expandAll(); diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ICopyable.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ICopyable.java deleted file mode 100644 index aec006548..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ICopyable.java +++ /dev/null @@ -1,23 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.ui.dialogs; - -import org.eclipse.swt.widgets.Control; - -/** - * ICopyable defines an interface for UI elements that provide - * copy support. - * - * @since 3.5 - */ -public interface ICopyable { - public void copyToClipboard(Control activeControl); -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IRepositorySelectionListener.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IRepositorySelectionListener.java new file mode 100644 index 000000000..fdbdd1925 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IRepositorySelectionListener.java @@ -0,0 +1,29 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.dialogs; + +import java.net.URI; + +/** + * Listener for the repository selection combo. Whenever the selected repository changes (menu selection, + * text modified, new repo added) this listener will be notified. + * + * @since 3.5 + */ +public interface IRepositorySelectionListener { + /** + * Called whenever the selected repository in the combo changes. + * + * @param repoChoice one of AvailableIUGroup.AVAILABLE_NONE, AvailableIUGroup.AVAILABLE_ALL, AvailableIUGroup.AVAILABLE_LOCAL, AvailableIUGroup.AVAILABLE_SPECIFIED + * @param repoLocation if the repoChoice is set to AvailableIUGroup.AVAILABLE_SPECIFIED, this field will contain the URI of the selected repo, otherwise null + */ + public void repositorySelectionChanged(int repoChoice, URI repoLocation); +} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IResolutionErrorReportingPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IResolutionErrorReportingPage.java index 7c38efd84..9b62a6c30 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IResolutionErrorReportingPage.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IResolutionErrorReportingPage.java @@ -11,8 +11,8 @@ package org.eclipse.equinox.internal.p2.ui.dialogs; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; +import org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; /** * @@ -23,5 +23,5 @@ import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResoluti * */ public interface IResolutionErrorReportingPage extends ISelectableIUsPage { - public void updateStatus(IUElementListRoot root, PlannerResolutionOperation resolvedOperation); + public void updateStatus(IUElementListRoot root, ProfileChangeOperation operation); } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUCopyrightPropertyPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUCopyrightPropertyPage.java new file mode 100644 index 000000000..6eebf3e56 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUCopyrightPropertyPage.java @@ -0,0 +1,80 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.dialogs; + +import java.net.MalformedURLException; +import org.eclipse.core.runtime.URIUtil; +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.p2.metadata.ICopyright; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.osgi.util.NLS; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.*; + +/** + * PropertyPage that shows an IU's copyright + * + * @since 3.4 + */ +public class IUCopyrightPropertyPage extends IUPropertyPage { + + protected Control createIUPage(Composite parent, IInstallableUnit iu) { + // Get the copyright in the current locale + final ICopyright copyright = iu.getCopyright(null); + if (copyright != null && copyright.getBody().length() > 0) { + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + + Text text = new Text(composite, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER | SWT.WRAP); + GridData gd = new GridData(SWT.FILL, SWT.FILL, false, true); + gd.widthHint = computeWidthLimit(text, 80); + gd.grabExcessVerticalSpace = true; + text.setLayoutData(gd); + text.setText(copyright.getBody()); + text.setEditable(false); + + // If an URL was specified, provide a link to it + String filename = (copyright.getLocation() != null) ? copyright.getLocation().getPath() : null; + if (filename != null && (filename.endsWith(".htm") || filename.endsWith(".html"))) { //$NON-NLS-1$ //$NON-NLS-2$ + Label label = new Label(composite, SWT.NONE); + label.setText(ProvUIMessages.IUCopyrightPropertyPage_ViewLinkLabel); + // Create a link to the copyright URL + Link link = new Link(composite, SWT.LEFT | SWT.WRAP); + link.setText(NLS.bind("{0}", URIUtil.toUnencodedString(copyright.getLocation()))); //$NON-NLS-1$ + gd = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); + gd.widthHint = computeWidthLimit(link, 80); + link.setLayoutData(gd); + link.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + try { + showURL(copyright.getLocation().toURL()); + } catch (MalformedURLException e1) { + //cannot show this URL + } + } + }); + } + + return composite; + } + Label label = new Label(parent, SWT.NULL); + label.setText(ProvUIMessages.IUCopyrightPropertyPage_NoCopyright); + return label; + + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUDetailsGroup.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUDetailsGroup.java index 733c36c4b..8ae5ffefb 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUDetailsGroup.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUDetailsGroup.java @@ -11,7 +11,7 @@ package org.eclipse.equinox.internal.p2.ui.dialogs; import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.PropertyDialogAction; +import org.eclipse.equinox.internal.p2.ui.actions.PropertyDialogAction; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUGeneralInfoPropertyPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUGeneralInfoPropertyPage.java new file mode 100644 index 000000000..cca891543 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUGeneralInfoPropertyPage.java @@ -0,0 +1,141 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.dialogs; + +import java.net.MalformedURLException; +import java.net.URL; +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.osgi.util.NLS; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.*; + +/** + * PropertyPage that shows an IU's properties + * + * @since 3.4 + */ +public class IUGeneralInfoPropertyPage extends IUPropertyPage { + + protected Control createIUPage(Composite parent, IInstallableUnit iu) { + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + + createGeneralSection(composite, iu); + createDescriptionSection(composite, iu); + createDocumentationSection(composite, iu); + + return composite; + } + + private void createGeneralSection(Composite parent, IInstallableUnit iu) { + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + // Get general info in the default locale + addField(composite, ProvUIMessages.IUGeneralInfoPropertyPage_NameLabel, iu.getProperty(IInstallableUnit.PROP_NAME, null)); + addField(composite, ProvUIMessages.IUGeneralInfoPropertyPage_IdentifierLabel, iu.getId()); + addField(composite, ProvUIMessages.IUGeneralInfoPropertyPage_VersionLabel, iu.getVersion().toString()); + addField(composite, ProvUIMessages.IUGeneralInfoPropertyPage_ProviderLabel, iu.getProperty(IInstallableUnit.PROP_PROVIDER, null)); + addField(composite, ProvUIMessages.IUGeneralInfoPropertyPage_ContactLabel, iu.getProperty(IInstallableUnit.PROP_CONTACT, null)); + + } + + private void createDescriptionSection(Composite parent, IInstallableUnit iu) { + // Get the iu description in the default locale + String description = iu.getProperty(IInstallableUnit.PROP_DESCRIPTION, null); + if (description != null && description.length() > 0) { + Group group = new Group(parent, SWT.NONE); + group.setText(ProvUIMessages.IUGeneralInfoPropertyPage_DescriptionLabel); + group.setLayout(new GridLayout()); + group.setLayoutData(new GridData(GridData.FILL_BOTH)); + + Text text = new Text(group, SWT.MULTI | SWT.WRAP | SWT.READ_ONLY | SWT.V_SCROLL); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + gd.widthHint = computeWidthLimit(text, 80); + gd.heightHint = 200; + text.setEditable(false); + text.setText(description); + text.setLayoutData(gd); + } + + } + + private void createDocumentationSection(Composite parent, IInstallableUnit iu) { + String docURL = iu.getProperty(IInstallableUnit.PROP_DOC_URL); + if (docURL != null && docURL.length() > 0) { + final URL url; + try { + url = new URL(docURL); + } catch (MalformedURLException e) { + return; + } + String filename = (url != null) ? url.getFile() : null; + if (filename != null && (filename.endsWith(".htm") || filename.endsWith(".html"))) { //$NON-NLS-1$ //$NON-NLS-2$ + // create some space + new Label(parent, SWT.NONE); + // Now create a link to the documentation + Label label = new Label(parent, SWT.NONE); + label.setText(ProvUIMessages.IUGeneralInfoPropertyPage_DocumentationLink); + Link link = new Link(parent, SWT.LEFT | SWT.WRAP); + link.setText(NLS.bind("{0}", url.toExternalForm())); //$NON-NLS-1$ + GridData gd = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); + gd.widthHint = computeWidthLimit(link, 80); + link.setLayoutData(gd); + link.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + showURL(url); + } + }); + } + } + } + + private void addField(Composite parent, String property, String value) { + + if (value != null && value.length() > 0) { + Label label = new Label(parent, SWT.NONE); + label.setText(property); + + Text text = new Text(parent, SWT.WRAP | SWT.READ_ONLY); + text.setText(getEscapedString(value)); + // Needed to get the right color on the Mac. + // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=258112 + text.setBackground(text.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + text.setLayoutData(gd); + } + } + + private String getEscapedString(String value) { + StringBuffer result = new StringBuffer(value.length() + 10); + for (int i = 0; i < value.length(); ++i) { + char c = value.charAt(i); + if ('&' == c) { + result.append("&&"); //$NON-NLS-1$ + } else { + result.append(c); + } + } + return result.toString(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IULicensePropertyPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IULicensePropertyPage.java new file mode 100644 index 000000000..685e654c0 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IULicensePropertyPage.java @@ -0,0 +1,83 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.dialogs; + +import org.eclipse.equinox.p2.metadata.ILicense; + +import org.eclipse.core.runtime.URIUtil; +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.osgi.util.NLS; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.*; + +/** + * PropertyPage that shows an IU's license + * + * @since 3.4 + */ +public class IULicensePropertyPage extends IUPropertyPage { + + protected Control createIUPage(Composite parent, IInstallableUnit iu) { + // Get the license in the default locale + ILicense[] licenses = iu.getLicenses(null); + final ILicense license; + //FIXME + if (licenses.length > 0 && licenses[0].getBody() != null && licenses[0].getBody().length() > 0) { + license = licenses[0]; + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + + Text text = new Text(composite, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER | SWT.WRAP); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + gd.widthHint = computeWidthLimit(text, 80); + gd.heightHint = computeHeightLimit(text, 20); + text.setLayoutData(gd); + text.setText(license.getBody()); + text.setEditable(false); + + // If an URL was specified, provide a link to it + String filename = (license.getLocation() != null) ? license.getLocation().getPath() : null; + if (filename != null && (filename.endsWith(".htm") || filename.endsWith(".html"))) { //$NON-NLS-1$ //$NON-NLS-2$ + Label label = new Label(composite, SWT.NONE); + label.setText(ProvUIMessages.IULicensePropertyPage_ViewLicenseLabel); + // Create a link to the license URL + Link link = new Link(composite, SWT.LEFT | SWT.WRAP); + link.setText(NLS.bind("{0}", URIUtil.toUnencodedString(license.getLocation()))); //$NON-NLS-1$ + gd = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); + gd.widthHint = computeWidthLimit(link, 80); + link.setLayoutData(gd); + link.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + try { + showURL(license.getLocation().toURL()); + } catch (Exception e1) { + //can't browse invalid location + } + } + }); + } + + return composite; + } + Label label = new Label(parent, SWT.NULL); + label.setText(ProvUIMessages.IULicensePropertyPage_NoLicense); + return label; + + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUPropertyPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUPropertyPage.java index 4c1a33c53..5109868fd 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUPropertyPage.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/IUPropertyPage.java @@ -11,9 +11,9 @@ package org.eclipse.equinox.internal.p2.ui.dialogs; import java.net.URL; +import org.eclipse.equinox.internal.p2.ui.ProvUI; import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.FontMetrics; @@ -35,7 +35,7 @@ public abstract class IUPropertyPage extends PropertyPage { protected Control createContents(Composite parent) { noDefaultAndApplyButton(); - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(getElement(), IInstallableUnit.class); + IInstallableUnit iu = ProvUI.getAdapter(getElement(), IInstallableUnit.class); Control control; if (iu == null) { Label label = new Label(parent, SWT.DEFAULT); diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/InstallWizard.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/InstallWizard.java new file mode 100644 index 000000000..1bf65a96d --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/InstallWizard.java @@ -0,0 +1,144 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.dialogs; + +import org.eclipse.equinox.internal.p2.ui.model.AvailableIUElement; + +import java.util.ArrayList; +import org.eclipse.equinox.internal.p2.ui.ProvUIImages; +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.internal.p2.ui.model.*; +import org.eclipse.equinox.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.InstallOperation; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.swt.widgets.Composite; + +/** + * An install wizard that allows the users to browse all of the repositories + * and search/select for items to install. + * + * @since 3.6 + */ +public class InstallWizard extends WizardWithLicenses { + + SelectableIUsPage errorReportingPage; + IUElementListRoot originalRoot; + + public InstallWizard(ProvisioningUI ui, InstallOperation operation, IInstallableUnit[] initialSelections, LoadMetadataRepositoryJob preloadJob) { + super(ui, operation, initialSelections, preloadJob); + setWindowTitle(ProvUIMessages.InstallIUOperationLabel); + setDefaultPageImageDescriptor(ProvUIImages.getImageDescriptor(ProvUIImages.WIZARD_BANNER_INSTALL)); + } + + protected ResolutionResultsWizardPage createResolutionPage() { + return new InstallWizardPage(ui, this, root, (InstallOperation) operation); + } + + protected ISelectableIUsPage createMainPage(IUElementListRoot input, Object[] selections) { + mainPage = new AvailableIUsPage(ui, this); + if (selections != null && selections.length > 0) + mainPage.setCheckedElements(selections); + return mainPage; + + } + + protected void initializeResolutionModelElements(Object[] selectedElements) { + if (selectedElements == null) + return; + root = new IUElementListRoot(); + ArrayList list = new ArrayList(selectedElements.length); + ArrayList selections = new ArrayList(selectedElements.length); + for (int i = 0; i < selectedElements.length; i++) { + IInstallableUnit iu = ElementUtils.getIU(selectedElements[i]); + if (iu != null) { + AvailableIUElement element = new AvailableIUElement(root, iu, getProfileId(), shouldShowProvisioningPlanChildren()); + list.add(element); + selections.add(element); + } + } + root.setChildren(list.toArray()); + planSelections = selections.toArray(); + } + + public void createPageControls(Composite pageContainer) { + super.createPageControls(pageContainer); + if (repoPreloadJob != null) + // async exec since we are in the middle of opening + pageContainer.getDisplay().asyncExec(new Runnable() { + public void run() { + repoPreloadJob.reportAccumulatedStatus(); + } + }); + } + + protected ProvisioningContext getProvisioningContext() { + return ((AvailableIUsPage) mainPage).getProvisioningContext(); + } + + protected IResolutionErrorReportingPage createErrorReportingPage() { + if (root == null) + errorReportingPage = new SelectableIUsPage(ui, this, null, null); + else + errorReportingPage = new SelectableIUsPage(ui, this, root, root.getChildren(root)); + errorReportingPage.setTitle(ProvUIMessages.InstallWizardPage_Title); + errorReportingPage.setDescription(ProvUIMessages.PreselectedIUInstallWizard_Description); + errorReportingPage.updateStatus(root, operation); + return errorReportingPage; + } + + protected void planChanged() { + // the superclass may change the page root when we don't wish this to happen. + // The code below will correct that case. We set redraw to avoid a big flash. + errorReportingPage.getControl().setRedraw(false); + try { + super.planChanged(); + // We don't want the root of the error page to change unless we are on the + // main page. For example, if we are on the error page, change checkmarks, and + // resolve again with an error, we wouldn't want the root items to change in the + // error page. + if (getContainer().getCurrentPage() == mainPage) { + originalRoot = root; + } else { + errorReportingPage.updateStatus(originalRoot, operation); + } + // we always update the checkmarks to the current root + errorReportingPage.setCheckedElements(root.getChildren(root)); + } finally { + errorReportingPage.getControl().setRedraw(true); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.wizard.Wizard#getPreviousPage(org.eclipse.jface.wizard.IWizardPage) + */ + public IWizardPage getPreviousPage(IWizardPage page) { + if (page == errorReportingPage) { + mainPage.setCheckedElements(errorReportingPage.getCheckedIUElements()); + return mainPage; + } + return super.getPreviousPage(page); + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.dialogs.ProvisioningOperationWizard#getProfileChangeOperation(java.lang.Object[]) + */ + protected ProfileChangeOperation getProfileChangeOperation(Object[] elements) { + InstallOperation op = new InstallOperation(ui.getSession(), ElementUtils.elementsToIUs(elements)); + op.setProfileId(getProfileId()); + // op.setRootMarkerKey(getRootMarkerKey()); + return op; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/InstallWizardPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/InstallWizardPage.java index 46078100d..8c260697f 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/InstallWizardPage.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/InstallWizardPage.java @@ -11,14 +11,14 @@ package org.eclipse.equinox.internal.p2.ui.dialogs; import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot; +import org.eclipse.equinox.p2.operations.InstallOperation; +import org.eclipse.equinox.p2.ui.ProvisioningUI; public class InstallWizardPage extends SizeComputingWizardPage { - public InstallWizardPage(Policy policy, String profileId, IUElementListRoot root, PlannerResolutionOperation initialResolution) { - super(policy, root, profileId, initialResolution); + public InstallWizardPage(ProvisioningUI ui, ProvisioningOperationWizard wizard, IUElementListRoot root, InstallOperation operation) { + super(ui, wizard, root, operation); setTitle(ProvUIMessages.InstallWizardPage_Title); setDescription(ProvUIMessages.InstallWizardPage_NoCheckboxDescription); } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/InstalledIUGroup.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/InstalledIUGroup.java new file mode 100644 index 000000000..ceb7ab4fc --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/InstalledIUGroup.java @@ -0,0 +1,111 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.dialogs; + +import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; +import org.eclipse.equinox.internal.p2.ui.ProvUIProvisioningListener; +import org.eclipse.equinox.internal.p2.ui.model.ProfileElement; +import org.eclipse.equinox.internal.p2.ui.viewers.*; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.viewers.StructuredViewer; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.DisposeEvent; +import org.eclipse.swt.events.DisposeListener; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.widgets.*; + +/** + * An InstalledIUGroup is a reusable UI component that displays the + * IU's in a given profile. + * + * @since 3.4 + */ +public class InstalledIUGroup extends StructuredIUGroup { + + private String profileId; + + /** + * Create a group that represents the installed IU's. + * + * @param parent the parent composite for the group + * @param font The font to use for calculating pixel sizes. This font is + * not managed by the receiver. + * @param profileId the id of the profile whose content is being shown. + * @param columnConfig the columns to be shown + */ + public InstalledIUGroup(ProvisioningUI ui, final Composite parent, Font font, String profileId, IUColumnConfig[] columnConfig) { + super(ui, parent, font, columnConfig); + if (profileId == null) + this.profileId = ProvisioningUI.getDefaultUI().getProfileId(); + else + this.profileId = profileId; + createGroupComposite(parent); + } + + protected StructuredViewer createViewer(Composite parent) { + // Table of installed IU's + TreeViewer installedIUViewer = new TreeViewer(parent, SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); + + // Filters and sorters before establishing content, so we don't refresh unnecessarily. + IUComparator comparator = new IUComparator(IUComparator.IU_NAME); + comparator.useColumnConfig(getColumnConfig()); + installedIUViewer.setComparator(comparator); + installedIUViewer.setComparer(new ProvElementComparer()); + + // Now the content. + installedIUViewer.setContentProvider(new DeferredQueryContentProvider()); + + // Now the visuals, columns before labels. + setTreeColumns(installedIUViewer.getTree()); + installedIUViewer.setLabelProvider(new IUDetailsLabelProvider(null, getColumnConfig(), null)); + + // Input last. + installedIUViewer.setInput(getInput()); + + final StructuredViewerProvisioningListener listener = new StructuredViewerProvisioningListener(installedIUViewer, ProvUIProvisioningListener.PROV_EVENT_IU | ProvUIProvisioningListener.PROV_EVENT_PROFILE); + ProvUIActivator.getDefault().addProvisioningListener(listener); + installedIUViewer.getControl().addDisposeListener(new DisposeListener() { + public void widgetDisposed(DisposeEvent e) { + ProvUIActivator.getDefault().removeProvisioningListener(listener); + } + }); + return installedIUViewer; + } + + private void setTreeColumns(Tree tree) { + IUColumnConfig[] columns = getColumnConfig(); + tree.setHeaderVisible(true); + + for (int i = 0; i < columns.length; i++) { + TreeColumn tc = new TreeColumn(tree, SWT.NONE, i); + tc.setResizable(true); + tc.setText(columns[i].getColumnTitle()); + tc.setWidth(columns[i].getWidthInPixels(tree)); + } + } + + Object getInput() { + ProfileElement element = new ProfileElement(null, profileId); + return element; + } + + /** + * Get the viewer used to represent the installed IU's + */ + public StructuredViewer getStructuredViewer() { + return super.getStructuredViewer(); + } + + public Control getDefaultFocusControl() { + return super.getDefaultFocusControl(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/PreselectedIUInstallWizard.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/PreselectedIUInstallWizard.java new file mode 100644 index 000000000..45d4f22dc --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/PreselectedIUInstallWizard.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.dialogs; + +import org.eclipse.equinox.internal.p2.ui.model.AvailableIUElement; + +import java.util.ArrayList; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.model.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.InstallOperation; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; +import org.eclipse.equinox.p2.ui.ProvisioningUI; + +/** + * An Install wizard that is invoked when the user has already selected which + * IUs should be installed and does not need to browse the available software. + * + * @since 3.5 + */ +public class PreselectedIUInstallWizard extends WizardWithLicenses { + + QueryableMetadataRepositoryManager manager; + + public PreselectedIUInstallWizard(ProvisioningUI ui, InstallOperation operation, IInstallableUnit[] initialSelections, LoadMetadataRepositoryJob job) { + super(ui, operation, initialSelections, job); + setWindowTitle(ProvUIMessages.InstallIUOperationLabel); + setDefaultPageImageDescriptor(ProvUIImages.getImageDescriptor(ProvUIImages.WIZARD_BANNER_INSTALL)); + } + + protected ISelectableIUsPage createMainPage(IUElementListRoot input, Object[] selections) { + mainPage = new SelectableIUsPage(ui, this, input, selections); + mainPage.setTitle(ProvUIMessages.PreselectedIUInstallWizard_Title); + mainPage.setDescription(ProvUIMessages.PreselectedIUInstallWizard_Description); + ((SelectableIUsPage) mainPage).updateStatus(input, operation); + return mainPage; + } + + protected ResolutionResultsWizardPage createResolutionPage() { + return new InstallWizardPage(ui, this, root, (InstallOperation) operation); + } + + protected void initializeResolutionModelElements(Object[] selectedElements) { + root = new IUElementListRoot(); + ArrayList list = new ArrayList(selectedElements.length); + ArrayList selected = new ArrayList(selectedElements.length); + for (int i = 0; i < selectedElements.length; i++) { + IInstallableUnit iu = ElementUtils.getIU(selectedElements[i]); + if (iu != null) { + AvailableIUElement element = new AvailableIUElement(root, iu, getProfileId(), shouldShowProvisioningPlanChildren()); + list.add(element); + selected.add(element); + } + } + root.setChildren(list.toArray()); + planSelections = selected.toArray(); + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.dialogs.ProvisioningOperationWizard#getErrorReportingPage() + */ + protected IResolutionErrorReportingPage createErrorReportingPage() { + return (IResolutionErrorReportingPage) mainPage; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.dialogs.ProvisioningOperationWizard#getProfileChangeOperation(java.lang.Object[]) + */ + protected ProfileChangeOperation getProfileChangeOperation(Object[] elements) { + InstallOperation op = new InstallOperation(ui.getSession(), ElementUtils.elementsToIUs(elements)); + op.setProfileId(getProfileId()); + // op.setRootMarkerKey(getRootMarkerKey()); + op.setProvisioningContext(getProvisioningContext()); + return op; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProvisioningOperationWizard.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProvisioningOperationWizard.java index cf39d0cd4..f2d38fe8c 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProvisioningOperationWizard.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProvisioningOperationWizard.java @@ -10,19 +10,18 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.dialogs; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; + import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.HashSet; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.ui.*; import org.eclipse.equinox.internal.p2.ui.model.ElementUtils; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot; +import org.eclipse.equinox.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.ui.*; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.wizard.IWizardPage; @@ -39,30 +38,25 @@ public abstract class ProvisioningOperationWizard extends Wizard { private static final String WIZARD_SETTINGS_SECTION = "WizardSettings"; //$NON-NLS-1$ - protected Policy policy; - protected String profileId; - protected IUElementListRoot root, originalRoot; - protected PlannerResolutionOperation resolutionOperation; - private Object[] planSelections; + protected ProvisioningUI ui; + protected IUElementListRoot root; + protected ProfileChangeOperation operation; + protected Object[] planSelections; protected ISelectableIUsPage mainPage; protected IResolutionErrorReportingPage errorPage; protected ResolutionResultsWizardPage resolutionPage; private ProvisioningContext provisioningContext; - boolean couldNotResolve; + protected LoadMetadataRepositoryJob repoPreloadJob; + IStatus couldNotResolveStatus = Status.OK_STATUS; // we haven't tried and failed boolean waitingForOtherJobs = false; - public ProvisioningOperationWizard(Policy policy, String profileId, IUElementListRoot root, Object[] initialSelections, PlannerResolutionOperation initialResolution) { + public ProvisioningOperationWizard(ProvisioningUI ui, ProfileChangeOperation operation, Object[] initialSelections, LoadMetadataRepositoryJob job) { super(); - this.policy = policy; - this.profileId = profileId; - this.root = root; - this.originalRoot = root; - this.resolutionOperation = initialResolution; - if (initialSelections == null) - planSelections = new Object[0]; - else - planSelections = initialSelections; + this.ui = ui; + initializeResolutionModelElements(initialSelections); + this.operation = operation; + this.repoPreloadJob = job; setForcePreviousAndNextButtons(true); setNeedsProgressMonitor(true); } @@ -74,9 +68,14 @@ public abstract class ProvisioningOperationWizard extends Wizard { public void addPages() { mainPage = createMainPage(root, planSelections); addPage(mainPage); + errorPage = createErrorReportingPage(); + if (errorPage != mainPage) + addPage(errorPage); + resolutionPage = createResolutionPage(); + addPage(resolutionPage); } - protected abstract IResolutionErrorReportingPage getErrorReportingPage(); + protected abstract IResolutionErrorReportingPage createErrorReportingPage(); protected abstract ISelectableIUsPage createMainPage(IUElementListRoot input, Object[] selections); @@ -86,23 +85,8 @@ public abstract class ProvisioningOperationWizard extends Wizard { return resolutionPage.performFinish(); } - /* - * (non-Javadoc) - * @see org.eclipse.jface.wizard.Wizard#canFinish() - */ - public boolean canFinish() { - if (resolutionPage == null) - return false; - if (!super.canFinish()) - return false; - // Special case. The error reporting page has to be complete in - // order to press next and perform a resolution. But that doesn't - // mean the wizard can finish. - if (resolutionOperation != null) { - int severity = resolutionOperation.getResolutionResult().getSummaryStatus().getSeverity(); - return severity != IStatus.ERROR && severity != IStatus.CANCEL; - } - return false; + protected LoadMetadataRepositoryJob getRepositoryPreloadJob() { + return repoPreloadJob; } /* @@ -110,75 +94,43 @@ public abstract class ProvisioningOperationWizard extends Wizard { * @see org.eclipse.jface.wizard.Wizard#getNextPage(org.eclipse.jface.wizard.IWizardPage) */ public IWizardPage getNextPage(IWizardPage page) { + // If we are moving from the main page or error page, we may need to resolve before + // advancing. if (page == mainPage || page == errorPage) { ISelectableIUsPage currentPage = (ISelectableIUsPage) page; // Do we need to resolve? - boolean weResolved = false; - if (resolutionOperation == null || (resolutionOperation != null && shouldRecomputePlan(currentPage))) { - resolutionOperation = null; - provisioningContext = getProvisioningContext(); - planSelections = currentPage.getCheckedIUElements(); - root = makeResolutionElementRoot(planSelections); + if (operation == null || (operation != null && shouldRecomputePlan(currentPage))) { recomputePlan(getContainer()); - planChanged(); - weResolved = true; } else { - planSelections = currentPage.getCheckedIUElements(); - root = makeResolutionElementRoot(planSelections); + // the selections have not changed from an IU point of view, but we want + // to reinitialize the resolution model elements to ensure they are up to + // date. + initializeResolutionModelElements(planSelections); } - return selectNextPage(page, getCurrentStatus(), weResolved); - } - return super.getNextPage(page); - } - - protected IWizardPage selectNextPage(IWizardPage currentPage, IStatus status, boolean hasResolved) { - // We have already established before calling this method that the - // current page is either the main page or the error page. - if (status.getSeverity() == IStatus.CANCEL) - return currentPage; - else if (status.getSeverity() == IStatus.ERROR) { - if (errorPage == null) - errorPage = getErrorReportingPage(); - if (currentPage == errorPage) { - updateErrorPageStatus(errorPage); - return null; - } - showingErrorPage(); - return errorPage; - } else { - if (resolutionPage == null) { - resolutionPage = createResolutionPage(); - addPage(resolutionPage); + IStatus status = operation.getResolutionResult(); + if (status == null || status.getSeverity() == IStatus.ERROR) { + return errorPage; + } else if (status.getSeverity() == IStatus.CANCEL) { + return page; + } else { + return resolutionPage; } - // need to clear any previous error status reported so that traversing - // back to the error page will not show the error - if (currentPage instanceof IResolutionErrorReportingPage) - updateErrorPageStatus((IResolutionErrorReportingPage) currentPage); - return resolutionPage; } - } - - /** - * The error page is being shown for the first time given the - * current plan. Update any information needed before showing - * the page. - */ - protected void showingErrorPage() { - // default is to do nothing + return super.getNextPage(page); } private boolean shouldRecomputePlan(ISelectableIUsPage page) { boolean previouslyWaiting = waitingForOtherJobs; boolean previouslyCanceled = getCurrentStatus().getSeverity() == IStatus.CANCEL; - waitingForOtherJobs = ProvisioningOperationRunner.hasScheduledOperationsFor(profileId); + waitingForOtherJobs = ui.hasScheduledOperations(); return waitingForOtherJobs || previouslyWaiting || previouslyCanceled || pageSelectionsHaveChanged(page) || provisioningContextChanged(); } private boolean pageSelectionsHaveChanged(ISelectableIUsPage page) { - HashSet selectedIUs = new HashSet(); + HashSet selectedIUs = new HashSet(); Object[] currentSelections = page.getCheckedIUElements(); selectedIUs.addAll(Arrays.asList(ElementUtils.elementsToIUs(currentSelections))); - HashSet lastIUSelections = new HashSet(); + HashSet lastIUSelections = new HashSet(); lastIUSelections.addAll(Arrays.asList(ElementUtils.elementsToIUs(planSelections))); return !(selectedIUs.equals(lastIUSelections)); } @@ -194,20 +146,13 @@ public abstract class ProvisioningOperationWizard extends Wizard { } protected void planChanged() { - if (resolutionOperation != null) { - IStatus status = resolutionOperation.getResolutionResult().getSummaryStatus(); - if (status.getSeverity() != IStatus.ERROR && status.getSeverity() != IStatus.CANCEL) { - if (resolutionPage != null) - resolutionPage.updateStatus(root, resolutionOperation); - else { - resolutionPage = createResolutionPage(); - addPage(resolutionPage); - } - } + errorPage.updateStatus(root, operation); + if (errorPage != resolutionPage) { + resolutionPage.updateStatus(root, operation); } } - protected abstract IUElementListRoot makeResolutionElementRoot(Object[] selectedElements); + protected abstract void initializeResolutionModelElements(Object[] selectedElements); protected ProvisioningContext getProvisioningContext() { return null; @@ -220,57 +165,46 @@ public abstract class ProvisioningOperationWizard extends Wizard { * @param runnableContext */ public void recomputePlan(IRunnableContext runnableContext) { - final Object[] elements = root.getChildren(root); - couldNotResolve = false; - try { - if (elements.length == 0) { - couldNotResolve(ProvUIMessages.ResolutionWizardPage_NoSelections); - } else + couldNotResolveStatus = Status.OK_STATUS; + provisioningContext = getProvisioningContext(); + initializeResolutionModelElements(mainPage.getCheckedIUElements()); + if (planSelections.length == 0) { + operation = null; + couldNotResolve(ProvUIMessages.ResolutionWizardPage_NoSelections); + } else { + operation = getProfileChangeOperation(planSelections); + try { runnableContext.run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) { - resolutionOperation = null; - MultiStatus status = PlanAnalyzer.getProfileChangeAlteredStatus(); - ProfileChangeRequest request = computeProfileChangeRequest(elements, status, monitor); - if (request != null) { - resolutionOperation = new PlannerResolutionOperation(ProvUIMessages.ProfileModificationWizardPage_ResolutionOperationLabel, profileId, request, provisioningContext, status, false); - try { - resolutionOperation.execute(monitor); - } catch (ProvisionException e) { - ProvUI.handleException(e, null, StatusManager.SHOW | StatusManager.LOG); - couldNotResolve(null); - } - } + operation.resolveModal(monitor); } }); - } catch (InterruptedException e) { - // Nothing to report if thread was interrupted - } catch (InvocationTargetException e) { - ProvUI.handleException(e.getCause(), null, StatusManager.SHOW | StatusManager.LOG); - couldNotResolve(null); + + } catch (InterruptedException e) { + // Nothing to report if thread was interrupted + } catch (InvocationTargetException e) { + ProvUI.handleException(e.getCause(), null, StatusManager.SHOW | StatusManager.LOG); + couldNotResolve(null); + } } - if (errorPage == null) - errorPage = getErrorReportingPage(); - updateErrorPageStatus(errorPage); + planChanged(); } - void updateErrorPageStatus(IResolutionErrorReportingPage page) { - page.updateStatus(originalRoot, resolutionOperation); - } + protected abstract ProfileChangeOperation getProfileChangeOperation(Object[] elements); void couldNotResolve(String message) { - resolutionOperation = null; - couldNotResolve = true; if (message != null) { - IStatus status = new MultiStatus(ProvUIActivator.PLUGIN_ID, IStatusCodes.UNEXPECTED_NOTHING_TO_DO, message, null); - StatusManager.getManager().handle(status, StatusManager.LOG); + couldNotResolveStatus = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, message, null); + } else { + couldNotResolveStatus = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningOperationWizard_UnexpectedFailureToResolve, null); } + StatusManager.getManager().handle(couldNotResolveStatus, StatusManager.LOG); } public IStatus getCurrentStatus() { - if (couldNotResolve || resolutionOperation == null) { - return PlanAnalyzer.getStatus(IStatusCodes.UNEXPECTED_NOTHING_TO_DO, null); - } - return resolutionOperation.getResolutionResult().getSummaryStatus(); + if (operation != null && operation.getResolutionResult() != null) + return operation.getResolutionResult(); + return couldNotResolveStatus; } public String getDialogSettingsSectionName() { @@ -285,6 +219,15 @@ public abstract class ProvisioningOperationWizard extends Wizard { } } - protected abstract ProfileChangeRequest computeProfileChangeRequest(Object[] checkedElements, MultiStatus additionalStatus, IProgressMonitor monitor); + protected Policy getPolicy() { + return ui.getPolicy(); + } + protected String getProfileId() { + return ui.getProfileId(); + } + + protected boolean shouldShowProvisioningPlanChildren() { + return ProvUI.getQueryContext(getPolicy()).getShowProvisioningPlanChildren(); + } } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProvisioningWizardDialog.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProvisioningWizardDialog.java new file mode 100644 index 000000000..4f650b656 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProvisioningWizardDialog.java @@ -0,0 +1,62 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.dialogs; + +import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; +import org.eclipse.jface.dialogs.IDialogSettings; +import org.eclipse.jface.wizard.WizardDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Shell; + +/** + * Subclass of WizardDialog that provides bounds saving behavior. + * @since 3.5 + * + */ +public class ProvisioningWizardDialog extends WizardDialog { + private ProvisioningOperationWizard wizard; + + public ProvisioningWizardDialog(Shell parent, ProvisioningOperationWizard wizard) { + super(parent, wizard); + this.wizard = wizard; + setShellStyle(getShellStyle() | SWT.RESIZE); + } + + protected IDialogSettings getDialogBoundsSettings() { + IDialogSettings settings = ProvUIActivator.getDefault().getDialogSettings(); + IDialogSettings section = settings.getSection(wizard.getDialogSettingsSectionName()); + if (section == null) { + section = settings.addNewSection(wizard.getDialogSettingsSectionName()); + } + return section; + } + + /** + * @see org.eclipse.jface.window.Window#close() + */ + public boolean close() { + if (getShell() != null && !getShell().isDisposed()) { + wizard.saveBoundsRelatedSettings(); + } + return super.close(); + } + + /** + * This method is provided only for automated testing. + * + * @noreference This method is not intended to be referenced by clients. + */ + public Button testGetButton(int id) { + return getButton(id); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProvisioningWizardPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProvisioningWizardPage.java index 085056b08..4418a01e8 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProvisioningWizardPage.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ProvisioningWizardPage.java @@ -10,6 +10,7 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.dialogs; +import org.eclipse.equinox.p2.ui.*; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.dnd.*; import org.eclipse.swt.widgets.Control; @@ -17,8 +18,13 @@ import org.eclipse.ui.PlatformUI; abstract class ProvisioningWizardPage extends WizardPage implements ICopyable { - protected ProvisioningWizardPage(String pageName) { + private ProvisioningUI ui; + private ProvisioningOperationWizard wizard; + + protected ProvisioningWizardPage(String pageName, ProvisioningUI ui, ProvisioningOperationWizard wizard) { super(pageName); + this.wizard = wizard; + this.ui = ui; } protected void activateCopy(Control control) { @@ -26,6 +32,10 @@ abstract class ProvisioningWizardPage extends WizardPage implements ICopyable { } + protected ProvisioningOperationWizard getProvisioningWizard() { + return wizard; + } + public void copyToClipboard(Control activeControl) { String text = getClipboardText(activeControl); if (text.length() == 0) @@ -44,4 +54,16 @@ abstract class ProvisioningWizardPage extends WizardPage implements ICopyable { public void saveBoundsRelatedSettings() { // Default is to do nothing } + + protected ProvisioningUI getProvisioningUI() { + return ui; + } + + protected Policy getPolicy() { + return ui.getPolicy(); + } + + String getProfileId() { + return ui.getProfileId(); + } } \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/RepositoryManipulatorDropTarget.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/RepositoryManipulatorDropTarget.java index cb258f8e8..a44ee11d4 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/RepositoryManipulatorDropTarget.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/RepositoryManipulatorDropTarget.java @@ -14,13 +14,9 @@ import java.net.URI; import java.net.URISyntaxException; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryLocationValidator; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTargetEvent; @@ -38,13 +34,15 @@ import org.eclipse.ui.statushandlers.StatusManager; * */ public class RepositoryManipulatorDropTarget extends URLDropAdapter { - RepositoryManipulator manipulator; + ProvisioningUI ui; + RepositoryTracker tracker; Control control; - public RepositoryManipulatorDropTarget(RepositoryManipulator manipulator, Control control) { + public RepositoryManipulatorDropTarget(ProvisioningUI ui, Control control) { super(true); // convert file drops to URL - Assert.isNotNull(manipulator); - this.manipulator = manipulator; + Assert.isNotNull(ui); + this.ui = ui; + this.tracker = ui.getRepositoryTracker(); this.control = control; } @@ -54,7 +52,7 @@ public class RepositoryManipulatorDropTarget extends URLDropAdapter { try { location[0] = URIUtil.fromString(urlText); } catch (URISyntaxException e) { - ProvUI.reportStatus(RepositoryLocationValidator.getInvalidLocationStatus(urlText), StatusManager.SHOW | StatusManager.LOG); + ProvUI.reportStatus(tracker.getInvalidLocationStatus(urlText), StatusManager.SHOW | StatusManager.LOG); return; } if (location[0] == null) @@ -63,13 +61,10 @@ public class RepositoryManipulatorDropTarget extends URLDropAdapter { Job job = new WorkbenchJob(ProvUIMessages.RepositoryManipulatorDropTarget_DragAndDropJobLabel) { public IStatus runInUIThread(IProgressMonitor monitor) { - IStatus status = manipulator.getRepositoryLocationValidator(control.getShell()).validateRepositoryLocation(location[0], false, monitor); + IStatus status = tracker.validateRepositoryLocation(ui.getSession(), location[0], false, monitor); if (status.isOK()) { - ProvisioningOperation addOperation = manipulator.getAddOperation(location[0]); - ProvisioningOperationRunner.schedule(addOperation, StatusManager.SHOW | StatusManager.LOG); + tracker.addRepository(location[0], null, ui.getSession()); event.detail = DND.DROP_LINK; - } else if (status.getCode() == RepositoryLocationValidator.ALTERNATE_ACTION_TAKEN) { - event.detail = DND.DROP_COPY; } else if (status.getSeverity() == IStatus.CANCEL) { event.detail = DND.DROP_NONE; } else { diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/RepositoryNameAndLocationDialog.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/RepositoryNameAndLocationDialog.java index ddb988360..702d88a51 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/RepositoryNameAndLocationDialog.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/RepositoryNameAndLocationDialog.java @@ -15,7 +15,9 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.SWT; @@ -37,13 +39,13 @@ public class RepositoryNameAndLocationDialog extends StatusDialog { Button okButton; Text url, nickname; - Policy policy; + ProvisioningUI ui; URI location; String name; - public RepositoryNameAndLocationDialog(Shell parentShell, Policy policy) { + public RepositoryNameAndLocationDialog(Shell parentShell, ProvisioningUI ui) { super(parentShell); - this.policy = policy; + this.ui = ui; setTitle(ProvUIMessages.RepositoryNameAndLocationDialog_Title); } @@ -71,25 +73,13 @@ public class RepositoryNameAndLocationDialog extends StatusDialog { } /** - * Return a location validator appropriate for this dialog. The - * default is to retrieve it from the repository manipulator. - * Subclasses may override. - * - * @return the validator - */ - protected RepositoryLocationValidator getRepositoryLocationValidator() { - return getRepositoryManipulator().getRepositoryLocationValidator(getShell()); - } - - /** - * Return a RepositoryManipulator appropriate for validating and adding the + * Return a RepositoryTracker appropriate for validating and adding the * repository. * - * The default manipulator is described by the policy. Subclasses may override. - * @return the repository manipulator + * @return the Repository Tracker */ - protected RepositoryManipulator getRepositoryManipulator() { - return policy.getRepositoryManipulator(); + protected RepositoryTracker getRepositoryTracker() { + return ui.getRepositoryTracker(); } protected void okPressed() { @@ -111,7 +101,7 @@ public class RepositoryNameAndLocationDialog extends StatusDialog { * @return the URL currently typed in by the user. */ protected URI getUserLocation() { - return RepositoryLocationValidator.locationFromString(url.getText().trim()); + return getRepositoryTracker().locationFromString(url.getText().trim()); } /** @@ -144,16 +134,16 @@ public class RepositoryNameAndLocationDialog extends StatusDialog { if (url == null || url.isDisposed()) return Status.OK_STATUS; final IStatus[] status = new IStatus[1]; - status[0] = RepositoryLocationValidator.getInvalidLocationStatus(url.getText().trim()); + status[0] = getRepositoryTracker().getInvalidLocationStatus(url.getText().trim()); final URI userLocation = getUserLocation(); if (url.getText().length() == 0) - status[0] = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, RepositoryLocationValidator.LOCAL_VALIDATION_ERROR, ProvUIMessages.RepositoryGroup_URLRequired, null); + status[0] = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvisioningSession.STATUS_INVALID_REPOSITORY_LOCATION, ProvUIMessages.RepositoryGroup_URLRequired, null); else if (userLocation == null) - status[0] = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, RepositoryLocationValidator.LOCAL_VALIDATION_ERROR, ProvUIMessages.AddRepositoryDialog_InvalidURL, null); + status[0] = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvisioningSession.STATUS_INVALID_REPOSITORY_LOCATION, ProvUIMessages.AddRepositoryDialog_InvalidURL, null); else { BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { public void run() { - status[0] = getRepositoryLocationValidator().validateRepositoryLocation(userLocation, contactRepositories, null); + status[0] = getRepositoryTracker().validateRepositoryLocation(ui.getSession(), userLocation, contactRepositories, null); } }); } @@ -219,4 +209,8 @@ public class RepositoryNameAndLocationDialog extends StatusDialog { url.setSelection(0, url.getText().length()); return url; } + + protected ProvisioningUI getProvisioningUI() { + return ui; + } } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/RepositorySelectionGroup.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/RepositorySelectionGroup.java new file mode 100644 index 000000000..25d2a612f --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/RepositorySelectionGroup.java @@ -0,0 +1,610 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Yury Chernikov - Bug 271447 [ui] Bad layout in 'Install available software' dialog + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.dialogs; + +import com.ibm.icu.text.Collator; +import java.lang.reflect.InvocationTargetException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.query.IUViewQueryContext; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.fieldassist.ControlDecoration; +import org.eclipse.jface.fieldassist.FieldDecorationRegistry; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.jface.wizard.IWizardContainer; +import org.eclipse.osgi.util.NLS; +import org.eclipse.swt.SWT; +import org.eclipse.swt.dnd.*; +import org.eclipse.swt.events.*; +import org.eclipse.swt.graphics.*; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.*; + +/** + * A RepositorySelectionGroup is a reusable UI component that displays + * available repositories and allows the user to select them. + * + * @since 3.5 + */ +public class RepositorySelectionGroup { + + private static final String SITE_NONE = ProvUIMessages.AvailableIUsPage_NoSites; + private static final String SITE_ALL = ProvUIMessages.AvailableIUsPage_AllSites; + private static final String SITE_LOCAL = ProvUIMessages.AvailableIUsPage_LocalSites; + private static final int INDEX_SITE_NONE = 0; + private static final int INDEX_SITE_ALL = 1; + private static final int DEC_MARGIN_WIDTH = 2; + private static final String LINKACTION = "linkAction"; //$NON-NLS-1$ + + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=245569 + private static final int COUNT_VISIBLE_ITEMS = 20; + IWizardContainer container; + ProvisioningUI ui; + IUViewQueryContext queryContext; + + ListenerList listeners = new ListenerList(); + + Combo repoCombo; + Link repoManipulatorLink; + ControlDecoration repoDec; + ComboAutoCompleteField repoAutoComplete; + ProvUIProvisioningListener comboRepoListener; + + Image info, warning, error; + URI[] comboRepos; // the URIs shown in the combo, kept in sync with combo items + HashMap disabledRepoProposals = new HashMap(); // proposal string -> disabled URI + + public RepositorySelectionGroup(ProvisioningUI ui, IWizardContainer container, Composite parent, IUViewQueryContext queryContext) { + this.container = container; + this.queryContext = queryContext; + this.ui = ui; + createControl(parent); + } + + public Control getDefaultFocusControl() { + return repoCombo; + } + + public void addRepositorySelectionListener(IRepositorySelectionListener listener) { + listeners.add(listener); + } + + protected void createControl(Composite parent) { + final RepositoryTracker tracker = ProvisioningUI.getDefaultUI().getRepositoryTracker(); + // Get the possible field error indicators + info = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_INFORMATION).getImage(); + warning = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_WARNING).getImage(); + error = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_ERROR).getImage(); + + // Combo that filters sites + Composite comboComposite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginTop = 0; + layout.marginBottom = IDialogConstants.VERTICAL_SPACING; + layout.numColumns = 3; + comboComposite.setLayout(layout); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); + comboComposite.setLayoutData(gd); + + Label label = new Label(comboComposite, SWT.NONE); + label.setText(ProvUIMessages.AvailableIUsPage_RepoFilterLabel); + + repoCombo = new Combo(comboComposite, SWT.DROP_DOWN); + repoCombo.addSelectionListener(new SelectionListener() { + + public void widgetDefaultSelected(SelectionEvent e) { + repoComboSelectionChanged(); + } + + public void widgetSelected(SelectionEvent e) { + repoComboSelectionChanged(); + } + + }); + // Auto complete - install before our own key listeners, so that auto complete gets first shot. + repoAutoComplete = new ComboAutoCompleteField(repoCombo); + repoCombo.setVisibleItemCount(COUNT_VISIBLE_ITEMS); + repoCombo.addKeyListener(new KeyAdapter() { + + public void keyPressed(KeyEvent e) { + if (e.keyCode == SWT.CR) + addRepository(false); + } + }); + + // We don't ever want this to be interpreted as a default + // button event + repoCombo.addTraverseListener(new TraverseListener() { + public void keyTraversed(TraverseEvent e) { + if (e.detail == SWT.TRAVERSE_RETURN) { + e.doit = false; + } + } + }); + + gd = new GridData(SWT.FILL, SWT.CENTER, true, false); + // breathing room for info dec + gd.horizontalIndent = DEC_MARGIN_WIDTH * 2; + repoCombo.setLayoutData(gd); + repoCombo.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent event) { + URI location = null; + IStatus status = null; + String text = repoCombo.getText().trim(); + int index = getComboIndex(text); + // only validate text that doesn't match existing text in combo + if (index < 0) { + location = tracker.locationFromString(repoCombo.getText()); + if (location == null) { + status = tracker.getInvalidLocationStatus(repoCombo.getText()); + } else { + status = tracker.validateRepositoryLocation(ui.getSession(), location, false, new NullProgressMonitor()); + } + } else { + // user typed or pasted an existing location. Select it. + repoComboSelectionChanged(); + } + setRepoComboDecoration(status); + } + }); + + repoDec = new ControlDecoration(repoCombo, SWT.LEFT | SWT.TOP); + repoDec.setMarginWidth(DEC_MARGIN_WIDTH); + + DropTarget target = new DropTarget(repoCombo, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK); + target.setTransfer(new Transfer[] {URLTransfer.getInstance(), FileTransfer.getInstance()}); + target.addDropListener(new URLDropAdapter(true) { + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.ui.dialogs.URLDropAdapter#handleURLString(java.lang.String, org.eclipse.swt.dnd.DropTargetEvent) + */ + protected void handleDrop(String urlText, DropTargetEvent event) { + repoCombo.setText(urlText); + event.detail = DND.DROP_LINK; + addRepository(false); + } + }); + + Button button = new Button(comboComposite, SWT.PUSH); + button.setText(ProvUIMessages.AvailableIUsPage_AddButton); + button.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + addRepository(true); + } + + public void widgetSelected(SelectionEvent e) { + addRepository(true); + } + }); + setButtonLayoutData(button); + + // Link to repository manipulator + repoManipulatorLink = createLink(comboComposite, new Action() { + public void runWithEvent(Event event) { + ui.manipulateRepositories(repoCombo.getShell()); + } + }, getLinkLabel()); + gd = new GridData(SWT.END, SWT.FILL, true, false); + gd.horizontalSpan = 3; + repoManipulatorLink.setLayoutData(gd); + + addComboProvisioningListeners(); + parent.addDisposeListener(new DisposeListener() { + public void widgetDisposed(DisposeEvent e) { + removeProvisioningListeners(); + } + + }); + } + + private String getLinkLabel() { + if (ui.getPolicy().getRepositoryPreferencePageId() != null) { + String pageName = ui.getPolicy().getRepositoryPreferencePageName(); + if (pageName == null) + pageName = ProvUIMessages.RepositorySelectionGroup_PrefPageName; + return NLS.bind(ProvUIMessages.RepositorySelectionGroup_PrefPageLink, pageName); + } + return ProvUIMessages.RepositorySelectionGroup_GenericSiteLinkTitle; + } + + private void setButtonLayoutData(Button button) { + GridData data = new GridData(SWT.FILL, SWT.CENTER, false, false); + GC gc = new GC(button); + gc.setFont(JFaceResources.getDialogFont()); + FontMetrics fm = gc.getFontMetrics(); + gc.dispose(); + int widthHint = Dialog.convertHorizontalDLUsToPixels(fm, IDialogConstants.BUTTON_WIDTH); + Point minSize = button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); + data.widthHint = Math.max(widthHint, minSize.x); + button.setLayoutData(data); + } + + public void setRepositorySelection(int scope, URI location) { + switch (scope) { + case AvailableIUGroup.AVAILABLE_ALL : + fillRepoCombo(SITE_ALL); + break; + case AvailableIUGroup.AVAILABLE_LOCAL : + fillRepoCombo(SITE_LOCAL); + break; + case AvailableIUGroup.AVAILABLE_SPECIFIED : + fillRepoCombo(getSiteString(location)); + break; + default : + fillRepoCombo(SITE_NONE); + } + setRepoComboDecoration(null); + } + + protected void setRepoComboDecoration(final IStatus status) { + if (status == null || status.isOK() || status.getSeverity() == IStatus.CANCEL) { + repoDec.setShowOnlyOnFocus(true); + repoDec.setDescriptionText(ProvUIMessages.AvailableIUsPage_RepoFilterInstructions); + repoDec.setImage(info); + // We may have been previously showing an error or warning + // hover. We will need to dismiss it, but if there is no text + // typed, don't do this, so that the user gets the info cue + if (repoCombo.getText().length() > 0) + repoDec.showHoverText(null); + return; + } + Image image; + if (status.getSeverity() == IStatus.WARNING) + image = warning; + else if (status.getSeverity() == IStatus.ERROR) + image = error; + else + image = info; + repoDec.setImage(image); + repoDec.setDescriptionText(status.getMessage()); + repoDec.setShowOnlyOnFocus(false); + // use a delay to show the validation method because the very next + // selection or keystroke might fix it + repoCombo.getDisplay().timerExec(500, new Runnable() { + public void run() { + if (repoDec != null && repoDec.getImage() != info) + repoDec.showHoverText(status.getMessage()); + } + }); + + } + + /* + * Fill the repo combo and use the specified string + * as the selection. If the selection is null, then the + * current selection should be preserved if applicable. + */ + void fillRepoCombo(final String selection) { + RepositoryTracker tracker = ui.getRepositoryTracker(); + URI[] sites = tracker.getKnownRepositories(ui.getSession()); + boolean hasLocalSites = getLocalSites().length > 0; + final String[] items; + if (hasLocalSites) { + // None, All, repo1, repo2....repo n, Local + comboRepos = new URI[sites.length + 3]; + items = new String[sites.length + 3]; + } else { + // None, All, repo1, repo2....repo n + comboRepos = new URI[sites.length + 2]; + items = new String[sites.length + 2]; + } + items[INDEX_SITE_NONE] = SITE_NONE; + items[INDEX_SITE_ALL] = SITE_ALL; + for (int i = 0; i < sites.length; i++) { + items[i + 2] = getSiteString(sites[i]); + comboRepos[i + 2] = sites[i]; + } + if (hasLocalSites) + items[items.length - 1] = SITE_LOCAL; + if (sites.length > 0) + sortRepoItems(items, comboRepos, hasLocalSites); + Runnable runnable = new Runnable() { + public void run() { + if (repoCombo == null || repoCombo.isDisposed()) + return; + String repoToSelect = selection; + if (repoToSelect == null) { + // If the combo is open and something is selected, use that index if we + // weren't given a string to select. + int selIndex = repoCombo.getSelectionIndex(); + if (selIndex >= 0) + repoToSelect = repoCombo.getItem(selIndex); + else + repoToSelect = repoCombo.getText(); + } + repoCombo.setItems(items); + repoAutoComplete.setProposalStrings(getComboProposals()); + boolean selected = false; + for (int i = 0; i < items.length; i++) + if (items[i].equals(repoToSelect)) { + selected = true; + if (repoCombo.getListVisible()) + repoCombo.select(i); + repoCombo.setText(repoToSelect); + break; + } + if (!selected) { + if (repoCombo.getListVisible()) + repoCombo.select(INDEX_SITE_NONE); + repoCombo.setText(SITE_NONE); + } + repoComboSelectionChanged(); + } + }; + if (Display.getCurrent() == null) + repoCombo.getDisplay().asyncExec(runnable); + else + runnable.run(); + } + + String getSiteString(URI uri) { + String nickname = ui.getSession().getMetadataRepositoryManager().getRepositoryProperty(uri, IRepository.PROP_NICKNAME); + if (nickname != null && nickname.length() > 0) + return NLS.bind(ProvUIMessages.AvailableIUsPage_NameWithLocation, nickname, URIUtil.toUnencodedString(uri)); + return URIUtil.toUnencodedString(uri); + } + + private Link createLink(Composite parent, IAction action, String text) { + Link link = new Link(parent, SWT.PUSH); + link.setText(text); + + link.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event event) { + IAction linkAction = getLinkAction(event.widget); + if (linkAction != null) { + linkAction.runWithEvent(event); + } + } + }); + link.setToolTipText(action.getToolTipText()); + link.setData(LINKACTION, action); + return link; + } + + IAction getLinkAction(Widget widget) { + Object data = widget.getData(LINKACTION); + if (data == null || !(data instanceof IAction)) { + return null; + } + return (IAction) data; + } + + private void sortRepoItems(String[] strings, URI[] locations, boolean hasLocalSites) { + int sortStart = 2; + int sortEnd = hasLocalSites ? strings.length - 2 : strings.length - 1; + if (sortStart >= sortEnd) + return; + final HashMap uriToString = new HashMap(); + for (int i = sortStart; i <= sortEnd; i++) { + uriToString.put(locations[i], strings[i]); + } + final Collator collator = Collator.getInstance(Locale.getDefault()); + Comparator stringComparator = new Comparator() { + public int compare(String a, String b) { + return collator.compare(a, b); + } + }; + Comparator uriComparator = new Comparator() { + public int compare(URI a, URI b) { + return collator.compare(uriToString.get(a), uriToString.get(b)); + } + }; + + Arrays.sort(strings, sortStart, sortEnd, stringComparator); + Arrays.sort(locations, sortStart, sortEnd, uriComparator); + } + + private URI[] getLocalSites() { + // use our current visibility flags plus the local filter + int flags = ui.getRepositoryTracker().getMetadataRepositoryFlags() | IRepositoryManager.REPOSITORIES_LOCAL; + return ui.getSession().getMetadataRepositoryManager().getKnownRepositories(flags); + } + + String[] getComboProposals() { + int flags = ui.getRepositoryTracker().getMetadataRepositoryFlags() | IRepositoryManager.REPOSITORIES_DISABLED; + String[] items = repoCombo.getItems(); + // Clear any previously remembered disabled repos + disabledRepoProposals = new HashMap(); + URI[] disabled = ui.getSession().getMetadataRepositoryManager().getKnownRepositories(flags); + String[] disabledItems = new String[disabled.length]; + for (int i = 0; i < disabledItems.length; i++) { + disabledItems[i] = getSiteString(disabled[i]); + disabledRepoProposals.put(disabledItems[i], disabled[i]); + } + String[] both = new String[items.length + disabledItems.length]; + System.arraycopy(items, 0, both, 0, items.length); + System.arraycopy(disabledItems, 0, both, items.length, disabledItems.length); + return both; + } + + int getComboIndex(String repoText) { + // Callers have typically done this already, but just in case + repoText = repoText.trim(); + // First look for exact match to the combo string. + // This includes the name, etc. + if (repoText.length() > 0) { + String[] items = repoCombo.getItems(); + for (int i = 0; i < items.length; i++) + if (repoText.equals(items[i])) { + return i; + } + } + // Look for URI match - the user may have pasted or dragged + // in a location that matches one we already know about, even + // if the text does not match completely. (slashes, no name, etc.) + try { + URI location = URIUtil.fromString(repoText); + for (int i = 0; i < comboRepos.length; i++) + if (URIUtil.sameURI(location, comboRepos[i])) { + return i; + } + } catch (URISyntaxException e) { + // never mind + } + return -1; + } + + void addComboProvisioningListeners() { + // We need to monitor repository events so that we can adjust the repo combo. + comboRepoListener = new ProvUIProvisioningListener(ProvUIProvisioningListener.PROV_EVENT_METADATA_REPOSITORY) { + protected void repositoryAdded(RepositoryEvent e) { + fillRepoCombo(getSiteString(e.getRepositoryLocation())); + } + + protected void repositoryRemoved(RepositoryEvent e) { + fillRepoCombo(null); + } + + protected void refreshAll() { + fillRepoCombo(null); + } + }; + ProvUI.addProvisioningListener(comboRepoListener); + } + + void removeProvisioningListeners() { + if (comboRepoListener != null) { + ProvUI.removeProvisioningListener(comboRepoListener); + comboRepoListener = null; + } + + } + + /* + * Add a repository using the text in the combo or launch a dialog if the text + * represents an already known repo. For any add operation spawned by this + * method, we do not want to notify the UI with a special listener. This is to + * prevent a multiple update flash because we intend to reset the available IU + * filter as soon as the new repo is added. + */ + void addRepository(boolean alwaysPrompt) { + final RepositoryTracker manipulator = ui.getRepositoryTracker(); + final String selectedRepo = repoCombo.getText().trim(); + int selectionIndex = getComboIndex(selectedRepo); + final boolean isNewText = selectionIndex < 0; + // If we are adding something already in the combo, just + // select that item. + if (!alwaysPrompt && !isNewText && selectionIndex != repoCombo.getSelectionIndex()) { + repoComboSelectionChanged(); + } else if (alwaysPrompt) { + AddRepositoryDialog dialog = new AddRepositoryDialog(repoCombo.getShell(), ui) { + + protected String getInitialLocationText() { + if (isNewText) + return selectedRepo; + return super.getInitialLocationText(); + } + + }; + dialog.setTitle(ProvUIMessages.AddRepositoryDialog_Title); + dialog.open(); + URI location = dialog.getAddedLocation(); + if (location != null) + fillRepoCombo(getSiteString(location)); + } else if (isNewText) { + try { + container.run(false, false, new IRunnableWithProgress() { + public void run(IProgressMonitor monitor) { + URI location; + IStatus status; + // This might be a disabled repo. If so, no need to validate further. + if (disabledRepoProposals.containsKey(selectedRepo)) { + location = disabledRepoProposals.get(selectedRepo); + status = Status.OK_STATUS; + } else { + location = manipulator.locationFromString(selectedRepo); + if (location == null) + status = manipulator.getInvalidLocationStatus(selectedRepo); + else { + status = manipulator.validateRepositoryLocation(ui.getSession(), location, false, monitor); + } + } + if (status.isOK() && location != null) { + manipulator.addRepository(location, null, ui.getSession()); + } + setRepoComboDecoration(status); + } + }); + } catch (InvocationTargetException e) { + // ignore + } catch (InterruptedException e) { + // ignore + } + } + } + + public ProvisioningContext getProvisioningContext() { + int siteSel = getComboIndex(repoCombo.getText().trim()); + if (siteSel < 0 || siteSel == INDEX_SITE_ALL || siteSel == INDEX_SITE_NONE) + return new ProvisioningContext(); + URI[] locals = getLocalSites(); + // If there are local sites, the last item in the combo is "Local Sites Only" + // Use all local sites in this case + // We have to set metadata repositories and artifact repositories in the + // provisioning context because the artifact repositories are used for + // sizing. + if (locals.length > 0 && siteSel == repoCombo.getItemCount() - 1) { + ProvisioningContext context = new ProvisioningContext(locals); + context.setArtifactRepositories(locals); + return context; + } + // A single site is selected. + ProvisioningContext context = new ProvisioningContext(new URI[] {comboRepos[siteSel]}); + context.setArtifactRepositories(new URI[] {comboRepos[siteSel]}); + return context; + } + + void repoComboSelectionChanged() { + int repoChoice = -1; + URI repoLocation = null; + + int selection = -1; + if (repoCombo.getListVisible()) { + selection = repoCombo.getSelectionIndex(); + } else { + selection = getComboIndex(repoCombo.getText().trim()); + } + int localIndex = getLocalSites().length == 0 ? repoCombo.getItemCount() : repoCombo.getItemCount() - 1; + if (comboRepos == null || selection < 0) { + selection = INDEX_SITE_NONE; + } + + if (selection == INDEX_SITE_NONE) { + repoChoice = AvailableIUGroup.AVAILABLE_NONE; + } else if (selection == INDEX_SITE_ALL) { + repoChoice = AvailableIUGroup.AVAILABLE_ALL; + } else if (selection >= localIndex) { + repoChoice = AvailableIUGroup.AVAILABLE_LOCAL; + } else { + repoChoice = AvailableIUGroup.AVAILABLE_SPECIFIED; + repoLocation = comboRepos[selection]; + } + + Object[] selectionListeners = listeners.getListeners(); + for (int i = 0; i < selectionListeners.length; i++) { + ((IRepositorySelectionListener) selectionListeners[i]).repositorySelectionChanged(repoChoice, repoLocation); + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ResolutionResultsWizardPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ResolutionResultsWizardPage.java index 7283048dc..5ee5043e3 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ResolutionResultsWizardPage.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ResolutionResultsWizardPage.java @@ -11,20 +11,15 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.dialogs; -import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.p2.ui.model.ElementUtils; -import org.eclipse.equinox.internal.p2.ui.model.QueriedElement; -import org.eclipse.equinox.internal.p2.ui.viewers.IUDetailsLabelProvider; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProfileModificationOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.*; +import org.eclipse.equinox.internal.p2.ui.model.*; +import org.eclipse.equinox.internal.p2.ui.viewers.*; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.operations.ProvisioningJob; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.viewers.*; import org.eclipse.swt.SWT; @@ -45,8 +40,7 @@ public abstract class ResolutionResultsWizardPage extends ResolutionStatusPage { private static final String DIALOG_SETTINGS_SECTION = "ResolutionResultsPage"; //$NON-NLS-1$ protected IUElementListRoot input; - PlannerResolutionOperation resolvedOperation; - protected Policy policy; + ProfileChangeOperation resolvedOperation; TreeViewer treeViewer; ProvElementContentProvider contentProvider; IUDetailsLabelProvider labelProvider; @@ -54,15 +48,18 @@ public abstract class ResolutionResultsWizardPage extends ResolutionStatusPage { private IUDetailsGroup iuDetailsGroup; SashForm sashForm; - protected ResolutionResultsWizardPage(Policy policy, IUElementListRoot input, String profileID, PlannerResolutionOperation resolvedOperation) { - super("ResolutionPage", profileID); //$NON-NLS-1$ - this.policy = policy; - Assert.isNotNull(resolvedOperation); - this.resolvedOperation = resolvedOperation; + protected ResolutionResultsWizardPage(ProvisioningUI ui, ProvisioningOperationWizard wizard, IUElementListRoot input, ProfileChangeOperation operation) { + super("ResolutionPage", ui, wizard); //$NON-NLS-1$ + // We can exist as an empty page, but if there is an operation, we need to know that it's resolved. + if (operation != null && !operation.hasResolved()) { + operation.resolveModal(null); + } + this.resolvedOperation = operation; if (input == null) this.input = new IUElementListRoot(); else this.input = input; + updateStatus(input, resolvedOperation); } /* @@ -117,7 +114,7 @@ public abstract class ResolutionResultsWizardPage extends ResolutionStatusPage { labelProvider = new IUDetailsLabelProvider(null, getColumnConfig(), getShell()); treeViewer.setLabelProvider(labelProvider); - setDrilldownElements(input, resolvedOperation.getProvisioningPlan()); + setDrilldownElements(input, resolvedOperation); treeViewer.setInput(input); // Optional area to show the size @@ -137,9 +134,8 @@ public abstract class ResolutionResultsWizardPage extends ResolutionStatusPage { } public boolean performFinish() { - if (resolvedOperation.getResolutionResult().getSummaryStatus().getSeverity() != IStatus.ERROR) { - ProfileModificationOperation op = createProfileModificationOperation(resolvedOperation); - ProvisioningOperationRunner.schedule(op, StatusManager.SHOW | StatusManager.LOG); + if (resolvedOperation.getResolutionResult().getSeverity() != IStatus.ERROR) { + getProvisioningUI().schedule(resolvedOperation.getProvisioningJob(null), StatusManager.SHOW | StatusManager.LOG); return true; } return false; @@ -149,8 +145,10 @@ public abstract class ResolutionResultsWizardPage extends ResolutionStatusPage { return treeViewer; } - public ProvisioningPlan getCurrentPlan() { - return resolvedOperation.getProvisioningPlan(); + public IProvisioningPlan getCurrentPlan() { + if (resolvedOperation != null) + return resolvedOperation.getProvisioningPlan(); + return null; } protected Object[] getSelectedElements() { @@ -164,33 +162,38 @@ public abstract class ResolutionResultsWizardPage extends ResolutionStatusPage { return units[0]; } - protected String getProfileId() { - return profileId; - } - protected IInstallableUnit[] getIUs() { return ElementUtils.elementsToIUs(input.getChildren(input)); } - void setDrilldownElements(IUElementListRoot root, ProvisioningPlan plan) { - if (plan == null) + void setDrilldownElements(IUElementListRoot root, ProfileChangeOperation operation) { + if (operation == null || operation.getProvisioningPlan() == null) return; Object[] elements = root.getChildren(root); for (int i = 0; i < elements.length; i++) { if (elements[i] instanceof QueriedElement) { - ((QueriedElement) elements[i]).setQueryable(getQueryable(plan)); + ((QueriedElement) elements[i]).setQueryable(getQueryable(operation.getProvisioningPlan())); } } } - private ProfileModificationOperation createProfileModificationOperation(PlannerResolutionOperation op) { - ProfileModificationOperation pmo = new ProfileModificationOperation(getOperationLabel(), profileId, op.getProvisioningPlan(), op.getProvisioningContext()); - pmo.setTaskName(getOperationTaskName()); - return pmo; - } - protected abstract String getOperationLabel(); + /** + * Returns the restart policy for this operation. + * + * @return an integer constant describing whether the running profile + * needs to be restarted. + * + * @see ProvisioningJob#RESTART_NONE + * @see ProvisioningJob#RESTART_ONLY + * @see ProvisioningJob#RESTART_OR_APPLY + * + */ + protected int getRestartPolicy() { + return ProvisioningJob.RESTART_OR_APPLY; + } + /** * Returns the task name for this operation, or null to display * a generic task name. @@ -203,7 +206,7 @@ public abstract class ResolutionResultsWizardPage extends ResolutionStatusPage { return new TreeViewer(parent, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION); } - protected abstract IQueryable getQueryable(ProvisioningPlan plan); + protected abstract IQueryable getQueryable(IProvisioningPlan plan); protected String getClipboardText(Control control) { return CopyUtils.getIndentedClipboardText(getSelectedElements(), labelProvider); @@ -217,9 +220,9 @@ public abstract class ResolutionResultsWizardPage extends ResolutionStatusPage { return treeViewer != null; } - protected void updateCaches(IUElementListRoot newRoot, PlannerResolutionOperation op) { + protected void updateCaches(IUElementListRoot newRoot, ProfileChangeOperation op) { resolvedOperation = op; - setDrilldownElements(newRoot, resolvedOperation.getProvisioningPlan()); + setDrilldownElements(newRoot, resolvedOperation); if (treeViewer != null) { if (input != newRoot) treeViewer.setInput(newRoot); diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ResolutionStatusPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ResolutionStatusPage.java index 1fd3b1e07..442759296 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ResolutionStatusPage.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ResolutionStatusPage.java @@ -11,16 +11,13 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.dialogs; -import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.IUPropertyUtils; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.IUColumnConfig; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot; +import org.eclipse.equinox.internal.p2.ui.viewers.IUColumnConfig; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.swt.custom.SashForm; @@ -42,17 +39,15 @@ public abstract class ResolutionStatusPage extends ProvisioningWizardPage { private static final String VERSION_COLUMN_WIDTH = "VersionColumnWidth"; //$NON-NLS-1$ private static final String ID_COLUMN_WIDTH = "IDColumnWidth"; //$NON-NLS-1$ private IUColumnConfig nameColumn, versionColumn, idColumn; - protected String profileId; /** * @param pageName */ - protected ResolutionStatusPage(String pageName, String profileId) { - super(pageName); - this.profileId = profileId; + protected ResolutionStatusPage(String pageName, ProvisioningUI ui, ProvisioningOperationWizard wizard) { + super(pageName, ui, wizard); } - protected abstract void updateCaches(IUElementListRoot root, PlannerResolutionOperation resolvedOperation); + protected abstract void updateCaches(IUElementListRoot root, ProfileChangeOperation resolvedOperation); protected abstract boolean isCreated(); @@ -64,17 +59,14 @@ public abstract class ResolutionStatusPage extends ProvisioningWizardPage { * Update the status area of the wizard to report the results of the operation. * * @param newRoot the root that describes the root IUs involved in creating the plan - * @param op the PlannerResolutionOperation that describes the plan that was created. - * Should not be null, but subclasses can be more forgiving. + * @param op the ProfileChangeOperation that describes the operation */ - public void updateStatus(IUElementListRoot newRoot, PlannerResolutionOperation op) { - Assert.isNotNull(op); + public void updateStatus(IUElementListRoot newRoot, ProfileChangeOperation op) { + IStatus currentStatus = getProvisioningWizard().getCurrentStatus(); updateCaches(newRoot, op); - IStatus currentStatus; int messageType = IMessageProvider.NONE; - boolean pageComplete = true; - currentStatus = op.getResolutionResult().getSummaryStatus(); + boolean pageComplete = op != null; if (currentStatus != null && !currentStatus.isOK()) { messageType = IMessageProvider.INFORMATION; int severity = currentStatus.getSeverity(); @@ -99,7 +91,7 @@ public abstract class ResolutionStatusPage extends ProvisioningWizardPage { protected String getIUDescription(IInstallableUnit iu) { // Get the iu description in the default locale - String description = IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION); + String description = iu.getProperty(IInstallableUnit.PROP_DESCRIPTION, null); if (description == null) description = ""; //$NON-NLS-1$ return description; @@ -115,14 +107,14 @@ public abstract class ResolutionStatusPage extends ProvisioningWizardPage { return ProvUIMessages.ResolutionWizardPage_WarningInfoStatus; } - void setDetailText(PlannerResolutionOperation resolvedOperation) { + void setDetailText(ProfileChangeOperation resolvedOperation) { String detail = null; IInstallableUnit selectedIU = getSelectedIU(); IUDetailsGroup detailsGroup = getDetailsGroup(); // We either haven't resolved, or we failed to resolve and reported some error // while doing so. Since the specific error was already reported, the description // text can be used for the selected IU. - if (resolvedOperation == null) { + if (resolvedOperation == null || !resolvedOperation.hasResolved()) { if (selectedIU != null) { detail = getIUDescription(selectedIU); detailsGroup.enablePropertyLink(true); @@ -136,15 +128,15 @@ public abstract class ResolutionStatusPage extends ProvisioningWizardPage { // An IU is selected and we have resolved. Look for information about the specific IU. if (selectedIU != null) { - detail = resolvedOperation.getResolutionResult().getDetailedReport(new IInstallableUnit[] {selectedIU}); + detail = resolvedOperation.getResolutionDetails(selectedIU); if (detail != null) { detailsGroup.enablePropertyLink(false); detailsGroup.setDetailText(detail); return; } // No specific error about this IU. Show the overall error if it is in error. - if (resolvedOperation.getResolutionResult().getSummaryStatus().getSeverity() == IStatus.ERROR) { - detail = resolvedOperation.getResolutionResult().getSummaryReport(); + if (resolvedOperation.getResolutionResult().getSeverity() == IStatus.ERROR) { + detail = resolvedOperation.getResolutionDetails(); detailsGroup.enablePropertyLink(false); detailsGroup.setDetailText(detail); return; @@ -157,7 +149,7 @@ public abstract class ResolutionStatusPage extends ProvisioningWizardPage { } //No IU is selected, give the overall report - detail = resolvedOperation.getResolutionResult().getSummaryReport(); + detail = resolvedOperation.getResolutionDetails(); detailsGroup.enablePropertyLink(false); if (detail == null) detail = ""; //$NON-NLS-1$ diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/SelectableIUsPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/SelectableIUsPage.java index 91ce7ab4b..7e83e395f 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/SelectableIUsPage.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/SelectableIUsPage.java @@ -11,19 +11,17 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.dialogs; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; import org.eclipse.equinox.internal.p2.ui.model.ElementUtils; -import org.eclipse.equinox.internal.p2.ui.viewers.IUDetailsLabelProvider; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.*; -import org.eclipse.jface.dialogs.*; +import org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot; +import org.eclipse.equinox.internal.p2.ui.viewers.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.ui.Policy; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.viewers.*; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.swt.SWT; @@ -46,7 +44,7 @@ public class SelectableIUsPage extends ResolutionStatusPage implements IResoluti IUElementListRoot root; Object[] initialSelections; - PlannerResolutionOperation resolvedOperation; + ProfileChangeOperation resolvedOperation; CheckboxTableViewer tableViewer; IUDetailsGroup iuDetailsGroup; ProvElementContentProvider contentProvider; @@ -55,12 +53,14 @@ public class SelectableIUsPage extends ResolutionStatusPage implements IResoluti protected Policy policy; SashForm sashForm; - public SelectableIUsPage(Policy policy, IUElementListRoot root, Object[] initialSelections, String profileId) { - super("IUSelectionPage", profileId); //$NON-NLS-1$ + public SelectableIUsPage(ProvisioningUI ui, ProvisioningOperationWizard wizard, IUElementListRoot root, Object[] initialSelections) { + super("IUSelectionPage", ui, wizard); //$NON-NLS-1$ this.root = root; - this.policy = policy; + if (root == null) + root = new IUElementListRoot(); this.initialSelections = initialSelections; - this.profileId = profileId; + if (initialSelections == null) + initialSelections = new IInstallableUnit[0]; } /* @@ -201,13 +201,14 @@ public class SelectableIUsPage extends ResolutionStatusPage implements IResoluti protected IInstallableUnit[] elementsToIUs(Object[] elements) { IInstallableUnit[] theIUs = new IInstallableUnit[elements.length]; for (int i = 0; i < elements.length; i++) { - theIUs[i] = (IInstallableUnit) ProvUI.getAdapter(elements[i], IInstallableUnit.class); + theIUs[i] = ProvUI.getAdapter(elements[i], IInstallableUnit.class); } return theIUs; } protected void setInitialCheckState() { - tableViewer.setCheckedElements(initialSelections); + if (initialSelections != null) + tableViewer.setCheckedElements(initialSelections); } /* @@ -252,31 +253,6 @@ public class SelectableIUsPage extends ResolutionStatusPage implements IResoluti return units[0]; } - /* - * Overridden to handle conditions where continuing with the operation should not be allowed. - * (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.ui.dialogs.ResolutionStatusPage#updateStatus(org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot, org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation) - */ - public void updateStatus(IUElementListRoot newRoot, PlannerResolutionOperation op) { - IStatus specialStatus = null; - if (ProvisioningOperationRunner.hasScheduledOperationsFor(profileId)) { - specialStatus = PlanAnalyzer.getStatus(IStatusCodes.OPERATION_ALREADY_IN_PROGRESS, null); - } else if (op == null) { - specialStatus = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, 0, ProvUIMessages.ProfileModificationWizardPage_UnexpectedError, null); - } - if (specialStatus == null) { - super.updateStatus(newRoot, op); - } else { - updateCaches(newRoot, op); - setPageComplete(false); - if (!isCreated()) - return; - getDetailsGroup().setDetailText(specialStatus.getMessage()); - setMessage(getMessageText(specialStatus), IMessageProvider.ERROR); - - } - } - protected IUDetailsGroup getDetailsGroup() { return iuDetailsGroup; } @@ -285,7 +261,7 @@ public class SelectableIUsPage extends ResolutionStatusPage implements IResoluti return tableViewer != null; } - protected void updateCaches(IUElementListRoot newRoot, PlannerResolutionOperation op) { + protected void updateCaches(IUElementListRoot newRoot, ProfileChangeOperation op) { resolvedOperation = op; if (root != newRoot && tableViewer != null) tableViewer.setInput(newRoot); diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/SizeComputingWizardPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/SizeComputingWizardPage.java index da87ce46f..a95451df7 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/SizeComputingWizardPage.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/SizeComputingWizardPage.java @@ -14,16 +14,15 @@ import java.text.NumberFormat; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.*; import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.model.IIUElement; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; -import org.eclipse.equinox.internal.provisional.p2.ui.ValidationDialogServiceUI; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; @@ -38,34 +37,30 @@ public abstract class SizeComputingWizardPage extends ResolutionResultsWizardPag protected Label sizeInfo; protected long size; Job sizingJob; - private ProvisioningPlan lastComputedPlan = null; + private IProvisioningPlan lastComputedPlan = null; - protected SizeComputingWizardPage(Policy policy, IUElementListRoot root, String profileID, PlannerResolutionOperation initialResolution) { - super(policy, root, profileID, initialResolution); + protected SizeComputingWizardPage(ProvisioningUI ui, ProvisioningOperationWizard wizard, IUElementListRoot root, ProfileChangeOperation initialResolution) { + super(ui, wizard, root, initialResolution); // Compute size immediately if a plan is available. This may or may not finish before // the widgetry is created. - if (initialResolution != null) - computeSizing(initialResolution.getProvisioningPlan(), profileID, initialResolution.getProvisioningContext()); + if (initialResolution != null && initialResolution.hasResolved()) + computeSizing(initialResolution.getProvisioningPlan(), initialResolution.getProvisioningContext()); else // Set the size to indicate there is no size yet. - size = IIUElement.SIZE_NOTAPPLICABLE; + size = ProvisioningSession.SIZE_NOTAPPLICABLE; } - protected void computeSizing(final ProvisioningPlan plan, final String id, final ProvisioningContext provisioningContext) { + protected void computeSizing(final IProvisioningPlan plan, final ProvisioningContext provisioningContext) { if (plan == lastComputedPlan) return; lastComputedPlan = plan; - size = IIUElement.SIZE_UNKNOWN; + size = ProvisioningSession.SIZE_UNKNOWN; updateSizingInfo(); if (sizingJob != null) sizingJob.cancel(); sizingJob = new Job(ProvUIMessages.SizeComputingWizardPage_SizeJobTitle) { protected IStatus run(IProgressMonitor monitor) { - try { - size = ProvisioningUtil.getSize(plan, id, provisioningContext, monitor); - } catch (ProvisionException e) { - return e.getStatus(); - } + size = getProvisioningUI().getSession().getSize(plan, provisioningContext, monitor); if (monitor.isCanceled()) return Status.CANCEL_STATUS; if (display != null) { @@ -81,13 +76,13 @@ public abstract class SizeComputingWizardPage extends ResolutionResultsWizardPag }; sizingJob.setUser(false); sizingJob.setSystem(true); - sizingJob.setProperty(ValidationDialogServiceUI.SUPPRESS_AUTHENTICATION_JOB_MARKER, Boolean.toString(true)); - sizingJob.schedule(); + sizingJob.setProperty(LoadMetadataRepositoryJob.SUPPRESS_AUTHENTICATION_JOB_MARKER, Boolean.toString(true)); sizingJob.addJobChangeListener(new JobChangeAdapter() { public void done(IJobChangeEvent event) { sizingJob = null; } }); + sizingJob.schedule(); } protected void createSizingInfo(Composite parent) { @@ -99,7 +94,7 @@ public abstract class SizeComputingWizardPage extends ResolutionResultsWizardPag protected void updateSizingInfo() { if (sizeInfo != null && !sizeInfo.isDisposed()) { - if (size == IIUElement.SIZE_NOTAPPLICABLE) + if (size == ProvisioningSession.SIZE_NOTAPPLICABLE) sizeInfo.setVisible(false); else { sizeInfo.setText(NLS.bind(ProvUIMessages.UpdateOrInstallWizardPage_Size, getFormattedSize())); @@ -109,7 +104,7 @@ public abstract class SizeComputingWizardPage extends ResolutionResultsWizardPag } protected String getFormattedSize() { - if (size == IIUElement.SIZE_UNKNOWN || size == IIUElement.SIZE_UNAVAILABLE) + if (size == ProvisioningSession.SIZE_UNKNOWN || size == ProvisioningSession.SIZE_UNAVAILABLE) return ProvUIMessages.IUDetailsLabelProvider_Unknown; if (size > 1000L) { long kb = size / 1000L; @@ -125,13 +120,13 @@ public abstract class SizeComputingWizardPage extends ResolutionResultsWizardPag } } - public void updateStatus(IUElementListRoot root, PlannerResolutionOperation op) { + public void updateStatus(IUElementListRoot root, ProfileChangeOperation op) { super.updateStatus(root, op); - if (op.getProvisioningPlan() != null) - computeSizing(op.getProvisioningPlan(), getProfileId(), op.getProvisioningContext()); + if (op != null && op.getProvisioningPlan() != null) + computeSizing(op.getProvisioningPlan(), op.getProvisioningContext()); } - protected IQueryable getQueryable(ProvisioningPlan plan) { + protected IQueryable getQueryable(IProvisioningPlan plan) { return plan.getAdditions(); } } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/StructuredIUGroup.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/StructuredIUGroup.java index 5564df78c..44ffabc05 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/StructuredIUGroup.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/StructuredIUGroup.java @@ -10,12 +10,14 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.dialogs; +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.internal.p2.ui.QueryProvider; import org.eclipse.equinox.internal.p2.ui.model.ElementUtils; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.QueryProvider; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.IUColumnConfig; +import org.eclipse.equinox.internal.p2.ui.viewers.IUColumnConfig; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.ui.Policy; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; @@ -36,21 +38,22 @@ public abstract class StructuredIUGroup { private FontMetrics fm; protected StructuredViewer viewer; private Composite composite; - private Policy policy; + private ProvisioningUI ui; private IUColumnConfig[] columnConfig; + private QueryProvider queryProvider; /** * Create a group that represents the available IU's. * - * @param policy The application policy to use in the group + * @param ui The application policy to use in the group * @param parent the parent composite for the group * to retrieve elements in the viewer. * @param font The font to use for calculating pixel sizes. This font is * not managed by the receiver. * @param columnConfig the columns to be shown */ - protected StructuredIUGroup(Policy policy, Composite parent, Font font, IUColumnConfig[] columnConfig) { - this.policy = policy; + protected StructuredIUGroup(ProvisioningUI ui, Composite parent, Font font, IUColumnConfig[] columnConfig) { + this.ui = ui; if (columnConfig == null) this.columnConfig = ProvUI.getIUColumnConfig(); else @@ -127,11 +130,21 @@ public abstract class StructuredIUGroup { } protected QueryProvider getQueryProvider() { - return policy.getQueryProvider(); + if (queryProvider == null) + queryProvider = new QueryProvider(ui); + return queryProvider; } protected Policy getPolicy() { - return policy; + return ui.getPolicy(); + } + + protected ProvisioningSession getSession() { + return ui.getSession(); + } + + protected ProvisioningUI getProvisioningUI() { + return ui; } protected Control getDefaultFocusControl() { diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UninstallWizard.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UninstallWizard.java new file mode 100644 index 000000000..e5cb26203 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UninstallWizard.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.dialogs; + +import org.eclipse.equinox.internal.p2.ui.model.InstalledIUElement; + +import java.util.ArrayList; +import org.eclipse.equinox.internal.p2.ui.ProvUIImages; +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.internal.p2.ui.model.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.operations.UninstallOperation; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.wizard.IWizardPage; + +/** + * @since 3.4 + */ +public class UninstallWizard extends ProvisioningOperationWizard { + + public UninstallWizard(ProvisioningUI ui, UninstallOperation operation, IInstallableUnit[] initialSelections, LoadMetadataRepositoryJob job) { + super(ui, operation, initialSelections, job); + setWindowTitle(ProvUIMessages.UninstallIUOperationLabel); + setDefaultPageImageDescriptor(ProvUIImages.getImageDescriptor(ProvUIImages.WIZARD_BANNER_UNINSTALL)); + } + + protected ISelectableIUsPage createMainPage(IUElementListRoot input, Object[] selections) { + mainPage = new SelectableIUsPage(ui, this, input, selections); + mainPage.setTitle(ProvUIMessages.UninstallIUOperationLabel); + mainPage.setDescription(ProvUIMessages.UninstallDialog_UninstallMessage); + ((SelectableIUsPage) mainPage).updateStatus(input, operation); + return mainPage; + } + + protected ResolutionResultsWizardPage createResolutionPage() { + return new UninstallWizardPage(ui, this, root, (UninstallOperation) operation); + } + + protected void initializeResolutionModelElements(Object[] selectedElements) { + root = new IUElementListRoot(); + ArrayList list = new ArrayList(selectedElements.length); + ArrayList selections = new ArrayList(selectedElements.length); + for (int i = 0; i < selectedElements.length; i++) { + IInstallableUnit iu = ElementUtils.getIU(selectedElements[i]); + if (iu != null) { + InstalledIUElement element = new InstalledIUElement(root, getProfileId(), iu); + list.add(element); + selections.add(element); + } + } + root.setChildren(list.toArray()); + planSelections = selections.toArray(); + } + + protected IResolutionErrorReportingPage createErrorReportingPage() { + return (SelectableIUsPage) mainPage; + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.wizard.Wizard#getStartingPage() + */ + public IWizardPage getStartingPage() { + if (getCurrentStatus().isOK()) { + ((SelectableIUsPage) mainPage).setPageComplete(true); + return resolutionPage; + } + return super.getStartingPage(); + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.dialogs.ProvisioningOperationWizard#getProfileChangeOperation(java.lang.Object[]) + */ + protected ProfileChangeOperation getProfileChangeOperation(Object[] elements) { + UninstallOperation op = new UninstallOperation(ui.getSession(), ElementUtils.elementsToIUs(elements)); + op.setProfileId(getProfileId()); + // op.setRootMarkerKey(getRootMarkerKey()); + op.setProvisioningContext(getProvisioningContext()); + return op; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UninstallWizardPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UninstallWizardPage.java index e43caae2c..376bbed82 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UninstallWizardPage.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UninstallWizardPage.java @@ -11,16 +11,17 @@ package org.eclipse.equinox.internal.p2.ui.dialogs; import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.UninstallOperation; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.ui.ProvisioningUI; public class UninstallWizardPage extends ResolutionResultsWizardPage { - public UninstallWizardPage(Policy policy, IUElementListRoot root, String profileId, PlannerResolutionOperation initialResolution) { - super(policy, root, profileId, initialResolution); + public UninstallWizardPage(ProvisioningUI ui, ProvisioningOperationWizard wizard, IUElementListRoot root, UninstallOperation initialResolution) { + super(ui, wizard, root, initialResolution); setTitle(ProvUIMessages.UninstallWizardPage_Title); setDescription(ProvUIMessages.UninstallWizardPage_Description); } @@ -33,7 +34,7 @@ public class UninstallWizardPage extends ResolutionResultsWizardPage { return ProvUIMessages.UninstallIUOperationTask; } - protected IQueryable getQueryable(ProvisioningPlan plan) { + protected IQueryable getQueryable(IProvisioningPlan plan) { return plan.getRemovals(); } } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UpdateWizard.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UpdateWizard.java new file mode 100644 index 000000000..46b375868 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UpdateWizard.java @@ -0,0 +1,146 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Genuitec, LLC - added license support + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.dialogs; + +import java.util.*; +import org.eclipse.equinox.internal.p2.ui.ProvUIImages; +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.internal.p2.ui.model.AvailableUpdateElement; +import org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.*; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.swt.widgets.Composite; + +/** + * @since 3.4 + */ +public class UpdateWizard extends WizardWithLicenses { + IInstallableUnit[] iusToReplace; + boolean skipSelectionsPage = false; + + public static IInstallableUnit[] getIUsToReplace(Object[] elements) { + Set iusToReplace = new HashSet(); + for (int i = 0; i < elements.length; i++) { + if (elements[i] instanceof AvailableUpdateElement) { + iusToReplace.add(((AvailableUpdateElement) elements[i]).getIUToBeUpdated()); + } + } + return iusToReplace.toArray(new IInstallableUnit[iusToReplace.size()]); + } + + public static IInstallableUnit[] getReplacementIUs(Object[] elements) { + Set replacements = new HashSet(); + for (int i = 0; i < elements.length; i++) { + if (elements[i] instanceof AvailableUpdateElement) { + replacements.add(((AvailableUpdateElement) elements[i]).getIU()); + } + } + return replacements.toArray(new IInstallableUnit[replacements.size()]); + } + + public static Update[] makeUpdatesFromElements(Object[] elements) { + Set updates = new HashSet(); + for (int i = 0; i < elements.length; i++) { + if (elements[i] instanceof AvailableUpdateElement) { + updates.add(((AvailableUpdateElement) elements[i]).getUpdate()); + } + } + return updates.toArray(new Update[updates.size()]); + } + + public UpdateWizard(ProvisioningUI ui, UpdateOperation operation, Object[] initialSelections, LoadMetadataRepositoryJob preloadJob) { + super(ui, operation, initialSelections, preloadJob); + setWindowTitle(ProvUIMessages.UpdateAction_UpdatesAvailableTitle); + setDefaultPageImageDescriptor(ProvUIImages.getImageDescriptor(ProvUIImages.WIZARD_BANNER_UPDATE)); + } + + protected ISelectableIUsPage createMainPage(IUElementListRoot input, Object[] selections) { + mainPage = new SelectableIUsPage(ui, this, input, selections); + mainPage.setTitle(ProvUIMessages.UpdateAction_UpdatesAvailableTitle); + mainPage.setDescription(ProvUIMessages.UpdateAction_UpdatesAvailableMessage); + ((SelectableIUsPage) mainPage).updateStatus(input, operation); + return mainPage; + } + + protected ResolutionResultsWizardPage createResolutionPage() { + return new UpdateWizardPage(ui, this, root, (UpdateOperation) operation); + } + + protected void initializeResolutionModelElements(Object[] selectedElements) { + root = new IUElementListRoot(); + ArrayList list = new ArrayList(selectedElements.length); + ArrayList selected = new ArrayList(selectedElements.length); + for (int i = 0; i < selectedElements.length; i++) { + if (selectedElements[i] instanceof AvailableUpdateElement) { + AvailableUpdateElement element = (AvailableUpdateElement) selectedElements[i]; + AvailableUpdateElement newElement = new AvailableUpdateElement(root, element.getIU(), element.getIUToBeUpdated(), getProfileId(), shouldShowProvisioningPlanChildren()); + list.add(newElement); + selected.add(newElement); + } else if (selectedElements[i] instanceof Update) { + Update update = (Update) selectedElements[i]; + AvailableUpdateElement newElement = new AvailableUpdateElement(root, update.replacement, update.toUpdate, getProfileId(), shouldShowProvisioningPlanChildren()); + list.add(newElement); + selected.add(newElement); + } + } + root.setChildren(list.toArray()); + planSelections = selected.toArray(); + } + + public void createPageControls(Composite pageContainer) { + super.createPageControls(pageContainer); + if (getRepositoryPreloadJob() != null) + // async exec since we are in the middle of opening + pageContainer.getDisplay().asyncExec(new Runnable() { + public void run() { + getRepositoryPreloadJob().reportAccumulatedStatus(); + } + }); + } + + protected IResolutionErrorReportingPage createErrorReportingPage() { + return (SelectableIUsPage) mainPage; + } + + public void setSkipSelectionsPage(boolean skipSelectionsPage) { + this.skipSelectionsPage = skipSelectionsPage; + } + + public IWizardPage getStartingPage() { + if (skipSelectionsPage) { + // TODO see https://bugs.eclipse.org/bugs/show_bug.cgi?id=276963 + IWizardPage page = getNextPage(mainPage); + if (page != null) + return page; + } + return mainPage; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.dialogs.ProvisioningOperationWizard#getProfileChangeOperation(java.lang.Object[]) + */ + protected ProfileChangeOperation getProfileChangeOperation(Object[] elements) { + if (operation == null) { + operation = new UpdateOperation(ui.getSession(), getIUsToReplace(elements)); + operation.setProfileId(getProfileId()); + // operation.setRootMarkerKey(getRootMarkerKey()); + operation.setProvisioningContext(getProvisioningContext()); + + } else { + ((UpdateOperation) operation).setSelectedUpdates(makeUpdatesFromElements(elements)); + } + return operation; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UpdateWizardPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UpdateWizardPage.java index eafb86b29..c8bf6dd31 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UpdateWizardPage.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/UpdateWizardPage.java @@ -10,17 +10,18 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.dialogs; +import org.eclipse.equinox.p2.metadata.IUpdateDescriptor; + import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IUpdateDescriptor; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.UpdateOperation; +import org.eclipse.equinox.p2.ui.ProvisioningUI; public class UpdateWizardPage extends SizeComputingWizardPage { - public UpdateWizardPage(Policy policy, IUElementListRoot root, String profileId, PlannerResolutionOperation initialResolution) { - super(policy, root, profileId, initialResolution); + public UpdateWizardPage(ProvisioningUI ui, ProvisioningOperationWizard wizard, IUElementListRoot root, UpdateOperation operation) { + super(ui, wizard, root, operation); setTitle(ProvUIMessages.UpdateWizardPage_Title); setDescription(ProvUIMessages.UpdateWizardPage_Description); } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/WizardWithLicenses.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/WizardWithLicenses.java index 221786295..a8b7e0646 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/WizardWithLicenses.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/WizardWithLicenses.java @@ -12,15 +12,10 @@ package org.eclipse.equinox.internal.p2.ui.dialogs; import org.eclipse.equinox.internal.p2.ui.model.ElementUtils; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.AcceptLicensesWizardPage; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.wizard.IWizardContainer; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.ui.*; import org.eclipse.jface.wizard.IWizardPage; -import org.eclipse.swt.widgets.Display; /** * Common superclass for wizards that need to show licenses. @@ -30,62 +25,52 @@ public abstract class WizardWithLicenses extends ProvisioningOperationWizard { AcceptLicensesWizardPage licensePage; - public WizardWithLicenses(Policy policy, String profileId, IUElementListRoot root, Object[] initialSelections, PlannerResolutionOperation initialResolution) { - super(policy, profileId, root, initialSelections, initialResolution); + /* + * (non-Javadoc) + * @see org.eclipse.jface.wizard.Wizard#addPages() + */ + public void addPages() { + super.addPages(); + licensePage = createLicensesPage(); + addPage(licensePage); } - protected AcceptLicensesWizardPage createLicensesPage(IInstallableUnit[] ius, ProvisioningPlan plan) { - return new AcceptLicensesWizardPage(policy, ius, plan); + public WizardWithLicenses(ProvisioningUI ui, ProfileChangeOperation operation, Object[] initialSelections, LoadMetadataRepositoryJob job) { + super(ui, operation, initialSelections, job); } - public void addPages() { - super.addPages(); + protected AcceptLicensesWizardPage createLicensesPage() { + IInstallableUnit[] ius = new IInstallableUnit[0]; + if (planSelections != null) + ius = ElementUtils.elementsToIUs(planSelections); + return new AcceptLicensesWizardPage(ui.getLicenseManager(), ius, operation); } + /* + * Overridden to determine whether the license page should be shown. + * (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.dialogs.ProvisioningOperationWizard#getNextPage(org.eclipse.jface.wizard.IWizardPage) + */ public IWizardPage getNextPage(IWizardPage page) { - if (page == resolutionPage) { - if (licensePage == null) { - licensePage = createLicensesPage(ElementUtils.elementsToIUs(mainPage.getCheckedIUElements()), resolutionPage.getCurrentPlan()); - addPage(licensePage); - Display.getDefault().asyncExec(new Runnable() { - public void run() { - IWizardContainer container = getContainer(); - if (container != null) - container.updateButtons(); - } - }); - - } - if (licensePage.hasLicensesToAccept()) { - return licensePage; - } - return null; - } else if (page == licensePage) { - // we are done. We explicitly code this because it's possible - // that the license page is added to the wizard before a dynamic page that - // gets added afterward, but should appear before. + // If the license page is supposed to be the next page, + // ensure there are actually licenses that need acceptance. + IWizardPage proposedPage = super.getNextPage(page); + if (proposedPage != licensePage) + return proposedPage; + if (!licensePage.hasLicensesToAccept()) return null; - } - return super.getNextPage(page); + return licensePage; } protected void planChanged() { super.planChanged(); - if (resolutionOperation == null) - return; - if (licensePage == null) { - licensePage = createLicensesPage(ElementUtils.elementsToIUs(mainPage.getCheckedIUElements()), resolutionOperation.getProvisioningPlan()); - addPage(licensePage); - } else - licensePage.update(ElementUtils.elementsToIUs(mainPage.getCheckedIUElements()), resolutionOperation.getProvisioningPlan()); - // Status of license page could change status of wizard next button - // If no current page has been set yet (ie, we are still being created) - // then the updateButtons() method will NPE. This check is needed in - // order to run the automated test cases. - if (getContainer().getCurrentPage() != null) - getContainer().updateButtons(); + licensePage.update(ElementUtils.elementsToIUs(planSelections), operation); } + /* + * (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.dialogs.ProvisioningOperationWizard#performFinish() + */ public boolean performFinish() { licensePage.performFinish(); return super.performFinish(); diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/messages.properties b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/messages.properties index a34c3c84d..6ee7196b3 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/messages.properties +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/messages.properties @@ -9,32 +9,17 @@ # IBM Corporation - initial API and implementation ############################################################################### -ProfileChangeRequestBuildingRequest=Processing request -ProfileElement_InvalidProfile=Invalid profile ID {0} ProfileModificationAction_InvalidSelections=Problem determining user request. Profile id: {0}, Selection count: {1} -ProfileModificationAction_NoChangeRequestProvided=Could not interpret the request -ProfileModificationAction_NoExplanationProvided=Unexpected error while processing the request. -ProfileModificationAction_ResolutionOperationLabel=Calculating Requirements ProfileModificationWizardPage_DetailsLabel=Details -ProfileModificationWizardPage_ResolutionOperationLabel=Calculating Requirements -ProfileModificationWizardPage_UnexpectedError=An unexpected error occurred. This wizard is no longer valid with the current selections. ProfileSnapshots_Label=Installation History -ProvisioningUtil_InstallPlanConfigurationError=A problem was encountered while preparing the system for the installation -ProvisioningUtil_NoRepositoryManager=No repository manager was found -ProvisioningUtil_LoadRepositoryFailure=Unable to load the repository {0} -ProvisioningUtil_NoProfileRegistryFound=No profile registry was found -ProvisioningUtil_NoPlannerFound=No provisioning planner was found -ProvisioningUtil_NoDirectorFound=No provisioning director was found -ProvisioningUtil_NoEngineFound=No provisioning engine was found ProvisioningOperationRunner_CannotApplyChanges=The changes could not be applied while the application is running. You must restart the application for the changes to take effect. -ProvisioningOperationRunner_ErrorExecutingOperation=Unexpected error while trying to run {0} +ProvisioningOperationWizard_UnexpectedFailureToResolve=Unexpected error InstalledSoftwarePage_NoProfile=This installation has not been configured for showing the installed software. See the error log for details. InstallIUOperationLabel=Install InstallIUOperationTask=Software installation in progress... InstallIUCommandLabel=&Install... InstallIUCommandTooltip=Install the selected items -InstallIUProgress=Installing... UninstallDialog_UninstallMessage=Check the items that you wish to uninstall. UninstallIUOperationLabel=Uninstall UninstallIUOperationTask=Uninstall is in progress... @@ -46,7 +31,6 @@ UninstallWizardPage_Title=Uninstall Details ServiceUI_LoginDetails=Please provide login details for {0} ServiceUI_LoginRequired=Login required ServiceUI_unsigned_message=Warning: You are installing software that contains unsigned content. The authenticity or validity of this software cannot be established. Do you want to continue with the installation? -ServiceUI_unsigned_title=Installing unsigned content ServiceUI_warning_title=Security Warning UpdateIUOperationLabel=Update UpdateIUOperationTask=Software update is in progress... @@ -56,7 +40,6 @@ UpdateIUProgress=Updating... RefreshAction_Label=Refres&h RefreshAction_Tooltip=Refresh RemoveColocatedRepositoryAction_Label=&Remove Sites... -RemoveColocatedRepositoryAction_OperationLabel=Remove RemoveColocatedRepositoryAction_Tooltip=Remove selected sites from the available software site list RevertIUCommandLabel=&Revert... RevertIUCommandTooltip=Revert to a previously installed configuration @@ -114,7 +97,9 @@ RepositoryManipulationPage_Title=Available Software Sites RepositoryManipulatorDropTarget_DragAndDropJobLabel=Drag and Drop Operation RepositoryManipulatorDropTarget_DragSourceNotValid={0} was not accepted as a valid software site location. Check the details. RepositoryNameAndLocationDialog_Title=Edit Site -ResolutionReport_SummaryStatus=Operation details +RepositorySelectionGroup_GenericSiteLinkTitle=Work with the list of software sites +RepositorySelectionGroup_PrefPageLink=Find more software by working with the '{0}' preferences. +RepositorySelectionGroup_PrefPageName=Software Sites ResolutionWizardPage_Canceled=The operation was cancelled. ResolutionWizardPage_ErrorStatus=The operation cannot be completed. See the details. ResolutionWizardPage_NoSelections=There were no installable units selected when the plan was computed. @@ -132,16 +117,13 @@ AcceptLicensesWizardPage_ReviewLicensesDescription=Licenses must be reviewed and AcceptLicensesWizardPage_SingleLicenseTextLabel=License &text (for {0}): AcceptLicensesWizardPage_Title=Review Licenses AddRepositoryDialog_Title=Add Repository -AddRepositoryDialog_DuplicateURL=Duplicate location AddRepositoryDialog_InvalidURL=The provided location is not valid AddRepositoryDialog_LocationLabel=&Location: AddRepositoryDialog_NameLabel=&Name: UpdateAction_UpdatesAvailableMessage=Check the updates that you wish to install. UpdateAction_UpdatesAvailableTitle=Available Updates -UpdateOperation_NothingToUpdate=There is nothing to update. UpdateOrInstallWizardPage_Size=Size: {0} -URLValidator_UnrecognizedURL=The location {0} is not a valid software site location. UpdateManagerCompatibility_ExportSitesTitle=Export Sites UpdateManagerCompatibility_ImportSitesTitle=Import Sites UpdateManagerCompatibility_InvalidSiteFileMessage=The selected file does not contain any updates sites. Please select another file. @@ -155,9 +137,6 @@ UserValidationDialog_PasswordLabel=&Password: UserValidationDialog_SavePasswordButton=&Save password UserValidationDialog_UsernameLabel=&Username: ColocatedRepositoryManipulator_AddSiteOperationLabel=Add Site -ColocatedRepositoryManipulator_GotoPrefs=Go to the Available Software Sites preferences -ColocatedRepositoryManipulator_ManageSites=&Manage Sites... -ColocatedRepositoryManipulator_RemoveSiteOperationLabel=Remove Site RevertProfilePage_ConfirmDeleteMultipleConfigs=Deleting the selected configurations from the installation history will free up the disk space used to store the configurations. However, you will no longer be able to revert your installation to these configurations. Are you sure you want to delete the configurations? RevertProfilePage_ConfirmDeleteSingleConfig=Deleting the configuration from the installation history will free up the disk space used to store it. However, you will no longer be able to revert your installation to this configuration. Are you sure you want to delete it? RevertProfilePage_Delete=&Delete @@ -173,52 +152,36 @@ InstallWizardPage_NoCheckboxDescription=Review the items to be installed. InstallWizardPage_Title=Install Details PreselectedIUInstallWizard_Title=Install PreselectedIUInstallWizard_Description=Check the items that you wish to install. - -PlanAnalyzer_IgnoringInstall="{0}" is not applicable to the current configuration and will not be installed. -PlanAnalyzer_LockedImpliedUpdate0={0} will be ignored because it is already installed, and updates are not permitted. -PlanAnalyzer_PartialInstall="{0}" is already present because other installed software requires it. It will be added to the installed software list. -PlanAnalyzer_PartialUninstall= "{0}" cannot be fully uninstalled because other installed software requires it. The parts that are not required will be uninstalled. -PlanAnalyzer_SideEffectInstall="{0}" will also be installed in order to complete this operation. -PlanAnalyzer_SideEffectUninstall="{0}" must be uninstalled in order to complete this operation. -PlannerResolutionOperation_UnexpectedError=Unexpected error. Unable to calculate requirements and dependencies. -PlanStatusHelper_IgnoringImpliedDowngrade="{0}" will be ignored because a newer version is already installed. -PlanStatusHelper_ImpliedUpdate="{0}" is already installed, so an update will be performed instead. -PlanStatusHelper_Items=Items -PlanStatusHelper_NothingToDo=Cannot complete the request. See the error log for details. -PlanStatusHelper_AlreadyInstalled="{0}" will be ignored because it is already installed. -PlanStatusHelper_AnotherOperationInProgress=Cannot continue the operation. There is another install operation in progress. -PlanStatusHelper_Launch=Launch... -PlanStatusHelper_RequestAltered=Your original request has been modified. -PlanStatusHelper_RequiresUpdateManager=Cannot continue the operation. One or more items requires support from the old Update Manager. -PlanStatusHelper_UnexpectedError=Unexpected error code {0} encountered for {1}. -PlanStatusHelper_UpdateManagerPromptTitle=Unsupported Install PlatformUpdateTitle = Software Updates PlatformRestartMessage = You will need to restart {0} for the changes to take effect. \ Would you like to restart now? +Policy_RequiresUpdateManagerMessage=A feature that you have selected uses install procedures that are not compatible with the current installation support. This feature can only be installed by the older Update Manager. \ +\ +Do you want to launch the older Update Manager? +Policy_RequiresUpdateManagerTitle=Unsupported Install ApplicationInRestartDialog = the application ProvUI_ErrorDuringApplyConfig=Error while attempting to apply changes. You must restart the application for changes to take effect. ProvUI_InformationTitle=Information ProvUI_InstallDialogError=Unable to open the Installation Information. ProvUI_NameColumnTitle=Name ProvUI_IdColumnTitle=Id -ProvUI_LoadErrorTitle=Error Contacting Site -ProvUI_PromptForSiteEdit=No software site found at {0}. Do you wish to edit the location? ProvUI_VersionColumnTitle=Version ProvUI_WarningTitle=Warning -ProvUIActivator_ExceptionDuringProfileChange=Exception while handling profile change event. -ProvUILicenseManager_ParsingError=Error parsing the accepted license registry ProvUIMessages_NotAccepted_EnterFor_0=Login details were not accepted. Please provide login details for {0} ProvUIMessages_SavedNotAccepted_EnterFor_0=Saved login details were not accepted. Please provide login details for {0} -OptionalPlatformRestartMessage = It is strongly recommended you restart {0} for the changes to take effect. \ -For some add-ons, it may be possible to apply the changes you have made without restarting. \ -Would you like to restart now? -ApplyProfileChangesDialog_ApplyChanges=Apply Changes -AvailableIUElement_ProfileNotFound=Could not find profile to use for size computation. +OptionalPlatformRestartMessage = You will need to restart {0} for the installation changes to take effect. \ +\ +You may try to apply the changes without restarting, but this may cause errors. +ApplyProfileChangesDialog_Restart=&Restart Now +ApplyProfileChangesDialog_NotYet=&Not Now +ApplyProfileChangesDialog_ApplyChanges=&Apply Changes Now AvailableIUGroup_LoadingRepository=Loading {0} AvailableIUGroup_NoSitesConfiguredDescription=This product was not configured with any software sites. Contact your systems administrator. AvailableIUGroup_NoSitesConfiguredExplanation=There are no software sites available. ColocatedRepositoryManipulator_NoContentExplanation=You may select a site in the combo box at the top. You may also type or paste a site name into the combo box and press Enter. You may also drag a site URL into the combo box or software list. +ColocatedRepositoryTracker_PromptForSiteLocationEdit=No software site found at {0}. Do you wish to edit the location? +ColocatedRepositoryTracker_SiteNotFoundTitle=Error Contacting Site AvailableIUGroup_NoSitesExplanation=There is no site selected. AvailableIUsPage_AddButton=&Add... AvailableIUsPage_AllSites=--All Available Sites-- @@ -239,26 +202,27 @@ AvailableIUsPage_ShowLatestVersions=Show only the &latest versions of available AvailableIUsPage_Title=Available Software AvailableIUWrapper_AllAreInstalled=All items are installed IUViewQueryContext_AllAreInstalledDescription=You can uncheck the 'Hide items that are already installed' check box to see all items. -DefaultQueryProvider_ErrorRetrievingProfile=Error retrieving profile {0} DeferredFetchFilteredTree_RetrievingList=Retrieving List ElementUtils_UpdateJobTitle=Updating Repository Information Label_Profiles=All Software Profiles Label_Repositories=Known Repositories +LaunchUpdateManagerButton=Launch... +LoadMetadataRepositoryJob_ContactSitesProgress=Contacting Software Sites +LoadMetadataRepositoryJob_SitesMissingError=Some sites could not be found. See the error log for more detail. MetadataRepositoryElement_NotFound=This repository is currently not available. MetadataRepositoryElement_RepositoryLoadError=Error loading repository {0} IUViewQueryContext_NoCategorizedItemsDescription=You can uncheck the 'Group items by category' check box to see items without categories. QueriedElementWrapper_NoCategorizedItemsExplanation=There are no categorized items QueriedElementWrapper_NoItemsExplanation=There are no items available QueriedElementWrapper_SiteNotFound=Could not find {0} -ColocatedRepositoryManipulator_SiteNotFoundDescription=The site's location may be entered incorrectly, or the site might be offline. You can correct the location in the 'Available Software Sites' preferences by removing the site and adding it with the proper location. If the site name appears to be correct, you can test the connection in the 'Available Software Sites' preferences. The site may be unreachable, or you may have a problem with your network connection. QueryableMetadataRepositoryManager_LoadRepositoryProgress=Contacting {0} QueryableMetadataRepositoryManager_MultipleRepositoriesNotFound=Some sites could not be found. See the error log for more detail. QueryableProfileRegistry_QueryProfileProgress=Getting profiles +QueryableRepositoryManager_LoadFailure=Could not load {0} QueryableUpdates_UpdateListProgress=Assembling list of updates SelectableIUsPage_Select_All=Select &All SelectableIUsPage_Deselect_All=&Deselect All SizeComputingWizardPage_SizeJobTitle=Computing size -SizingPhaseSet_PhaseSetName=Compute sizes RevertDialog_ConfigContentsLabel=Con&figuration contents: RevertDialog_ConfigsLabel=&Previous configurations: @@ -267,10 +231,6 @@ RevertDialog_RevertOperationLabel=Revert configuration RevertDialog_Title=Revert Software Configuration RollbackProfileElement_CurrentInstallation=Current Installation -RollbackProfileElement_InvalidSnapshot=The configuration snapshot is no longer valid. TrustCertificateDialog_Details=Details TrustCertificateDialog_Title=Do you trust these certificates? -PlanStatusHelper_PromptForUpdateManagerUI=A feature that you have selected uses install procedures that are not compatible with the current installation support. This feature can only be installed by the older Update Manager. \ -\ -Do you want to launch the older Update Manager? diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ArtifactElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ArtifactElement.java index dfbca544d..9ba9f4a7b 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ArtifactElement.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ArtifactElement.java @@ -10,8 +10,8 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.model; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; /** * Element wrapper class for an artifact key and its repository @@ -46,6 +46,7 @@ public class ArtifactElement extends ProvElement { return repo.getArtifactDescriptors(key); } + @SuppressWarnings("rawtypes") public Object getAdapter(Class adapter) { if (adapter == IArtifactRepository.class) return getArtifactRepository(); diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ArtifactRepositories.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ArtifactRepositories.java new file mode 100644 index 000000000..4b12392b8 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ArtifactRepositories.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.model; + +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.p2.ui.ProvisioningUI; + +/** + * Element class that represents the root of an artifact + * repository viewer. Its children are the artifact repositories + * obtained using the query installed in the content provider. + * + * @since 3.4 + * + */ +public class ArtifactRepositories extends RootElement { + + public ArtifactRepositories(ProvisioningUI ui, QueryableArtifactRepositoryManager queryable) { + super(ui); + this.queryable = queryable; + } + + protected int getDefaultQueryType() { + return QueryProvider.ARTIFACT_REPOS; + } + + /* + * (non-Javadoc) + * @see org.eclipse.ui.model.IWorkbenchAdapter#getLabel(java.lang.Object) + */ + public String getLabel(Object o) { + return ProvUIMessages.Label_Repositories; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ArtifactRepositoryElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ArtifactRepositoryElement.java index 03d709fd9..d137ed847 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ArtifactRepositoryElement.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ArtifactRepositoryElement.java @@ -12,18 +12,14 @@ package org.eclipse.equinox.internal.p2.ui.model; import java.net.URI; import org.eclipse.core.runtime.*; -import org.eclipse.core.runtime.jobs.ISchedulingRule; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IRepositoryElement; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.osgi.util.NLS; -import org.eclipse.ui.progress.IDeferredWorkbenchAdapter; -import org.eclipse.ui.progress.IElementCollector; /** * Element wrapper class for a artifact repository that gets its @@ -31,11 +27,12 @@ import org.eclipse.ui.progress.IElementCollector; * * @since 3.4 */ -public class ArtifactRepositoryElement extends ProvElement implements IDeferredWorkbenchAdapter, IRepositoryElement { +public class ArtifactRepositoryElement extends RemoteQueriedElement implements IRepositoryElement { URI location; IArtifactRepository repo; boolean isEnabled; + ProvisioningUI ui; public ArtifactRepositoryElement(Object parent, URI location) { this(parent, location, true); @@ -45,8 +42,10 @@ public class ArtifactRepositoryElement extends ProvElement implements IDeferredW super(parent); this.location = location; this.isEnabled = isEnabled; + ui = ProvUIActivator.getDefault().getProvisioningUI(); } + @SuppressWarnings("rawtypes") public Object getAdapter(Class adapter) { if (adapter == IArtifactRepository.class) return getRepository(null); @@ -59,18 +58,6 @@ public class ArtifactRepositoryElement extends ProvElement implements IDeferredW return ProvUIImages.IMG_ARTIFACT_REPOSITORY; } - protected Object[] fetchChildren(Object o, IProgressMonitor monitor) { - IArtifactRepository repository = (IArtifactRepository) getRepository(monitor); - if (repository == null) - return new ArtifactElement[0]; - IArtifactKey[] keys = repository.getArtifactKeys(); - ArtifactElement[] elements = new ArtifactElement[keys.length]; - for (int i = 0; i < keys.length; i++) { - elements[i] = new ArtifactElement(this, keys[i], repo); - } - return elements; - } - public String getLabel(Object o) { String name = getName(); if (name != null && name.length() > 0) { @@ -79,10 +66,10 @@ public class ArtifactRepositoryElement extends ProvElement implements IDeferredW return URIUtil.toUnencodedString(getLocation()); } - public IRepository getRepository(IProgressMonitor monitor) { + public IArtifactRepository getRepository(IProgressMonitor monitor) { if (repo == null) try { - repo = ProvisioningUtil.loadArtifactRepository(location, monitor); + repo = ui.getSession().getArtifactRepositoryManager().loadRepository(location, monitor); } catch (ProvisionException e) { handleException(e, NLS.bind(ProvUIMessages.MetadataRepositoryElement_RepositoryLoadError, location)); } catch (OperationCanceledException e) { @@ -91,22 +78,6 @@ public class ArtifactRepositoryElement extends ProvElement implements IDeferredW return repo; } - public ISchedulingRule getRule(Object object) { - return null; - } - - public boolean isContainer() { - return true; - } - - public void fetchDeferredChildren(Object o, IElementCollector collector, IProgressMonitor monitor) { - collector.add(fetchChildren(o, monitor), monitor); - } - - public Object[] getChildren(Object o) { - return fetchChildren(o, null); - } - /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.ui.model.RepositoryElement#getURL() */ @@ -119,16 +90,12 @@ public class ArtifactRepositoryElement extends ProvElement implements IDeferredW * @see org.eclipse.equinox.internal.provisional.p2.ui.model.RepositoryElement#getName() */ public String getName() { - try { - String name = ProvisioningUtil.getArtifactRepositoryProperty(location, IRepository.PROP_NICKNAME); - if (name == null) - name = ProvisioningUtil.getArtifactRepositoryProperty(location, IRepository.PROP_NAME); - if (name == null) - name = ""; //$NON-NLS-1$ - return name; - } catch (ProvisionException e) { - return ""; //$NON-NLS-1$ - } + String name = ui.getSession().getArtifactRepositoryManager().getRepositoryProperty(location, IRepository.PROP_NICKNAME); + if (name == null) + name = ui.getSession().getArtifactRepositoryManager().getRepositoryProperty(location, IRepository.PROP_NAME); + if (name == null) + name = ""; //$NON-NLS-1$ + return name; } /* @@ -136,14 +103,10 @@ public class ArtifactRepositoryElement extends ProvElement implements IDeferredW * @see org.eclipse.equinox.internal.provisional.p2.ui.model.RepositoryElement#getDescription() */ public String getDescription() { - try { - String description = ProvisioningUtil.getArtifactRepositoryProperty(location, IRepository.PROP_DESCRIPTION); - if (description == null) - return ""; //$NON-NLS-1$ - return description; - } catch (ProvisionException e) { + String description = ui.getSession().getArtifactRepositoryManager().getRepositoryProperty(location, IRepository.PROP_DESCRIPTION); + if (description == null) return ""; //$NON-NLS-1$ - } + return description; } /* (non-Javadoc) @@ -159,4 +122,22 @@ public class ArtifactRepositoryElement extends ProvElement implements IDeferredW public void setEnabled(boolean enabled) { isEnabled = enabled; } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.model.QueriedElement#getDefaultQueryType() + */ + protected int getDefaultQueryType() { + return QueryProvider.AVAILABLE_ARTIFACTS; + } + + /* + * overridden to lazily fetch repository + * (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueriedElement#getQueryable() + */ + public IQueryable getQueryable() { + if (queryable == null) + queryable = getRepository(new NullProgressMonitor()); + return queryable; + } } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/AvailableIUElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/AvailableIUElement.java index 878057512..f1d826c7f 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/AvailableIUElement.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/AvailableIUElement.java @@ -11,21 +11,17 @@ package org.eclipse.equinox.internal.p2.ui.model; import java.net.URI; +import java.util.Collection; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubMonitor; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.internal.p2.ui.ProvUIImages; +import org.eclipse.equinox.internal.p2.ui.QueryProvider; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.QueryProvider; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.repository.IRepository; /** * Element wrapper class for IU's that are available for installation. @@ -37,7 +33,7 @@ import org.eclipse.equinox.internal.provisional.p2.ui.policy.QueryProvider; public class AvailableIUElement extends QueriedElement implements IIUElement { IInstallableUnit iu; - boolean shouldShowChildren = Policy.getDefault().getQueryContext().getShowAvailableChildren(); + boolean shouldShowChildren; boolean isInstalled = false; boolean isUpdate = false; @@ -47,7 +43,7 @@ public class AvailableIUElement extends QueriedElement implements IIUElement { // probably refer to some preference or policy to decide what to do. // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=221087 private static boolean shouldShowSize = false; - long size = IIUElement.SIZE_UNKNOWN; + long size = ProvisioningSession.SIZE_UNKNOWN; String profileID; public AvailableIUElement(Object parent, IInstallableUnit iu, String profileID, boolean showChildren) { @@ -74,6 +70,7 @@ public class AvailableIUElement extends QueriedElement implements IIUElement { return iu.getId(); } + @SuppressWarnings("rawtypes") public Object getAdapter(Class adapter) { if (adapter == IInstallableUnit.class) return iu; @@ -87,24 +84,19 @@ public class AvailableIUElement extends QueriedElement implements IIUElement { public void computeSize(IProgressMonitor monitor) { if (profileID == null) return; - try { - SubMonitor mon = SubMonitor.convert(monitor, 100); - ProvisioningPlan plan = getSizingPlan(mon.newChild(50)); - size = ProvisioningUtil.getSize(plan, profileID, getProvisioningContext(), mon.newChild(50)); - } catch (ProvisionException e) { - handleException(e, ProvUIMessages.AvailableIUElement_ProfileNotFound); - size = IIUElement.SIZE_UNAVAILABLE; - } + SubMonitor mon = SubMonitor.convert(monitor, 100); + IProvisioningPlan plan = getSizingPlan(mon.newChild(50)); + size = getProvisioningUI().getSession().getSize(plan, getProvisioningContext(), mon.newChild(50)); } - protected IProfile getProfile() throws ProvisionException { - return ProvisioningUtil.getProfile(profileID); + protected IProfile getProfile() { + return getProvisioningUI().getSession().getProfileRegistry().getProfile(profileID); } - protected ProvisioningPlan getSizingPlan(IProgressMonitor monitor) throws ProvisionException { + protected IProvisioningPlan getSizingPlan(IProgressMonitor monitor) { ProfileChangeRequest request = ProfileChangeRequest.createByProfileId(profileID); request.addInstallableUnits(new IInstallableUnit[] {getIU()}); - return ProvisioningUtil.getProvisioningPlan(request, getProvisioningContext(), monitor); + return getProvisioningUI().getSession().getPlanner().getProvisioningPlan(request, getProvisioningContext(), monitor); } public IInstallableUnit getIU() { @@ -129,7 +121,7 @@ public class AvailableIUElement extends QueriedElement implements IIUElement { /* (non-Javadoc) * @see org.eclipse.equinox.internal.p2.ui.model.IUElement#getRequirements() */ - public IRequiredCapability[] getRequirements() { + public Collection getRequirements() { return iu.getRequiredCapabilities(); } @@ -181,8 +173,8 @@ public class AvailableIUElement extends QueriedElement implements IIUElement { } private ProvisioningContext getProvisioningContext() { - if (hasQueryable() && getQueryable() instanceof IRepository) - return new ProvisioningContext(new URI[] {((IRepository) getQueryable()).getLocation()}); + if (hasQueryable() && getQueryable() instanceof IRepository) + return new ProvisioningContext(new URI[] {((IRepository) getQueryable()).getLocation()}); return new ProvisioningContext(); } } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/AvailableUpdateElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/AvailableUpdateElement.java index d6c946e30..439625b9a 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/AvailableUpdateElement.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/AvailableUpdateElement.java @@ -11,12 +11,12 @@ package org.eclipse.equinox.internal.p2.ui.model; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; +import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.Update; /** * Element wrapper class for IU's that are available for installation. @@ -39,12 +39,12 @@ public class AvailableUpdateElement extends AvailableIUElement { return iuToBeUpdated; } - protected ProvisioningPlan getSizingPlan(IProgressMonitor monitor) throws ProvisionException { + protected IProvisioningPlan getSizingPlan(IProgressMonitor monitor) { ProfileChangeRequest request = ProfileChangeRequest.createByProfileId(profileID); if (iuToBeUpdated.getId().equals(getIU().getId())) - request.removeInstallableUnits(new IInstallableUnit[] {iuToBeUpdated}); - request.addInstallableUnits(new IInstallableUnit[] {getIU()}); - return ProvisioningUtil.getProvisioningPlan(request, new ProvisioningContext(), monitor); + request.removeInstallableUnit(iuToBeUpdated); + request.addInstallableUnits(getIU()); + return ProvUIActivator.getDefault().getSession().getPlanner().getProvisioningPlan(request, new ProvisioningContext(), monitor); } public boolean equals(Object obj) { @@ -69,4 +69,8 @@ public class AvailableUpdateElement extends AvailableIUElement { result = prime * result + ((iuToBeUpdated == null) ? 0 : iuToBeUpdated.hashCode()); return result; } + + public Update getUpdate() { + return new Update(iuToBeUpdated, getIU()); + } } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/CategoryElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/CategoryElement.java index d94d8219b..639af85c4 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/CategoryElement.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/CategoryElement.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.model; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; -import org.eclipse.equinox.internal.provisional.p2.ui.IUPropertyUtils; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.QueryProvider; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; +import org.eclipse.equinox.internal.p2.ui.ProvUIImages; +import org.eclipse.equinox.internal.p2.ui.QueryProvider; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; +import org.eclipse.equinox.p2.operations.ProvisioningSession; /** * Element wrapper class for IU's that represent categories of @@ -26,8 +28,8 @@ import org.eclipse.equinox.internal.provisional.p2.ui.policy.QueryProvider; */ public class CategoryElement extends RemoteQueriedElement implements IIUElement { - private ArrayList ius = new ArrayList(1); - private IRequiredCapability[] requirements; + private ArrayList ius = new ArrayList(1); + private Collection requirements; public CategoryElement(Object parent, IInstallableUnit iu) { super(parent); @@ -50,6 +52,7 @@ public class CategoryElement extends RemoteQueriedElement implements IIUElement return null; } + @SuppressWarnings("rawtypes") public Object getAdapter(Class adapter) { if (adapter == IInstallableUnit.class) return getIU(); @@ -63,11 +66,11 @@ public class CategoryElement extends RemoteQueriedElement implements IIUElement public IInstallableUnit getIU() { if (ius == null || ius.isEmpty()) return null; - return (IInstallableUnit) ius.get(0); + return ius.get(0); } public long getSize() { - return SIZE_UNKNOWN; + return ProvisioningSession.SIZE_UNKNOWN; } public boolean shouldShowSize() { @@ -94,27 +97,25 @@ public class CategoryElement extends RemoteQueriedElement implements IIUElement } private String getMergeKey(IInstallableUnit iu) { - String mergeKey = IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_NAME); + String mergeKey = iu.getProperty(IInstallableUnit.PROP_NAME, null); if (mergeKey == null || mergeKey.length() == 0) { mergeKey = iu.getId(); } return mergeKey; } - public IRequiredCapability[] getRequirements() { + public Collection getRequirements() { if (ius == null || ius.isEmpty()) - return new IRequiredCapability[0]; + return CollectionUtils.emptyList(); if (requirements == null) { if (ius.size() == 1) requirements = getIU().getRequiredCapabilities(); else { - ArrayList capabilities = new ArrayList(); - Iterator iter = ius.iterator(); - while (iter.hasNext()) { - IInstallableUnit iu = (IInstallableUnit) iter.next(); - capabilities.addAll(Arrays.asList(iu.getRequiredCapabilities())); + ArrayList capabilities = new ArrayList(); + for (IInstallableUnit iu : ius) { + capabilities.addAll(iu.getRequiredCapabilities()); } - requirements = (IRequiredCapability[]) capabilities.toArray(new IRequiredCapability[capabilities.size()]); + requirements = capabilities; } } return requirements; diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ElementUtils.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ElementUtils.java index 809645601..b75a0d8ee 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ElementUtils.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ElementUtils.java @@ -15,14 +15,13 @@ import java.net.URI; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.swt.widgets.Shell; /** @@ -36,60 +35,61 @@ public class ElementUtils { public static void updateRepositoryUsingElements(final MetadataRepositoryElement[] elements, final Shell shell) { Job job = new Job(ProvUIMessages.ElementUtils_UpdateJobTitle) { public IStatus run(IProgressMonitor monitor) { - ProvUI.startBatchOperation(); + final ProvisioningUI ui = ProvUIActivator.getDefault().getProvisioningUI(); + ui.signalRepositoryOperationStart(); + IMetadataRepositoryManager metaManager = ui.getSession().getMetadataRepositoryManager(); + IArtifactRepositoryManager artManager = ui.getSession().getArtifactRepositoryManager(); try { - int visibilityFlags = Policy.getDefault().getQueryContext().getMetadataRepositoryFlags(); - URI[] currentlyEnabled = ProvisioningUtil.getMetadataRepositories(visibilityFlags); - URI[] currentlyDisabled = ProvisioningUtil.getMetadataRepositories(IRepositoryManager.REPOSITORIES_DISABLED | visibilityFlags); + int visibilityFlags = ui.getRepositoryTracker().getMetadataRepositoryFlags(); + URI[] currentlyEnabled = metaManager.getKnownRepositories(visibilityFlags); + URI[] currentlyDisabled = metaManager.getKnownRepositories(IRepositoryManager.REPOSITORIES_DISABLED | visibilityFlags); for (int i = 0; i < elements.length; i++) { URI location = elements[i].getLocation(); if (elements[i].isEnabled()) { if (containsURI(currentlyDisabled, location)) // It should be enabled and is not currently - ProvisioningUtil.setColocatedRepositoryEnablement(location, true); + setColocatedRepositoryEnablement(ui, location, true); else if (!containsURI(currentlyEnabled, location)) { // It is not known as enabled or disabled. Add it. - ProvisioningUtil.addMetadataRepository(location, false); - ProvisioningUtil.addArtifactRepository(location, false); + metaManager.addRepository(location); + artManager.addRepository(location); } } else { if (containsURI(currentlyEnabled, location)) // It should be disabled, and is currently enabled - ProvisioningUtil.setColocatedRepositoryEnablement(location, false); + setColocatedRepositoryEnablement(ui, location, false); else if (!containsURI(currentlyDisabled, location)) { // It is not known as enabled or disabled. Add it and then disable it. - ProvisioningUtil.addMetadataRepository(location, false); - ProvisioningUtil.addArtifactRepository(location, false); - ProvisioningUtil.setColocatedRepositoryEnablement(location, false); + metaManager.addRepository(location); + artManager.addRepository(location); + setColocatedRepositoryEnablement(ui, location, false); } } String name = elements[i].getName(); if (name != null && name.length() > 0) { - ProvisioningUtil.setMetadataRepositoryProperty(location, IRepository.PROP_NICKNAME, name); - ProvisioningUtil.setArtifactRepositoryProperty(location, IRepository.PROP_NICKNAME, name); + metaManager.setRepositoryProperty(location, IRepository.PROP_NICKNAME, name); + artManager.setRepositoryProperty(location, IRepository.PROP_NICKNAME, name); } } // Are there any elements that need to be deleted? Go over the original state // and remove any elements that weren't in the elements we were given - Set nowKnown = new HashSet(); + Set nowKnown = new HashSet(); for (int i = 0; i < elements.length; i++) nowKnown.add(URIUtil.toUnencodedString(elements[i].getLocation())); for (int i = 0; i < currentlyEnabled.length; i++) { if (!nowKnown.contains(URIUtil.toUnencodedString(currentlyEnabled[i]))) { - ProvisioningUtil.removeMetadataRepository(currentlyEnabled[i]); - ProvisioningUtil.removeArtifactRepository(currentlyEnabled[i]); + metaManager.removeRepository(currentlyEnabled[i]); + artManager.removeRepository(currentlyEnabled[i]); } } for (int i = 0; i < currentlyDisabled.length; i++) { if (!nowKnown.contains(URIUtil.toUnencodedString(currentlyDisabled[i]))) { - ProvisioningUtil.removeMetadataRepository(currentlyDisabled[i]); - ProvisioningUtil.removeArtifactRepository(currentlyDisabled[i]); + metaManager.removeRepository(currentlyDisabled[i]); + artManager.removeRepository(currentlyDisabled[i]); } } - } catch (ProvisionException e) { - return e.getStatus(); } finally { - ProvUI.endBatchOperation(true); + ui.signalRepositoryOperationComplete(null, true); } return Status.OK_STATUS; } @@ -97,22 +97,27 @@ public class ElementUtils { job.schedule(); } + private static void setColocatedRepositoryEnablement(ProvisioningUI ui, URI location, boolean enable) { + ProvUIActivator.getDefault().getSession().getArtifactRepositoryManager().setEnabled(location, enable); + ProvUIActivator.getDefault().getSession().getMetadataRepositoryManager().setEnabled(location, enable); + } + public static IInstallableUnit getIU(Object element) { if (element instanceof IInstallableUnit) return (IInstallableUnit) element; if (element instanceof IIUElement) return ((IIUElement) element).getIU(); - return (IInstallableUnit) ProvUI.getAdapter(element, IInstallableUnit.class); + return ProvUI.getAdapter(element, IInstallableUnit.class); } public static IInstallableUnit[] elementsToIUs(Object[] elements) { - ArrayList theIUs = new ArrayList(elements.length); + ArrayList theIUs = new ArrayList(elements.length); for (int i = 0; i < elements.length; i++) { - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(elements[i], IInstallableUnit.class); + IInstallableUnit iu = ProvUI.getAdapter(elements[i], IInstallableUnit.class); if (iu != null) theIUs.add(iu); } - return (IInstallableUnit[]) theIUs.toArray(new IInstallableUnit[theIUs.size()]); + return theIUs.toArray(new IInstallableUnit[theIUs.size()]); } static boolean containsURI(URI[] locations, URI url) { diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/IIUElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/IIUElement.java index 7429ff412..06f419b1b 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/IIUElement.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/IIUElement.java @@ -10,9 +10,10 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.model; +import java.util.Collection; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; /** * Interface for elements that represent IU's. @@ -21,24 +22,6 @@ import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; */ public interface IIUElement { - /** - * Indicates that the size is currently unknown - */ - public static final long SIZE_UNKNOWN = -1L; - - /** - * Indicates that the size is unavailable (an - * attempt was made to compute size but it failed) - */ - public static final long SIZE_UNAVAILABLE = -2L; - - /** - * Indicates that there was nothing to size (there - * was no valid plan that could be used to compute - * size). - */ - public static final long SIZE_NOTAPPLICABLE = -3L; - public IInstallableUnit getIU(); public boolean shouldShowSize(); @@ -49,7 +32,7 @@ public interface IIUElement { public void computeSize(IProgressMonitor monitor); - public IRequiredCapability[] getRequirements(); + public Collection getRequirements(); public Object getParent(Object obj); diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/IRepositoryElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/IRepositoryElement.java new file mode 100644 index 000000000..f2890b704 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/IRepositoryElement.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.model; + +import java.net.URI; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.equinox.p2.repository.IRepository; + +/** + * Interface for elements that represent repositories. + * + * @since 3.4 + */ +public interface IRepositoryElement { + + public URI getLocation(); + + public String getName(); + + public String getDescription(); + + public boolean isEnabled(); + + public void setEnabled(boolean enabled); + + public IRepository getRepository(IProgressMonitor monitor); +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/IUElementListRoot.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/IUElementListRoot.java new file mode 100644 index 000000000..5689beea3 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/IUElementListRoot.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.model; + + + +/** + * Element class representing a fixed set of IU's. This element should + * never appear in a list, but can be used as a parent in a list. + * + * @since 3.5 + */ +public class IUElementListRoot extends ProvElement { + + Object[] children; + + public IUElementListRoot(Object[] children) { + super(null); + this.children = children; + } + + public IUElementListRoot() { + this(new Object[0]); + } + + public void setChildren(Object[] children) { + this.children = children; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.equinox.internal.provisional.p2.ui.model.ProvElement#getImageID(java.lang.Object) + */ + protected String getImageId(Object obj) { + return null; + } + + public String getLabel(Object o) { + return null; + } + + /* (non-Javadoc) + * @see org.eclipse.ui.model.IWorkbenchAdapter#getChildren(java.lang.Object) + */ + public Object[] getChildren(Object o) { + return children; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/InstalledIUElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/InstalledIUElement.java new file mode 100644 index 000000000..0b180a4d0 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/InstalledIUElement.java @@ -0,0 +1,129 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.model; + +import java.util.Collection; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.equinox.internal.p2.ui.ProvUIImages; +import org.eclipse.equinox.internal.p2.ui.QueryProvider; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; +import org.eclipse.equinox.p2.operations.ProvisioningSession; + +/** + * Element wrapper class for installed IU's. Used instead of the plain IU when + * there should be a parent profile available for operations. + * + * @since 3.4 + */ +public class InstalledIUElement extends QueriedElement implements IIUElement { + + String profileId; + IInstallableUnit iu; + + public InstalledIUElement(Object parent, String profileId, IInstallableUnit iu) { + super(parent); + this.profileId = profileId; + this.iu = iu; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.equinox.internal.provisional.p2.ui.model.ProvElement#getImageID(java.lang.Object) + */ + protected String getImageId(Object obj) { + return ProvUIImages.IMG_IU; + } + + public String getLabel(Object o) { + return iu.getId(); + } + + @SuppressWarnings("rawtypes") + public Object getAdapter(Class adapter) { + if (adapter == IInstallableUnit.class) + return iu; + return super.getAdapter(adapter); + } + + public String getProfileId() { + return profileId; + } + + public IInstallableUnit getIU() { + return iu; + } + + // TODO Later we might consider showing this in the installed views, + // but it is less important than before install. + public long getSize() { + return ProvisioningSession.SIZE_UNKNOWN; + } + + public boolean shouldShowSize() { + return false; + } + + public void computeSize(IProgressMonitor monitor) { + // Should never be called, as long as shouldShowSize() returns false + } + + public boolean shouldShowVersion() { + return true; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.model.IUElement#getRequirements() + */ + public Collection getRequirements() { + return iu.getRequiredCapabilities(); + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.model.QueriedElement#getDefaultQueryType() + */ + protected int getDefaultQueryType() { + return QueryProvider.INSTALLED_IUS; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.model.IIUElement#shouldShowChildren() + */ + public boolean shouldShowChildren() { + return true; + } + + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof InstalledIUElement)) + return false; + if (iu == null) + return false; + return iu.equals(((InstalledIUElement) obj).getIU()); + } + + public int hashCode() { + if (iu == null) + return 0; + return iu.hashCode(); + } + + public String toString() { + if (iu == null) + return "NULL"; //$NON-NLS-1$ + return iu.toString(); + } + +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/MetadataRepositories.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/MetadataRepositories.java new file mode 100644 index 000000000..df87eea75 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/MetadataRepositories.java @@ -0,0 +1,101 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.model; + +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.query.IUViewQueryContext; +import org.eclipse.equinox.p2.ui.ProvisioningUI; + +/** + * Element class that represents some collection of metadata repositories. + * It can be configured so that it retrieves its children in different ways. + * The default query type will return the metadata repositories specified in + * this element. Other query types can be used to query each repository and + * aggregate the children. + * + * @since 3.4 + * + */ +public class MetadataRepositories extends RootElement { + + private boolean includeDisabled = false; + + public MetadataRepositories(ProvisioningUI ui) { + this(ProvUI.getQueryContext(ui.getPolicy()), ui, null); + } + + public MetadataRepositories(IUViewQueryContext queryContext, ProvisioningUI ui, QueryableMetadataRepositoryManager queryable) { + super(queryContext, ui); + this.queryable = queryable; + } + + /** + * Get whether disabled repositories should be included in queries when no repositories + * have been specified. This boolean is used because the flags specified when getting + * repositories from a repository manager are treated as an AND, and we want to permit + * aggregating disabled repositories along with other flags. + * + * @return includeDisabled true if disabled repositories should be included and + * false if they should not be included. + */ + public boolean getIncludeDisabledRepositories() { + return includeDisabled; + } + + /** + * Set whether disabled repositories should be included in queries when no repositories + * have been specified. This boolean is used because the flags specified when getting + * repositories from a repository manager are treated as an AND, and we want to permit + * aggregating disabled repositories along with other flags. + * + * @param includeDisabled true if disabled repositories should be included and + * false if they should not be included. + */ + public void setIncludeDisabledRepositories(boolean includeDisabled) { + this.includeDisabled = includeDisabled; + } + + /* + * Overridden to check the query context. We might + * be showing repositories, or we might be flattening the + * view to some other element + * (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueriedElement#getQueryType() + */ + public int getQueryType() { + if (getQueryContext() == null) + return getDefaultQueryType(); + return getQueryContext().getQueryType(); + } + + protected int getDefaultQueryType() { + return QueryProvider.METADATA_REPOS; + } + + /* + * (non-Javadoc) + * @see org.eclipse.ui.model.IWorkbenchAdapter#getLabel(java.lang.Object) + */ + public String getLabel(Object o) { + return ProvUIMessages.Label_Repositories; + } + + /* + * Overridden because we might be iterating sites + * (type = METADATA_REPOSITORIES) rather than loading repos. If this + * is the case, we only care whether we have a queryable or not. + */ + public boolean hasQueryable() { + if (getQueryType() == QueryProvider.METADATA_REPOS) + return queryable != null; + return super.hasQueryable(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/MetadataRepositoryElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/MetadataRepositoryElement.java index b6a146cf7..8d8cd5f0b 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/MetadataRepositoryElement.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/MetadataRepositoryElement.java @@ -14,19 +14,17 @@ import java.net.URI; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IRepositoryElement; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; -import org.eclipse.ui.statushandlers.StatusManager; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.query.IUViewQueryContext; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; +import org.eclipse.equinox.p2.ui.Policy; +import org.eclipse.equinox.p2.ui.ProvisioningUI; /** * Element wrapper class for a metadata repository that gets its @@ -36,28 +34,27 @@ import org.eclipse.ui.statushandlers.StatusManager; * * @since 3.4 */ -public class MetadataRepositoryElement extends RootElement implements IRepositoryElement { +public class MetadataRepositoryElement extends RootElement implements IRepositoryElement { URI location; boolean isEnabled; String name; public MetadataRepositoryElement(Object parent, URI location, boolean isEnabled) { - this(parent, null, null, location, isEnabled); + this(parent, null, ProvisioningUI.getDefaultUI(), location, isEnabled); } - public MetadataRepositoryElement(IUViewQueryContext queryContext, Policy policy, URI location, boolean isEnabled) { - super(null, queryContext, policy); - this.location = location; - this.isEnabled = isEnabled; + public MetadataRepositoryElement(IUViewQueryContext queryContext, ProvisioningUI ui, URI location, boolean isEnabled) { + this(null, queryContext, ui, location, isEnabled); } - private MetadataRepositoryElement(Object parent, IUViewQueryContext queryContext, Policy policy, URI location, boolean isEnabled) { - super(parent, queryContext, policy); + private MetadataRepositoryElement(Object parent, IUViewQueryContext queryContext, ProvisioningUI ui, URI location, boolean isEnabled) { + super(parent, queryContext, ui); this.location = location; this.isEnabled = isEnabled; } + @SuppressWarnings("rawtypes") public Object getAdapter(Class adapter) { if (adapter == IMetadataRepository.class) return getQueryable(); @@ -76,7 +73,7 @@ public class MetadataRepositoryElement extends RootElement implements IRepositor //only invoke super if we successfully loaded the repository return super.fetchChildren(o, sub.newChild(100)); } catch (ProvisionException e) { - ProvUI.reportLoadFailure(location, e.getStatus(), StatusManager.SHOW, getPolicy().getRepositoryManipulator()); + getProvisioningUI().getRepositoryTracker().reportLoadFailure(location, e); // TODO see https://bugs.eclipse.org/bugs/show_bug.cgi?id=276784 return new Object[] {new EmptyElementExplanation(this, IStatus.ERROR, e.getLocalizedMessage(), "")}; //$NON-NLS-1$ } @@ -103,24 +100,25 @@ public class MetadataRepositoryElement extends RootElement implements IRepositor * (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueriedElement#getQueryable() */ - public IQueryable getQueryable() { + public IQueryable getQueryable() { if (queryable == null) - return (IQueryable) getRepository(new NullProgressMonitor()); + queryable = getRepository(new NullProgressMonitor()); return queryable; } - public IRepository getRepository(IProgressMonitor monitor) { + public IMetadataRepository getRepository(IProgressMonitor monitor) { try { return getMetadataRepository(monitor); } catch (ProvisionException e) { - ProvUI.reportLoadFailure(location, e.getStatus(), StatusManager.SHOW, getPolicy().getRepositoryManipulator()); + getProvisioningUI().getRepositoryTracker().reportLoadFailure(location, e); } return null; } private IMetadataRepository getMetadataRepository(IProgressMonitor monitor) throws ProvisionException { - if (queryable == null) - queryable = ProvisioningUtil.loadMetadataRepository(location, monitor); + if (queryable == null) { + queryable = getProvisioningUI().loadMetadataRepository(location, false, monitor); + } return (IMetadataRepository) queryable; } @@ -147,16 +145,13 @@ public class MetadataRepositoryElement extends RootElement implements IRepositor * @see org.eclipse.equinox.internal.provisional.p2.ui.model.RepositoryElement#getName() */ public String getName() { + ProvisioningSession session = getProvisioningUI().getSession(); if (name == null) { - try { - name = ProvisioningUtil.getMetadataRepositoryProperty(location, IRepository.PROP_NICKNAME); - if (name == null) - name = ProvisioningUtil.getMetadataRepositoryProperty(location, IRepository.PROP_NAME); - if (name == null) - name = ""; //$NON-NLS-1$ - } catch (ProvisionException e) { + name = session.getMetadataRepositoryManager().getRepositoryProperty(location, IRepository.PROP_NICKNAME); + if (name == null) + name = session.getMetadataRepositoryManager().getRepositoryProperty(location, IRepository.PROP_NAME); + if (name == null) name = ""; //$NON-NLS-1$ - } } return name; } @@ -175,16 +170,13 @@ public class MetadataRepositoryElement extends RootElement implements IRepositor * @see org.eclipse.equinox.internal.provisional.p2.ui.model.RepositoryElement#getDescription() */ public String getDescription() { - if (ProvUI.hasNotFoundStatusBeenReported(location)) + ProvisioningSession session = getProvisioningUI().getSession(); + if (getProvisioningUI().getRepositoryTracker().hasNotFoundStatusBeenReported(location)) return ProvUIMessages.MetadataRepositoryElement_NotFound; - try { - String description = ProvisioningUtil.getMetadataRepositoryProperty(location, IRepository.PROP_DESCRIPTION); - if (description == null) - return ""; //$NON-NLS-1$ - return description; - } catch (ProvisionException e) { + String description = session.getMetadataRepositoryManager().getRepositoryProperty(location, IRepository.PROP_DESCRIPTION); + if (description == null) return ""; //$NON-NLS-1$ - } + return description; } /* (non-Javadoc) @@ -216,7 +208,7 @@ public class MetadataRepositoryElement extends RootElement implements IRepositor return true; if (location == null) return false; - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); if (manager == null || !(manager instanceof MetadataRepositoryManager)) return false; IMetadataRepository repo = ((MetadataRepositoryManager) manager).getRepository(location); @@ -232,7 +224,7 @@ public class MetadataRepositoryElement extends RootElement implements IRepositor return super.getPolicy(); if (parent instanceof QueriedElement) return ((QueriedElement) parent).getPolicy(); - return Policy.getDefault(); + return ProvisioningUI.getDefaultUI().getPolicy(); } public String toString() { diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ProfileElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ProfileElement.java new file mode 100644 index 000000000..2da19283c --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ProfileElement.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.model; + +import org.eclipse.equinox.internal.p2.ui.ProvUIImages; +import org.eclipse.equinox.internal.p2.ui.QueryProvider; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.query.IQueryable; + +/** + * Element wrapper class for a profile that uses the query + * mechanism to obtain its contents. + * + * @since 3.4 + */ +public class ProfileElement extends RemoteQueriedElement { + String profileId; + + public ProfileElement(Object parent, String profileId) { + super(parent); + this.profileId = profileId; + } + + @SuppressWarnings("rawtypes") + public Object getAdapter(Class adapter) { + if (adapter == IProfile.class) + return getQueryable(); + return super.getAdapter(adapter); + } + + protected String getImageId(Object obj) { + return ProvUIImages.IMG_PROFILE; + } + + public String getLabel(Object o) { + return profileId; + } + + public String getProfileId() { + return profileId; + } + + protected int getDefaultQueryType() { + return QueryProvider.INSTALLED_IUS; + } + + public IQueryable getQueryable() { + return getProvisioningUI().getSession().getProfileRegistry().getProfile(profileId); + } + + /* + * Overridden to check whether we know the profile id rather + * than fetch the profile from the registry using getQueryable() + * (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueriedElement#knowsQueryable() + */ + public boolean knowsQueryable() { + return profileId != null; + } + + /* + * Overridden to check the children so that profiles + * showing in profile views accurately reflect if they + * are empty. We do not cache the children because often + * this element is the input of a view and when the view + * is refreshed we want to refetch the children. + * + * (non-Javadoc) + * @see org.eclipse.equinox.internal.p2.ui.model.RemoteQueriedElement#isContainer() + */ + public boolean isContainer() { + return super.getChildren(this).length > 0; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ProfileSnapshots.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ProfileSnapshots.java index a20faf194..d4b10e1c7 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ProfileSnapshots.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ProfileSnapshots.java @@ -12,9 +12,8 @@ package org.eclipse.equinox.internal.p2.ui.model; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.jobs.ISchedulingRule; +import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; import org.eclipse.ui.progress.IDeferredWorkbenchAdapter; import org.eclipse.ui.progress.IElementCollector; @@ -40,32 +39,27 @@ public class ProfileSnapshots extends ProvElement implements IDeferredWorkbenchA * @see org.eclipse.ui.model.IWorkbenchAdapter#getChildren(java.lang.Object) */ public Object[] getChildren(Object o) { - try { - long[] timestamps = ProvisioningUtil.getProfileTimestamps(profileId); - RollbackProfileElement[] elements = new RollbackProfileElement[timestamps.length]; - boolean skipFirst = false; - for (int i = 0; i < timestamps.length; i++) { - elements[i] = new RollbackProfileElement(this, profileId, timestamps[i]); - // Eliminate the first in the list (earliest) if there was no content at all. - // This doesn't always happen, but can, and we don't want to offer the user an empty profile to - // revert to. - if (i == 0) { - skipFirst = elements[0].getChildren(elements[0]).length == 0; - } - if (i == timestamps.length - 1) { - elements[i].setIsCurrentProfile(true); - } + long[] timestamps = ProvUIActivator.getDefault().getSession().getProfileRegistry().listProfileTimestamps(profileId); + RollbackProfileElement[] elements = new RollbackProfileElement[timestamps.length]; + boolean skipFirst = false; + for (int i = 0; i < timestamps.length; i++) { + elements[i] = new RollbackProfileElement(this, profileId, timestamps[i]); + // Eliminate the first in the list (earliest) if there was no content at all. + // This doesn't always happen, but can, and we don't want to offer the user an empty profile to + // revert to. + if (i == 0) { + skipFirst = elements[0].getChildren(elements[0]).length == 0; } - if (skipFirst) { - RollbackProfileElement[] elementsWithoutFirst = new RollbackProfileElement[elements.length - 1]; - System.arraycopy(elements, 1, elementsWithoutFirst, 0, elements.length - 1); - return elementsWithoutFirst; + if (i == timestamps.length - 1) { + elements[i].setIsCurrentProfile(true); } - return elements; - } catch (ProvisionException e) { - handleException(e, null); } - return null; + if (skipFirst) { + RollbackProfileElement[] elementsWithoutFirst = new RollbackProfileElement[elements.length - 1]; + System.arraycopy(elements, 1, elementsWithoutFirst, 0, elements.length - 1); + return elementsWithoutFirst; + } + return elements; } /* (non-Javadoc) diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/Profiles.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/Profiles.java new file mode 100644 index 000000000..3af9eb4eb --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/Profiles.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.model; + +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.internal.p2.ui.QueryProvider; +import org.eclipse.equinox.p2.ui.ProvisioningUI; + +/** + * Element class that represents the root of a profile + * viewer. Its children are the profiles that match the + * specified query for profiles. + * + * @since 3.4 + * + */ +public class Profiles extends RootElement { + + public Profiles(ProvisioningUI ui) { + super(ui); + } + + /* + * (non-Javadoc) + * @see org.eclipse.ui.model.IWorkbenchAdapter#getLabel(java.lang.Object) + */ + public String getLabel(Object o) { + return ProvUIMessages.Label_Profiles; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueriedElement#getDefaultQueryType() + */ + protected int getDefaultQueryType() { + return QueryProvider.PROFILES; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ProvElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ProvElement.java index 3758769da..047bd7034 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ProvElement.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/ProvElement.java @@ -11,9 +11,7 @@ package org.eclipse.equinox.internal.p2.ui.model; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; +import org.eclipse.equinox.internal.p2.ui.*; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.graphics.Image; @@ -36,6 +34,7 @@ public abstract class ProvElement implements IWorkbenchAdapter, IAdaptable { this.parent = parent; } + @SuppressWarnings("rawtypes") public Object getAdapter(Class adapter) { if (adapter == IWorkbenchAdapter.class) return this; diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/QueriedElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/QueriedElement.java index e708f39cc..f4bb6a83e 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/QueriedElement.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/QueriedElement.java @@ -13,10 +13,12 @@ package org.eclipse.equinox.internal.p2.ui.model; import java.util.*; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; -import org.eclipse.equinox.internal.provisional.p2.ui.ElementQueryDescriptor; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; +import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.query.IUViewQueryContext; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.ui.Policy; +import org.eclipse.equinox.p2.ui.ProvisioningUI; /** * Element class that represents an element that gets its children @@ -27,11 +29,11 @@ import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; */ public abstract class QueriedElement extends ProvElement { - protected IQueryable queryable; + protected IQueryable queryable; // This cache is used internally to facilitate child elements // that want to eliminate duplicates from the parent hierarchy. // This cache is *not* used as a general purpose child cache. - private Collection cachedChildren; + private Collection cachedChildren; protected QueriedElement(Object parent) { super(parent); @@ -41,11 +43,15 @@ public abstract class QueriedElement extends ProvElement { Object parent = getParent(this); if (parent instanceof QueriedElement) return ((QueriedElement) parent).getPolicy(); - return Policy.getDefault(); + return ProvUIActivator.getDefault().getProvisioningUI().getPolicy(); } - public QueryProvider getQueryProvider() { - return getPolicy().getQueryProvider(); + public ProvisioningUI getProvisioningUI() { + Object parent = getParent(this); + if (parent instanceof QueriedElement) + return ((QueriedElement) parent).getProvisioningUI(); + return ProvUIActivator.getDefault().getProvisioningUI(); + } public IUViewQueryContext getQueryContext() { @@ -59,6 +65,10 @@ public abstract class QueriedElement extends ProvElement { return fetchChildren(o, new NullProgressMonitor()); } + public QueryProvider getQueryProvider() { + return ProvUI.getQueryProvider(); + } + /* * (non-Javadoc) * @see org.eclipse.ui.model.IWorkbenchAdapter#getLabel(java.lang.Object) @@ -86,16 +96,16 @@ public abstract class QueriedElement extends ProvElement { } protected Object[] fetchChildren(Object o, IProgressMonitor monitor) { - cachedChildren = Collections.EMPTY_LIST; + cachedChildren = CollectionUtils.emptyList(); if (getQueryProvider() == null) return new Object[0]; ElementQueryDescriptor queryDescriptor = getQueryProvider().getQueryDescriptor(this); if (queryDescriptor == null) return new Object[0]; - Collection results = queryDescriptor.performQuery(monitor); + Collection results = queryDescriptor.performQuery(monitor); cachedChildren = Collections.unmodifiableCollection(results); if (results.size() > 0) { - Collection returnedChildren = new HashSet(); + Collection returnedChildren = new HashSet(); returnedChildren.addAll(results); Object[] siblings = getSiblings(); for (int i = 0; i < siblings.length; i++) { @@ -106,11 +116,11 @@ public abstract class QueriedElement extends ProvElement { return new Object[0]; } - public void setQueryable(IQueryable queryable) { + public void setQueryable(IQueryable queryable) { this.queryable = queryable; } - public IQueryable getQueryable() { + public IQueryable getQueryable() { return queryable; } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/QueriedElementWrapper.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/QueriedElementWrapper.java index 2b31deb32..e5085ab66 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/QueriedElementWrapper.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/QueriedElementWrapper.java @@ -14,14 +14,12 @@ package org.eclipse.equinox.internal.p2.ui.model; import java.util.*; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; -import org.eclipse.equinox.internal.provisional.p2.ui.ElementWrapper; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.model.MetadataRepositories; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.IUViewQueryContext; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.query.IUViewQueryContext; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.query.Collector; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.osgi.util.NLS; /** @@ -33,13 +31,13 @@ import org.eclipse.osgi.util.NLS; */ public abstract class QueriedElementWrapper extends ElementWrapper { - protected IQueryable queryable; + protected IQueryable queryable; protected Object parent; protected String emptyExplanationString; protected int emptyExplanationSeverity; protected String emptyExplanationDescription; - public QueriedElementWrapper(IQueryable queryable, Object parent) { + public QueriedElementWrapper(IQueryable queryable, Object parent) { this.queryable = queryable; this.parent = parent; } @@ -57,7 +55,7 @@ public abstract class QueriedElementWrapper extends ElementWrapper { return item; } - public Collection getElements(Collector collector) { + public Collection getElements(Collector collector) { // Any previously stored explanations are not valid. emptyExplanationString = null; emptyExplanationSeverity = IStatus.INFO; @@ -68,19 +66,17 @@ public abstract class QueriedElementWrapper extends ElementWrapper { // is empty and the parent is an IU, then being empty is not a big deal, it means // we are in drilldown. if (parent instanceof MetadataRepositoryElement) { + RepositoryTracker manipulator = ProvisioningUI.getDefaultUI().getRepositoryTracker(); MetadataRepositoryElement repo = (MetadataRepositoryElement) parent; - if (ProvUI.hasNotFoundStatusBeenReported(repo.getLocation())) { - String description = null; - if (Policy.getDefault().getRepositoryManipulator() != null) - description = Policy.getDefault().getRepositoryManipulator().getRepositoryNotFoundInstructionString(); - return emptyExplanation(IStatus.ERROR, NLS.bind(ProvUIMessages.QueriedElementWrapper_SiteNotFound, URIUtil.toUnencodedString(repo.getLocation())), description); + if (manipulator.hasNotFoundStatusBeenReported(repo.getLocation())) { + return emptyExplanation(IStatus.ERROR, NLS.bind(ProvUIMessages.QueriedElementWrapper_SiteNotFound, URIUtil.toUnencodedString(repo.getLocation())), ""); //$NON-NLS-1$ } } if (parent instanceof QueriedElement) { QueriedElement element = (QueriedElement) parent; IUViewQueryContext context = element.getQueryContext(); if (context == null) - context = element.getPolicy().getQueryContext(); + context = ProvUI.getQueryContext(element.getPolicy()); if (parent instanceof MetadataRepositoryElement || parent instanceof MetadataRepositories) { if (context != null && context.getViewType() == IUViewQueryContext.AVAILABLE_VIEW_BY_CATEGORY && context.getUseCategories()) { return emptyExplanation(IStatus.INFO, ProvUIMessages.QueriedElementWrapper_NoCategorizedItemsExplanation, context.getUsingCategoriesDescription()); @@ -91,7 +87,7 @@ public abstract class QueriedElementWrapper extends ElementWrapper { // It is empty, but the parent is an IU, so this could be a drilldown. return Collections.EMPTY_LIST; } - Collection elements = super.getElements(collector); + Collection elements = super.getElements(collector); // We had elements but now they have been filtered out. Hopefully // we can explain this. if (elements.isEmpty()) { @@ -104,8 +100,8 @@ public abstract class QueriedElementWrapper extends ElementWrapper { return elements; } - Collection emptyExplanation(int severity, String explanationString, String explanationDescription) { - ArrayList collection = new ArrayList(1); + Collection emptyExplanation(int severity, String explanationString, String explanationDescription) { + ArrayList collection = new ArrayList(1); collection.add(new EmptyElementExplanation(parent, severity, explanationString, explanationDescription)); return collection; } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/RemoteQueriedElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/RemoteQueriedElement.java index fa346e63e..b84c78b10 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/RemoteQueriedElement.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/RemoteQueriedElement.java @@ -13,7 +13,7 @@ package org.eclipse.equinox.internal.p2.ui.model; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.jobs.ISchedulingRule; -import org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager; +import org.eclipse.equinox.internal.p2.ui.QueryableMetadataRepositoryManager; import org.eclipse.ui.progress.IDeferredWorkbenchAdapter; import org.eclipse.ui.progress.IElementCollector; diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/RollbackProfileElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/RollbackProfileElement.java index 5e2e01e40..5258326e5 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/RollbackProfileElement.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/RollbackProfileElement.java @@ -14,13 +14,9 @@ import com.ibm.icu.text.DateFormat; import java.util.Date; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.QueryProvider; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.query.IQueryable; /** * Element class for a profile snapshot @@ -55,19 +51,16 @@ public class RollbackProfileElement extends RemoteQueriedElement { return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(new Date(timestamp)); } + @SuppressWarnings("rawtypes") public Object getAdapter(Class adapter) { if (adapter == IProfile.class) - try { - return getProfileSnapshot(new NullProgressMonitor()); - } catch (ProvisionException e) { - handleException(e, ProvUIMessages.RollbackProfileElement_InvalidSnapshot); - } + return getProfileSnapshot(new NullProgressMonitor()); return super.getAdapter(adapter); } - public IProfile getProfileSnapshot(IProgressMonitor monitor) throws ProvisionException { + public IProfile getProfileSnapshot(IProgressMonitor monitor) { if (snapshot == null) { - snapshot = ProvisioningUtil.getProfile(profileId, timestamp); + snapshot = getProvisioningUI().getSession().getProfileRegistry().getProfile(profileId, timestamp); setQueryable(snapshot); } return snapshot; @@ -97,12 +90,7 @@ public class RollbackProfileElement extends RemoteQueriedElement { * (non-Javadoc) * @see org.eclipse.equinox.internal.p2.ui.model.QueriedElement#getQueryable() */ - public IQueryable getQueryable() { - try { - return getProfileSnapshot(new NullProgressMonitor()); - } catch (ProvisionException e) { - handleException(e, null); - return null; - } + public IQueryable getQueryable() { + return getProfileSnapshot(new NullProgressMonitor()); } } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/RootElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/RootElement.java index ada55a55c..a9574e8f2 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/RootElement.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/RootElement.java @@ -10,12 +10,14 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.model; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.IUViewQueryContext; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.internal.p2.ui.query.IUViewQueryContext; +import org.eclipse.equinox.p2.ui.Policy; +import org.eclipse.equinox.p2.ui.ProvisioningUI; /** * Element class that represents the root of a viewer. It can be configured - * with its own policy and query context. + * with its own ui and query context. * * @since 3.5 * @@ -23,23 +25,23 @@ import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; public abstract class RootElement extends RemoteQueriedElement { private IUViewQueryContext queryContext; - private Policy policy; + private ProvisioningUI ui; - public RootElement(Policy policy) { - this(null, policy.getQueryContext(), policy); + public RootElement(ProvisioningUI ui) { + this(null, ProvUI.getQueryContext(ui.getPolicy()), ui); } - public RootElement(IUViewQueryContext queryContext, Policy policy) { - this(null, queryContext, policy); + public RootElement(IUViewQueryContext queryContext, ProvisioningUI ui) { + this(null, queryContext, ui); } /* * Special method for subclasses that can sometimes be a root, and sometimes not. */ - protected RootElement(Object parent, IUViewQueryContext queryContext, Policy policy) { + protected RootElement(Object parent, IUViewQueryContext queryContext, ProvisioningUI ui) { super(parent); this.queryContext = queryContext; - this.policy = policy; + this.ui = ui; } /** @@ -56,6 +58,10 @@ public abstract class RootElement extends RemoteQueriedElement { } public Policy getPolicy() { - return policy; + return ui.getPolicy(); + } + + public ProvisioningUI getProvisioningUI() { + return ui; } } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/Updates.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/Updates.java new file mode 100644 index 000000000..3f227d0a2 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/model/Updates.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.model; + +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.internal.p2.ui.QueryProvider; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; + +/** + * Element class that represents available updates. + * + * @since 3.4 + * + */ +public class Updates extends QueriedElement { + + private String profileId; + private IInstallableUnit[] iusToBeUpdated; + + public Updates(String profileId) { + this(profileId, null); + } + + public Updates(String profileId, IInstallableUnit[] iusToBeUpdated) { + super(null); + this.profileId = profileId; + this.iusToBeUpdated = iusToBeUpdated; + } + + /* + * (non-Javadoc) + * @see org.eclipse.ui.model.IWorkbenchAdapter#getLabel(java.lang.Object) + */ + public String getLabel(Object o) { + return ProvUIMessages.Updates_Label; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueriedElement#getDefaultQueryType() + */ + protected int getDefaultQueryType() { + return QueryProvider.AVAILABLE_UPDATES; + } + + public String getProfileId() { + return profileId; + } + + public IInstallableUnit[] getIUs() { + return iusToBeUpdated; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/AnyRequiredCapabilityQuery.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/AnyRequiredCapabilityQuery.java deleted file mode 100644 index ef3c69840..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/AnyRequiredCapabilityQuery.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.ui.query; - -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.MatchQuery; - -/** - * A query that searches a repository for all {@link IInstallableUnit} instances that - * meet any one of the given capabilities. - */ -public class AnyRequiredCapabilityQuery extends MatchQuery { - private IRequiredCapability[] requirements; - - /** - * Creates a new query for the capabilities of the given IU. - */ - public AnyRequiredCapabilityQuery(IRequiredCapability[] requirements) { - this.requirements = requirements; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.p2.query2.Query#isMatch(java.lang.Object) - */ - public boolean isMatch(Object object) { - if (!(object instanceof IInstallableUnit)) - return false; - IInstallableUnit candidate = (IInstallableUnit) object; - for (int i = 0; i < requirements.length; i++) - if (candidate.satisfies(requirements[i])) - return true; - return false; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/ArtifactKeyWrapper.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/ArtifactKeyWrapper.java new file mode 100644 index 000000000..27a4304a7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/ArtifactKeyWrapper.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * EclipseSource - ongoing development + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.query; + +import org.eclipse.equinox.internal.p2.ui.model.ArtifactElement; +import org.eclipse.equinox.internal.p2.ui.model.QueriedElementWrapper; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; + +/** + * Wrapper that accepts artifact keys and wraps them in an ArtifactKeyElement. + * + * @since 3.6 + */ +public class ArtifactKeyWrapper extends QueriedElementWrapper { + + IArtifactRepository repo; + + public ArtifactKeyWrapper(IArtifactRepository repo, Object parent) { + super(repo, parent); + this.repo = repo; + } + + protected boolean shouldWrap(Object match) { + if ((match instanceof IArtifactKey)) + return true; + return false; + } + + /** + * Transforms the item to a UI element + */ + protected Object wrap(Object item) { + return super.wrap(new ArtifactElement(parent, (IArtifactKey) item, repo)); + } + +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/ArtifactRepositoryElementWrapper.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/ArtifactRepositoryElementWrapper.java new file mode 100644 index 000000000..c3cccf152 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/ArtifactRepositoryElementWrapper.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * EclipseSource - ongoing development + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.query; + +import java.net.URI; +import org.eclipse.equinox.internal.p2.ui.model.ArtifactRepositoryElement; +import org.eclipse.equinox.internal.p2.ui.model.QueriedElementWrapper; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.ui.ProvisioningUI; + +/** + * ElementWrapper that wraps a URI with an ArtifactRepositoryElement. + * + * @since 3.4 + */ +public class ArtifactRepositoryElementWrapper extends QueriedElementWrapper { + + public ArtifactRepositoryElementWrapper(IQueryable queryable, Object parent) { + super(queryable, parent); + } + + /** + * Accepts a result that matches the query criteria. + * + * @param match an object matching the query + * @return true if the query should continue, + * or false to indicate the query should stop. + */ + protected boolean shouldWrap(Object match) { + if ((match instanceof URI)) + return true; + return false; + } + + /** + * Transforms the item to a UI element + */ + protected Object wrap(Object item) { + return super.wrap(new ArtifactRepositoryElement(parent, (URI) item, ProvisioningUI.getDefaultUI().getSession().getArtifactRepositoryManager().isEnabled((URI) item))); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/AvailableIUWrapper.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/AvailableIUWrapper.java index 3b270f4cd..af3ef4209 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/AvailableIUWrapper.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/AvailableIUWrapper.java @@ -13,12 +13,15 @@ package org.eclipse.equinox.internal.p2.ui.query; import java.util.Iterator; import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.ui.ProvUI; import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; import org.eclipse.equinox.internal.p2.ui.model.*; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.CategoryQuery; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.query.IQueryable; /** * A wrapper that examines available IU's and wraps them in an @@ -33,7 +36,7 @@ public class AvailableIUWrapper extends QueriedElementWrapper { private boolean hideInstalledIUs = false; private boolean drillDownChild = false; - public AvailableIUWrapper(IQueryable queryable, Object parent, boolean makeCategories, boolean makeDrillDownChild) { + public AvailableIUWrapper(IQueryable queryable, Object parent, boolean makeCategories, boolean makeDrillDownChild) { super(queryable, parent); this.makeCategories = makeCategories; this.drillDownChild = makeDrillDownChild; @@ -59,7 +62,7 @@ public class AvailableIUWrapper extends QueriedElementWrapper { InformationCache cache = null; protected boolean shouldWrap(Object match) { - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(match, IInstallableUnit.class); + IInstallableUnit iu = ProvUI.getAdapter(match, IInstallableUnit.class); cache = computeIUInformation(iu); // Cache the result // if we are hiding, hide anything that is the same iu or older @@ -80,11 +83,11 @@ public class AvailableIUWrapper extends QueriedElementWrapper { boolean isUpdate = false; boolean isInstalled = false; if (profile != null && iu != null) { - Collector collector = profile.query(new InstallableUnitQuery(iu.getId()), new Collector(), null); - Iterator iter = collector.iterator(); + IQueryResult queryResult = profile.query(new InstallableUnitQuery(iu.getId()), null); + Iterator iter = queryResult.iterator(); // We are typically iterating over only one IU unless it's a non-singleton. while (iter.hasNext()) { - IInstallableUnit installed = (IInstallableUnit) iter.next(); + IInstallableUnit installed = iter.next(); if (installed.getVersion().compareTo(iu.getVersion()) < 0) isUpdate = true; else { @@ -98,7 +101,7 @@ public class AvailableIUWrapper extends QueriedElementWrapper { } protected Object wrap(Object item) { - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(item, IInstallableUnit.class); + IInstallableUnit iu = ProvUI.getAdapter(item, IInstallableUnit.class); boolean isUpdate = false; boolean isInstalled = false; if (cache != null && cache.item == item) { @@ -141,8 +144,7 @@ public class AvailableIUWrapper extends QueriedElementWrapper { } protected boolean isCategory(IInstallableUnit iu) { - String isCategory = iu.getProperty(IInstallableUnit.PROP_TYPE_CATEGORY); - return isCategory != null && Boolean.valueOf(isCategory).booleanValue(); + return CategoryQuery.isCategory(iu); } protected boolean makeCategory() { diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/CategoryElementWrapper.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/CategoryElementWrapper.java index 049e5fb96..02788d2e2 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/CategoryElementWrapper.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/CategoryElementWrapper.java @@ -12,12 +12,13 @@ package org.eclipse.equinox.internal.p2.ui.query; import java.util.*; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; import org.eclipse.equinox.internal.p2.ui.model.CategoryElement; import org.eclipse.equinox.internal.p2.ui.model.QueriedElementWrapper; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IRequirement; +import org.eclipse.equinox.p2.query.Collector; +import org.eclipse.equinox.p2.query.IQueryable; /** * A collector that converts IU's to category elements as it accepts them. @@ -28,23 +29,25 @@ import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; public class CategoryElementWrapper extends QueriedElementWrapper { // Used to track nested categories - private Set referredIUs = new HashSet(); + private Set referredIUs = new HashSet(); - public CategoryElementWrapper(IQueryable queryable, Object parent) { + public CategoryElementWrapper(IQueryable queryable, Object parent) { super(queryable, parent); } protected boolean shouldWrap(Object match) { if (match instanceof IInstallableUnit) { IInstallableUnit iu = (IInstallableUnit) match; - IRequiredCapability[] requirements = iu.getRequiredCapabilities(); - for (int i = 0; i < requirements.length; i++) { - if (requirements[i].getNamespace().equals(IInstallableUnit.NAMESPACE_IU_ID)) { - referredIUs.add(requirements[i].getName()); + Collection requirements = iu.getRequiredCapabilities(); + for (IRequirement requirement : requirements) { + if (requirement instanceof IRequiredCapability) { + if (((IRequiredCapability) requirement).getNamespace().equals(IInstallableUnit.NAMESPACE_IU_ID)) { + referredIUs.add(((IRequiredCapability) requirement).getName()); + } } } - Iterator iter = super.getCollection().iterator(); + Iterator iter = super.getCollection().iterator(); // Don't add the same category IU twice. while (iter.hasNext()) { CategoryElement element = (CategoryElement) iter.next(); @@ -59,10 +62,10 @@ public class CategoryElementWrapper extends QueriedElementWrapper { return false; } - public Collection getElements(Collector collector) { + public Collection getElements(Collector collector) { if (collector.isEmpty()) return super.getElements(collector); - Collection results = super.getElements(collector); + Collection results = super.getElements(collector); cleanList(); return results; } @@ -77,7 +80,7 @@ public class CategoryElementWrapper extends QueriedElementWrapper { } private void removeNestedCategories() { - CategoryElement[] categoryIUs = (CategoryElement[]) getCollection().toArray(new CategoryElement[getCollection().size()]); + CategoryElement[] categoryIUs = getCollection().toArray(new CategoryElement[getCollection().size()]); // If any other element refers to a category element, remove it from the list for (int i = 0; i < categoryIUs.length; i++) { if (referredIUs.contains(categoryIUs[i].getIU().getId())) { diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/IUViewQueryContext.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/IUViewQueryContext.java new file mode 100644 index 000000000..0aa3daf34 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/IUViewQueryContext.java @@ -0,0 +1,169 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.query; + +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.internal.p2.ui.QueryProvider; + +/** + * IUViewQueryContext defines the different ways + * IUs can be viewed. Clients can use this context to + * control how the various IU views are represented and traversed. + * + * @since 2.0 + */ +public class IUViewQueryContext { + public static final int AVAILABLE_VIEW_BY_CATEGORY = 1; + public static final int AVAILABLE_VIEW_BY_REPO = 2; + public static final int AVAILABLE_VIEW_FLAT = 3; + + // Available view settings + // Default available view to repo as this provides the fastest information + private int view = AVAILABLE_VIEW_BY_REPO; + // Whether to show latest versions only, defaults to + // true. Clients typically use a pref setting or dialog + // setting to initialize + private boolean showLatestVersionsOnly = true; + // Whether to hide things that are already installed + // Defaults to false since we wouldn't know what profile to use + private boolean hideAlreadyInstalled = false; + // Whether to group items in repos by category. Note this only makes sense when the + // view type is AVAILABLE_VIEW_BY_REPO + private boolean useCategories = true; + // Whether to drill down into installed items + private boolean showInstallChildren = true; + // Whether to drill down into available items + private boolean showAvailableChildren = false; + // Whether to drill down into items in a provisioning plan + private boolean showProvisioningPlanChildren = true; + + private String profileId = null; + + private String hidingInstalledDescription = ProvUIMessages.IUViewQueryContext_AllAreInstalledDescription; + private String groupingCategoriesDescription = ProvUIMessages.IUViewQueryContext_NoCategorizedItemsDescription; + + public IUViewQueryContext(int viewType) { + this.view = viewType; + } + + /* (non-Javadoc) + * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueryContext#getQueryType() + */ + public int getQueryType() { + if (view == AVAILABLE_VIEW_BY_REPO) + return QueryProvider.METADATA_REPOS; + return QueryProvider.AVAILABLE_IUS; + } + + public int getViewType() { + return view; + } + + public void setViewType(int viewType) { + view = viewType; + } + + public boolean getShowLatestVersionsOnly() { + return showLatestVersionsOnly; + } + + public void setShowLatestVersionsOnly(boolean showLatest) { + showLatestVersionsOnly = showLatest; + } + + public void hideAlreadyInstalled(String installedProfileId) { + profileId = installedProfileId; + hideAlreadyInstalled = true; + } + + public void showAlreadyInstalled() { + hideAlreadyInstalled = false; + } + + public boolean getHideAlreadyInstalled() { + return hideAlreadyInstalled; + } + + public String getInstalledProfileId() { + return profileId; + } + + public void setInstalledProfileId(String profileId) { + this.profileId = profileId; + } + + /** + * Set a boolean that indicates whether categories should be used when + * viewing by repository. + * + * useCategories true if a site in a sites view should expand into categories, + * false if it should expand into IU's. + */ + + public void setUseCategories(boolean useCategories) { + this.useCategories = useCategories; + } + + /** + * Return a boolean that indicates whether categories should be used when + * viewing by repository. + * + * @return true if a site in a sites view should expand into categories, + * false if it should expand into IU's. + */ + public boolean getUseCategories() { + return useCategories; + } + + public boolean getShowInstallChildren() { + return showInstallChildren; + } + + public void setShowInstallChildren(boolean showChildren) { + showInstallChildren = showChildren; + } + + public boolean getShowAvailableChildren() { + return showAvailableChildren; + } + + public void setShowAvailableChildren(boolean showChildren) { + showAvailableChildren = showChildren; + } + + public boolean getShowProvisioningPlanChildren() { + return showProvisioningPlanChildren; + } + + public void setShowProvisioningPlanChildren(boolean showChildren) { + showProvisioningPlanChildren = showChildren; + } + + public String getHidingInstalledDescription() { + return hidingInstalledDescription; + } + + public void setHidingInstalledDescription(String description) { + hidingInstalledDescription = description; + } + + public String getUsingCategoriesDescription() { + return groupingCategoriesDescription; + } + + public void setUsingCategoriesDescription(String description) { + groupingCategoriesDescription = description; + } + + public boolean shouldGroupByCategories() { + return view == AVAILABLE_VIEW_BY_CATEGORY || (view == AVAILABLE_VIEW_BY_REPO && useCategories); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/InstalledIUElementWrapper.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/InstalledIUElementWrapper.java index 87e9c2c0e..9e465a8f8 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/InstalledIUElementWrapper.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/InstalledIUElementWrapper.java @@ -11,11 +11,11 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.query; +import org.eclipse.equinox.internal.p2.ui.model.InstalledIUElement; import org.eclipse.equinox.internal.p2.ui.model.QueriedElementWrapper; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; -import org.eclipse.equinox.internal.provisional.p2.ui.model.InstalledIUElement; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQueryable; /** * ElementWrapper that accepts the matched IU's and @@ -25,7 +25,7 @@ import org.eclipse.equinox.internal.provisional.p2.ui.model.InstalledIUElement; */ public class InstalledIUElementWrapper extends QueriedElementWrapper { - public InstalledIUElementWrapper(IQueryable queryable, Object parent) { + public InstalledIUElementWrapper(IQueryable queryable, Object parent) { super(queryable, parent); } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/MetadataRepositoryElementWrapper.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/MetadataRepositoryElementWrapper.java index ab4c3b760..245f726be 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/MetadataRepositoryElementWrapper.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/MetadataRepositoryElementWrapper.java @@ -14,8 +14,8 @@ package org.eclipse.equinox.internal.p2.ui.query; import java.net.URI; import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement; import org.eclipse.equinox.internal.p2.ui.model.QueriedElementWrapper; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; +import org.eclipse.equinox.p2.query.IQueryable; +import org.eclipse.equinox.p2.ui.ProvisioningUI; /** * ElementWrapper that accepts the matched repo URLs and @@ -25,7 +25,7 @@ import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUti */ public class MetadataRepositoryElementWrapper extends QueriedElementWrapper { - public MetadataRepositoryElementWrapper(IQueryable queryable, Object parent) { + public MetadataRepositoryElementWrapper(IQueryable queryable, Object parent) { super(queryable, parent); } @@ -46,6 +46,6 @@ public class MetadataRepositoryElementWrapper extends QueriedElementWrapper { * Transforms the item to a UI element */ protected Object wrap(Object item) { - return super.wrap(new MetadataRepositoryElement(parent, (URI) item, ProvisioningUtil.getMetadataRepositoryEnablement((URI) item))); + return super.wrap(new MetadataRepositoryElement(parent, (URI) item, ProvisioningUI.getDefaultUI().getSession().getMetadataRepositoryManager().isEnabled((URI) item))); } } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/ProfileElementWrapper.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/ProfileElementWrapper.java index 060ac32f3..d102bafae 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/ProfileElementWrapper.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/ProfileElementWrapper.java @@ -11,9 +11,9 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui.query; +import org.eclipse.equinox.internal.p2.ui.model.ProfileElement; import org.eclipse.equinox.internal.p2.ui.model.QueriedElementWrapper; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.ui.model.ProfileElement; +import org.eclipse.equinox.p2.engine.IProfile; /** * Collector that accepts the matched Profiles and diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/QueryableProfileRegistry.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/QueryableProfileRegistry.java index fb323f5e2..e14b99a73 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/QueryableProfileRegistry.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/QueryableProfileRegistry.java @@ -12,34 +12,31 @@ package org.eclipse.equinox.internal.p2.ui.query; import java.util.Arrays; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.SubMonitor; import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.ui.statushandlers.StatusManager; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.ui.ProvisioningUI; /** * An object that adds queryable support to the profile registry. */ -public class QueryableProfileRegistry implements IQueryable { +public class QueryableProfileRegistry implements IQueryable { - public Collector query(Query query, Collector result, IProgressMonitor monitor) { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName()); - if (profileRegistry == null) { - ProvUI.reportStatus(new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound), StatusManager.SHOW | StatusManager.LOG); - return result; - } - IProfile[] profiles = profileRegistry.getProfiles(); + private ProvisioningUI ui; + + public QueryableProfileRegistry(ProvisioningUI ui) { + this.ui = ui; + } + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + IProfile[] profiles = ui.getSession().getProfileRegistry().getProfiles(); SubMonitor sub = SubMonitor.convert(monitor, ProvUIMessages.QueryableProfileRegistry_QueryProfileProgress, profiles.length); try { - query.perform(Arrays.asList(profiles).iterator(), result); + return query.perform(Arrays.asList(profiles).iterator()); } finally { sub.done(); } - return result; } } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/QueryableUpdates.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/QueryableUpdates.java index 96b00f645..fbcad64ce 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/QueryableUpdates.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/query/QueryableUpdates.java @@ -13,52 +13,47 @@ package org.eclipse.equinox.internal.p2.ui.query; import java.util.ArrayList; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.ui.statushandlers.StatusManager; +import org.eclipse.equinox.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.ui.ProvisioningUI; /** * An object that implements a query for available updates */ -public class QueryableUpdates implements IQueryable { +public class QueryableUpdates implements IQueryable { private IInstallableUnit[] iusToUpdate; + ProvisioningUI ui; - public QueryableUpdates(IInstallableUnit[] iusToUpdate) { + public QueryableUpdates(ProvisioningUI ui, IInstallableUnit[] iusToUpdate) { + this.ui = ui; this.iusToUpdate = iusToUpdate; } - public Collector query(Query query, Collector result, IProgressMonitor monitor) { + public IQueryResult query(IQuery query, IProgressMonitor monitor) { if (monitor == null) monitor = new NullProgressMonitor(); int totalWork = 2000; monitor.beginTask(ProvUIMessages.QueryableUpdates_UpdateListProgress, totalWork); - IPlanner planner = (IPlanner) ServiceHelper.getService(ProvUIActivator.getContext(), IPlanner.class.getName()); - if (planner == null) { - ProvUI.reportStatus(new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningUtil_NoPlannerFound), StatusManager.SHOW | StatusManager.LOG); - return result; - } + IPlanner planner = ui.getSession().getPlanner(); try { - ArrayList allUpdates = new ArrayList(); + ArrayList allUpdates = new ArrayList(); for (int i = 0; i < iusToUpdate.length; i++) { if (monitor.isCanceled()) - return result; + return Collector.emptyCollector(); IInstallableUnit[] updates = planner.updatesFor(iusToUpdate[i], new ProvisioningContext(), new SubProgressMonitor(monitor, totalWork / 2 / iusToUpdate.length)); for (int j = 0; j < updates.length; j++) allUpdates.add(updates[j]); } - query.perform(allUpdates.iterator(), result); + return query.perform(allUpdates.iterator()); } catch (OperationCanceledException e) { // Nothing more to do, return result + return Collector.emptyCollector(); } finally { monitor.done(); } - return result; } } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/DeferredQueryContentProvider.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/DeferredQueryContentProvider.java index 163271e05..338acc279 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/DeferredQueryContentProvider.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/DeferredQueryContentProvider.java @@ -16,7 +16,6 @@ import java.util.HashSet; import org.eclipse.core.runtime.ListenerList; import org.eclipse.equinox.internal.p2.ui.model.QueriedElement; import org.eclipse.equinox.internal.p2.ui.model.RemoteQueriedElement; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.ProvElementContentProvider; import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.Viewer; @@ -32,8 +31,8 @@ public class DeferredQueryContentProvider extends ProvElementContentProvider { DeferredQueryTreeContentManager manager; Object currentInput; - HashMap alreadyQueried = new HashMap(); - HashSet queryCompleted = new HashSet(); + HashMap alreadyQueried = new HashMap(); + HashSet queryCompleted = new HashSet(); AbstractTreeViewer viewer = null; ListenerList listeners = new ListenerList(); boolean synchronous = false; @@ -73,8 +72,8 @@ public class DeferredQueryContentProvider extends ProvElementContentProvider { }); } else viewer = null; - alreadyQueried = new HashMap(); - queryCompleted = new HashSet(); + alreadyQueried = new HashMap(); + queryCompleted = new HashSet(); currentInput = newInput; Object[] inputListeners = listeners.getListeners(); for (int i = 0; i < inputListeners.length; i++) { diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUColumnConfig.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUColumnConfig.java new file mode 100644 index 000000000..62cd2860e --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUColumnConfig.java @@ -0,0 +1,172 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.viewers; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.swt.graphics.FontMetrics; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.widgets.Control; + +/** + * An IUColumnConfig describes a column in a viewer that is showing + * information about an IIInstallableUnit. + * + * @since 3.4 + */ +public class IUColumnConfig { + /** + * Constant indicating that the column represents an IInstallableUnit's id + */ + public final static int COLUMN_ID = 0; + + /** + * Constant indicating that the column represents an IInstallableUnit's name + */ + public final static int COLUMN_NAME = 1; + + /** + * Constant indicating that the column represents an IInstallableUnit's version + */ + public final static int COLUMN_VERSION = 2; + + /** + * Constant indicating that the column represents an IInstallableUnit's size + */ + public final static int COLUMN_SIZE = 3; + + private String columnTitle; + private int columnType; + private int columnWidth; + private int columnWidthInPixels; + + /** + * Create an IUColumnConfig describing a column with the specified title, type, and + * default width. + * + * @param title the title that should appear for the column + * @param columnType the type of column represented. The type may be used to determine + * appropriate size or formatting of the column's content. + * @param columnWidthInChars the width (in characters) that should be used for the column if no + * other width is specified by the client. + */ + + public IUColumnConfig(String title, int columnType, int columnWidthInChars) { + this.columnTitle = title; + this.columnType = columnType; + this.columnWidth = columnWidthInChars; + this.columnWidthInPixels = -1; + } + + /** + * Return the title of the column. + * @return the title that should be used for the column. + * + * @since 3.6 + */ + public String getColumnTitle() { + return columnTitle; + } + + /** + * Set the title of the column + * @param title the String that should be used when the column's title is shown + * + * @since 3.6 + */ + public void setColumnTitle(String title) { + this.columnTitle = title; + } + + /** + * Return the width of the column in character width units + * @return the width (in characters) of the column + * + * @since 3.6 + */ + public int getWidthInChars() { + return columnWidth; + } + + /** + * Set the width of the column in character width units + * @param columnWidth the width (in characters) of the column + * + * @since 3.6 + */ + public void setWidthInChars(int columnWidth) { + this.columnWidth = columnWidth; + } + + /** + * Get the width in pixels of this column when displayed in the specified + * control. If a specific width in pixels has already been specified by a client, + * that width is used. Otherwise, the value is computed based on the character + * width specified for the column. + * @param control + * @return the width in pixels that should be used for the column + * + * @since 3.6 + * + * @see #setWidthInPixels(int) + */ + public int getWidthInPixels(Control control) { + if (columnWidthInPixels >= 0) + return columnWidthInPixels; + + GC gc = new GC(control); + FontMetrics fm = gc.getFontMetrics(); + columnWidthInPixels = Dialog.convertWidthInCharsToPixels(fm, columnWidth); + return columnWidthInPixels; + } + + /** + * Set the width in pixels that should be used for this column. This width overrides + * any character width that has been specified. This method is useful when the column width + * is determined by user action. + * + * @param width + * + * @since 3.6 + */ + public void setWidthInPixels(int width) { + this.columnWidthInPixels = width; + } + + /** + * Return the type of column. + * @return an Integer constant specifying the type of data being shown in the column. + * + * @since 3.6 + * @see #COLUMN_ID + * @see #COLUMN_NAME + * @see #COLUMN_SIZE + * @see #COLUMN_VERSION + */ + public int getColumnType() { + return columnType; + } + + /** + * Set the type of column. + * @param type an Integer constant specifying the type of data being shown in the column. + * + * @since 3.6 + * + * @see #COLUMN_ID + * @see #COLUMN_NAME + * @see #COLUMN_SIZE + * @see #COLUMN_VERSION + */ + public void setColumnType(int type) { + this.columnType = type; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUComparator.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUComparator.java new file mode 100644 index 000000000..e742aeca9 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUComparator.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.viewers; + +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.viewers.ViewerComparator; + +public class IUComparator extends ViewerComparator { + public static final int IU_NAME = 0; + public static final int IU_ID = 1; + private int key; + private boolean showingId = false; + + public IUComparator(int sortKey) { + this.key = sortKey; + showingId = sortKey == IU_ID; + } + + /** + * Use the specified column config to determine + * whether the id should be used in lieu of an empty name + * when sorting. + * + * @param columnConfig + */ + public void useColumnConfig(IUColumnConfig[] columnConfig) { + for (int i = 0; i < columnConfig.length; i++) + if (columnConfig[i].getColumnType() == IUColumnConfig.COLUMN_ID) { + showingId = true; + break; + } + } + + public int compare(Viewer viewer, Object obj1, Object obj2) { + IInstallableUnit iu1 = ProvUI.getAdapter(obj1, IInstallableUnit.class); + IInstallableUnit iu2 = ProvUI.getAdapter(obj2, IInstallableUnit.class); + if (iu1 == null || iu2 == null) + // If these are not iu's use the super class comparator. + return super.compare(viewer, obj1, obj2); + + String key1, key2; + if (key == IU_NAME) { + // Compare the iu names in the default locale. + // If a name is not defined, we use blank if we know the id is shown in another + // column. If the id is not shown elsewhere, then we are displaying it, so use + // the id instead. + key1 = iu1.getProperty(IInstallableUnit.PROP_NAME, null); + if (key1 == null) + if (showingId) + key1 = ""; //$NON-NLS-1$ + else + key1 = iu1.getId(); + key2 = iu2.getProperty(IInstallableUnit.PROP_NAME, null); + if (key2 == null) + if (showingId) + key2 = ""; //$NON-NLS-1$ + else + key2 = iu2.getId(); + } else { + key1 = iu1.getId(); + key2 = iu2.getId(); + } + + int result = 0; + result = key1.compareToIgnoreCase(key2); + if (result == 0) { + // We want to show later versions first so compare backwards. + result = iu2.getVersion().compareTo(iu1.getVersion()); + } + return result; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUDetailsLabelProvider.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUDetailsLabelProvider.java index 35bb5d8b3..31214f8f9 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUDetailsLabelProvider.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUDetailsLabelProvider.java @@ -13,15 +13,13 @@ package org.eclipse.equinox.internal.p2.ui.viewers; import java.text.NumberFormat; import java.util.HashMap; -import java.util.Iterator; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.*; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.internal.p2.ui.*; import org.eclipse.equinox.internal.p2.ui.model.IIUElement; import org.eclipse.equinox.internal.p2.ui.model.ProvElement; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.IUColumnConfig; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.ProvisioningSession; import org.eclipse.jface.viewers.*; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.graphics.Font; @@ -45,7 +43,7 @@ public class IUDetailsLabelProvider extends ColumnLabelProvider implements ITabl private IUColumnConfig[] columnConfig; Shell shell; - HashMap jobs = new HashMap(); + HashMap jobs = new HashMap(); public IUDetailsLabelProvider() { this(null, null, null); @@ -79,7 +77,7 @@ public class IUDetailsLabelProvider extends ColumnLabelProvider implements ITabl columnContent = columnConfig[columnIndex].getColumnType(); } - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(element, IInstallableUnit.class); + IInstallableUnit iu = ProvUI.getAdapter(element, IInstallableUnit.class); if (iu == null) { if (columnIndex == 0) { if (element instanceof ProvElement) @@ -94,7 +92,7 @@ public class IUDetailsLabelProvider extends ColumnLabelProvider implements ITabl return iu.getId(); case IUColumnConfig.COLUMN_NAME : // Get the iu name in the current locale - String name = IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_NAME); + String name = iu.getProperty(IInstallableUnit.PROP_NAME, null); if (name != null) return name; // If the iu name is not available, we return blank if we know know we are @@ -135,7 +133,7 @@ public class IUDetailsLabelProvider extends ColumnLabelProvider implements ITabl long size = element.getSize(); // If size is already known, or we already tried // to get it, don't try again - if (size != IIUElement.SIZE_UNKNOWN) + if (size != ProvisioningSession.SIZE_UNKNOWN) return getFormattedSize(size); if (!jobs.containsKey(element)) { Job resolveJob = new Job(element.getIU().getId()) { @@ -153,7 +151,7 @@ public class IUDetailsLabelProvider extends ColumnLabelProvider implements ITabl return Status.CANCEL_STATUS; // If we still could not compute size, give up - if (element.getSize() == IIUElement.SIZE_UNKNOWN) + if (element.getSize() == ProvisioningSession.SIZE_UNKNOWN) return Status.OK_STATUS; if (shell == null || shell.isDisposed()) @@ -183,7 +181,7 @@ public class IUDetailsLabelProvider extends ColumnLabelProvider implements ITabl } private String getFormattedSize(long size) { - if (size == IIUElement.SIZE_UNKNOWN || size == IIUElement.SIZE_UNAVAILABLE) + if (size == ProvisioningSession.SIZE_UNKNOWN || size == ProvisioningSession.SIZE_UNAVAILABLE) return ProvUIMessages.IUDetailsLabelProvider_Unknown; if (size > 1000L) { long kb = size / 1000L; @@ -211,10 +209,10 @@ public class IUDetailsLabelProvider extends ColumnLabelProvider implements ITabl } public String getToolTipText(Object element) { - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(element, IInstallableUnit.class); + IInstallableUnit iu = ProvUI.getAdapter(element, IInstallableUnit.class); if (iu == null || toolTipProperty == null) return null; - return IUPropertyUtils.getIUProperty(iu, toolTipProperty); + return iu.getProperty(toolTipProperty, null); } /* (non-Javadoc) @@ -229,11 +227,8 @@ public class IUDetailsLabelProvider extends ColumnLabelProvider implements ITabl public void dispose() { super.dispose(); - Iterator iter = jobs.values().iterator(); - while (iter.hasNext()) { - Job job = (Job) iter.next(); + for (Job job : jobs.values()) job.cancel(); - } } } diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUDragAdapter.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUDragAdapter.java new file mode 100644 index 000000000..57e163043 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/IUDragAdapter.java @@ -0,0 +1,128 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.viewers; + +import java.util.*; +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.jface.util.LocalSelectionTransfer; +import org.eclipse.jface.viewers.*; +import org.eclipse.swt.dnd.*; +import org.eclipse.swt.widgets.Control; + +/** + * Implements drag behaviour when IU items are dragged from a repository view. + * + * @since 3.4 + */ +public class IUDragAdapter extends DragSourceAdapter { + + ISelectionProvider selectionProvider; + + /** + * Constructs a new drag adapter. + * + * @param provider + * The selection provider + */ + public IUDragAdapter(ISelectionProvider provider) { + selectionProvider = provider; + } + + /** + * Set the drag data to represent the local selection of IU's if possible. + * Fallback to using a text description of each IU. + */ + public void dragSetData(DragSourceEvent event) { + IInstallableUnit[] ius = getSelectedIUs(); + + if (ius == null || ius.length == 0) { + return; + } + + // use local selection transfer if possible + if (LocalSelectionTransfer.getTransfer().isSupportedType(event.dataType)) { + event.data = LocalSelectionTransfer.getTransfer().getSelection(); + return; + } + // resort to a text transfer + if (!TextTransfer.getInstance().isSupportedType(event.dataType)) { + return; + } + + // Get a text description of each IU and set as the drag data + final StringBuffer buffer = new StringBuffer(); + + for (int i = 0; i < ius.length; i++) { + buffer.append(ius[i].toString()); + buffer.append('\n'); + } + event.data = buffer.toString(); + } + + /** + * Start the drag only if the selection contains IUs. + */ + public void dragStart(DragSourceEvent event) { + + // Focus workaround copied from navigator drag adapter + DragSource dragSource = (DragSource) event.widget; + Control control = dragSource.getControl(); + if (control != control.getDisplay().getFocusControl()) { + event.doit = false; + return; + } + + // Check the selection + IStructuredSelection selection = (IStructuredSelection) selectionProvider.getSelection(); + // No drag if nothing is selected + if (selection.isEmpty()) { + event.doit = false; + return; + } + if (!areOnlyIUsSelected(selection)) { + event.doit = false; + return; + } + LocalSelectionTransfer.getTransfer().setSelection(selection); + event.doit = true; + } + + private IInstallableUnit[] getSelectedIUs() { + List ius = new ArrayList(); + + ISelection selection = selectionProvider.getSelection(); + if (!(selection instanceof IStructuredSelection) || selection.isEmpty()) { + return null; + } + IStructuredSelection structuredSelection = (IStructuredSelection) selection; + + Iterator iter = structuredSelection.iterator(); + while (iter.hasNext()) { + IInstallableUnit iu = ProvUI.getAdapter(iter.next(), IInstallableUnit.class); + if (iu != null) { + ius.add(iu); + } + } + return ius.toArray(new IInstallableUnit[ius.size()]); + } + + private boolean areOnlyIUsSelected(IStructuredSelection selection) { + Iterator iter = selection.iterator(); + while (iter.hasNext()) { + IInstallableUnit iu = ProvUI.getAdapter(iter.next(), IInstallableUnit.class); + if (iu == null) { + return false; + } + } + return true; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/InstallIUDropAdapter.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/InstallIUDropAdapter.java new file mode 100644 index 000000000..bb09719e7 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/InstallIUDropAdapter.java @@ -0,0 +1,216 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.viewers; + +import java.util.*; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.actions.InstallAction; +import org.eclipse.equinox.internal.p2.ui.model.InstalledIUElement; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.ui.ProvisioningUI; +import org.eclipse.jface.util.LocalSelectionTransfer; +import org.eclipse.jface.viewers.*; +import org.eclipse.swt.dnd.*; + +/** + * Defines drop behavior for selected IUs to mean install the IU on the target + * profile. + * + * @since 3.4 + * + */ +public class InstallIUDropAdapter extends ViewerDropAdapter { + + static boolean DEBUG = false; + ProvisioningUI ui; + + /** + * Constructs a new drop adapter. + * + * @param viewer + * the navigator's viewer + */ + public InstallIUDropAdapter(ProvisioningUI ui, StructuredViewer viewer) { + super(viewer); + this.ui = ui; + } + + /** + * Returns an error status with the given info. + */ + IStatus error(String message) { + return error(message, null); + } + + /** + * Returns an error status with the given info. + */ + IStatus error(String message, Throwable exception) { + return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, 0, message, exception); + } + + /** + * Returns the target profile id for the drop. If the drop is positioned on an + * IU, return its parent profile id. + */ + private String getProfileTarget(Object mouseTarget) { + IProfile profile = ProvUI.getAdapter(mouseTarget, IProfile.class); + if (profile != null) { + return profile.getProfileId(); + } + + if (mouseTarget instanceof InstalledIUElement) { + return ((InstalledIUElement) mouseTarget).getProfileId(); + } + return null; + } + + /** + * Returns an status indicating success. + */ + private IStatus ok() { + return new Status(IStatus.OK, ProvUIActivator.PLUGIN_ID, 0, null, null); + } + + /** + * Perform the drop. + * + * @see org.eclipse.swt.dnd.DropTargetListener#drop(org.eclipse.swt.dnd.DropTargetEvent) + */ + public boolean performDrop(final Object data) { + if (DEBUG) { + System.out.println("Perform drop on target: " + getCurrentTarget() + " with data: " + data); //$NON-NLS-1$//$NON-NLS-2$ + } + if (getCurrentTarget() == null || data == null) + return false; + + ISelection selection = LocalSelectionTransfer.getTransfer().getSelection(); + if (!(selection instanceof IStructuredSelection) || selection.isEmpty()) + return false; + + String profileId = getProfileTarget(getCurrentTarget()); + if (getCurrentOperation() == DND.DROP_COPY && profileId != null) { + final IStructuredSelection structuredSelection = (IStructuredSelection) selection; + ISelectionProvider selectionProvider = new ISelectionProvider() { + + /* (non-Javadoc) + * @see org.eclipse.jface.viewers.ISelectionProvider#addSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) + */ + public void addSelectionChangedListener(ISelectionChangedListener listener) { + // Ignore because the selection won't change + } + + /* (non-Javadoc) + * @see org.eclipse.jface.viewers.ISelectionProvider#getSelection() + */ + public ISelection getSelection() { + if (DEBUG) { + System.out.println("Selection was queried by action"); //$NON-NLS-1$ + System.out.println(structuredSelection.toString()); + } + return structuredSelection; + } + + /* (non-Javadoc) + * @see org.eclipse.jface.viewers.ISelectionProvider#removeSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) + */ + public void removeSelectionChangedListener(ISelectionChangedListener listener) { + // ignore because the selection is static + } + + /* (non-Javadoc) + * @see org.eclipse.jface.viewers.ISelectionProvider#setSelection(org.eclipse.jface.viewers.ISelection) + */ + public void setSelection(ISelection sel) { + throw new UnsupportedOperationException("This ISelectionProvider is static, and cannot be modified."); //$NON-NLS-1$ + } + }; + InstallAction action = new InstallAction(ui, selectionProvider, profileId); + if (DEBUG) + System.out.println("Running install action"); //$NON-NLS-1$ + action.run(); + return true; + } + return false; + } + + /** + * Validate whether the drop is valid for the target + */ + public boolean validateDrop(Object target, int dragOperation, TransferData transferType) { + + if (LocalSelectionTransfer.getTransfer().isSupportedType(transferType)) { + IStatus status = validateTarget(target, transferType); + if (DEBUG) { + System.out.println("Validate target: " + status); //$NON-NLS-1$ + } + return status.isOK(); + } + return false; + } + + /* + * Overridden to force a copy when the drag is valid. + * + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ViewerDropAdapter#dragEnter(org.eclipse.swt.dnd.DropTargetEvent) + */ + public void dragEnter(DropTargetEvent event) { + event.detail = DND.DROP_COPY; + super.dragEnter(event); + } + + /** + * Ensures that the drop target meets certain criteria + */ + private IStatus validateTarget(Object target, TransferData transferType) { + if (LocalSelectionTransfer.getTransfer().isSupportedType(transferType)) { + IInstallableUnit[] ius = getSelectedIUs(); + + if (ius.length == 0) { + return error(ProvUIMessages.ProvDropAdapter_NoIUsToDrop); + } + if (getProfileTarget(target) != null) { + return ok(); + } + return error(ProvUIMessages.ProvDropAdapter_InvalidDropTarget); + } + return error(ProvUIMessages.ProvDropAdapter_UnsupportedDropOperation); + } + + /** + * Returns the resource selection from the LocalSelectionTransfer. + * + * @return the resource selection from the LocalSelectionTransfer + */ + private IInstallableUnit[] getSelectedIUs() { + ISelection selection = LocalSelectionTransfer.getTransfer().getSelection(); + List ius = new ArrayList(); + + if (!(selection instanceof IStructuredSelection) || selection.isEmpty()) { + return null; + } + IStructuredSelection structuredSelection = (IStructuredSelection) selection; + + Iterator iter = structuredSelection.iterator(); + while (iter.hasNext()) { + IInstallableUnit iu = ProvUI.getAdapter(iter.next(), IInstallableUnit.class); + if (iu != null) { + ius.add(iu); + } + } + return ius.toArray(new IInstallableUnit[ius.size()]); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/ProvElementComparer.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/ProvElementComparer.java new file mode 100644 index 000000000..7eddb3b2c --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/ProvElementComparer.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.internal.p2.ui.viewers; + +import java.net.URI; +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.internal.p2.ui.model.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.jface.viewers.IElementComparer; + +public class ProvElementComparer implements IElementComparer { + + public boolean equals(Object a, Object b) { + // We treat category elements specially because this + // is one case where resolving down to an IU will lose identity + // differences. (category IU's with the same name and version number cannot be treated the same). + if (a instanceof CategoryElement || b instanceof CategoryElement) + return a.equals(b); + IInstallableUnit iu1 = getIU(a); + IInstallableUnit iu2 = getIU(b); + if (iu1 != null && iu2 != null) + return iu1.equals(iu2); + String p1 = getProfileId(a); + String p2 = getProfileId(b); + if (p1 != null && p2 != null) + return p1.equals(p2); + URI r1 = getRepositoryLocation(a); + URI r2 = getRepositoryLocation(b); + if (r1 != null && r2 != null) + return r1.equals(r2); + return a.equals(b); + } + + public int hashCode(Object element) { + if (element instanceof CategoryElement) + return element.hashCode(); + IInstallableUnit iu = getIU(element); + if (iu != null) + return iu.hashCode(); + String profileId = getProfileId(element); + if (profileId != null) + return profileId.hashCode(); + URI location = getRepositoryLocation(element); + if (location != null) + return location.hashCode(); + return element.hashCode(); + } + + private IInstallableUnit getIU(Object obj) { + return ProvUI.getAdapter(obj, IInstallableUnit.class); + } + + private String getProfileId(Object obj) { + if (obj instanceof ProfileElement) + return ((ProfileElement) obj).getLabel(obj); + IProfile profile = ProvUI.getAdapter(obj, IProfile.class); + if (profile == null) + return null; + return profile.getProfileId(); + } + + private URI getRepositoryLocation(Object obj) { + if (obj instanceof IRepositoryElement) + return ((IRepositoryElement) obj).getLocation(); + return null; + } + +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/ProvElementContentProvider.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/ProvElementContentProvider.java new file mode 100644 index 000000000..5e0c4bd9b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/ProvElementContentProvider.java @@ -0,0 +1,162 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.viewers; + +import java.util.ArrayList; +import java.util.Arrays; +import org.eclipse.core.runtime.*; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.internal.p2.ui.model.ProvElement; +import org.eclipse.jface.viewers.*; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.progress.*; + +/** + * Content provider that retrieves children of a ProvElement. + * + * @since 3.5 + * + */ +public class ProvElementContentProvider implements ITreeContentProvider { + + private Viewer viewer; + private Job fetchJob; + // family is used by test cases + Object fetchFamily = new Object(); + + /** + * + */ + public ProvElementContentProvider() { + // Default constructor + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) + */ + public Object[] getElements(final Object input) { + // Simple deferred fetch handling for table viewers + if (input instanceof IDeferredWorkbenchAdapter && viewer instanceof AbstractTableViewer) { + final Display display = viewer.getControl().getDisplay(); + final Object pending = new PendingUpdateAdapter(); + if (fetchJob != null) + fetchJob.cancel(); + fetchJob = new Job(ProvUIMessages.ProvElementContentProvider_FetchJobTitle) { + protected IStatus run(IProgressMonitor monitor) { + IDeferredWorkbenchAdapter parent = (IDeferredWorkbenchAdapter) input; + final ArrayList children = new ArrayList(); + parent.fetchDeferredChildren(parent, new IElementCollector() { + public void add(Object element, IProgressMonitor mon) { + if (mon.isCanceled()) + return; + children.add(element); + } + + public void add(Object[] elements, IProgressMonitor mon) { + if (mon.isCanceled()) + return; + children.addAll(Arrays.asList(elements)); + } + + public void done() { + // nothing special to do + } + + }, monitor); + display.asyncExec(new Runnable() { + public void run() { + AbstractTableViewer tableViewer = (AbstractTableViewer) viewer; + if (viewer == null || viewer.getControl().isDisposed()) + return; + tableViewer.getControl().setRedraw(false); + tableViewer.remove(pending); + tableViewer.add(children.toArray()); + finishedFetchingElements(input); + tableViewer.getControl().setRedraw(true); + } + }); + return Status.OK_STATUS; + } + + public boolean belongsTo(Object family) { + return family == fetchFamily; + } + + }; + fetchJob.schedule(); + return new Object[] {pending}; + } + Object[] elements = getChildren(input); + finishedFetchingElements(input); + return elements; + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object) + */ + public Object getParent(Object child) { + if (child instanceof ProvElement) { + return ((ProvElement) child).getParent(child); + } + return null; + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object) + */ + public boolean hasChildren(Object element) { + if (element instanceof ProvElement) + return ((ProvElement) element).hasChildren(element); + return false; + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object) + */ + public Object[] getChildren(final Object parent) { + if (parent instanceof ProvElement) { + return ((ProvElement) parent).getChildren(parent); + } + return new Object[0]; + } + + /* (non-Javadoc) + * @see org.eclipse.jface.viewers.IContentProvider#dispose() + */ + public void dispose() { + viewer = null; + if (fetchJob != null) { + fetchJob.cancel(); + fetchJob = null; + } + } + + /* (non-Javadoc) + * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object) + */ + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + this.viewer = viewer; + if (fetchJob != null) { + fetchJob.cancel(); + fetchJob = null; + } + } + + protected void finishedFetchingElements(Object parent) { + // do nothing + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/ProvElementLabelProvider.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/ProvElementLabelProvider.java new file mode 100644 index 000000000..e82f5f841 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/ProvElementLabelProvider.java @@ -0,0 +1,146 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.viewers; + +import org.eclipse.core.runtime.URIUtil; +import org.eclipse.equinox.internal.p2.metadata.IRequiredCapability; +import org.eclipse.equinox.internal.p2.ui.ProvUI; +import org.eclipse.equinox.internal.p2.ui.ProvUIImages; +import org.eclipse.equinox.internal.p2.ui.model.*; +import org.eclipse.equinox.p2.engine.IProfile; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.jface.viewers.ITableLabelProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.swt.graphics.Image; +import org.eclipse.ui.ISharedImages; +import org.eclipse.ui.PlatformUI; + +/** + * Label provider for provisioning elements. Some provisioning objects are + * wrapped by ProvElements and some are not. This is the most generic of the + * provisioning label providers. A two-column format for elements is + * supported, with the content of the columns dependent on the type of object. + * + * @since 3.4 + */ +public class ProvElementLabelProvider extends LabelProvider implements ITableLabelProvider { + + public String getText(Object obj) { + if (obj instanceof ProvElement) { + return ((ProvElement) obj).getLabel(obj); + } + if (obj instanceof IProfile) { + return ((IProfile) obj).getProfileId(); + } + if (obj instanceof IInstallableUnit) { + IInstallableUnit iu = (IInstallableUnit) obj; + return iu.getId(); + } + if (obj instanceof IRepository) { + String name = ((IRepository) obj).getName(); + if (name != null && name.length() > 0) { + return name; + } + return URIUtil.toUnencodedString(((IRepository) obj).getLocation()); + } + if (obj instanceof IRepositoryElement) { + String name = ((IRepositoryElement) obj).getName(); + if (name != null && name.length() > 0) { + return name; + } + return URIUtil.toUnencodedString(((IRepositoryElement) obj).getLocation()); + } + if (obj instanceof IArtifactKey) { + IArtifactKey key = (IArtifactKey) obj; + return key.getId() + " [" + key.getClassifier() + "]"; //$NON-NLS-1$//$NON-NLS-2$ + } + if (obj instanceof IProcessingStepDescriptor) { + IProcessingStepDescriptor descriptor = (IProcessingStepDescriptor) obj; + return descriptor.getProcessorId(); + } + if (obj instanceof IRequiredCapability) { + return ((IRequiredCapability) obj).getName(); + } + return obj.toString(); + } + + public Image getImage(Object obj) { + if (obj instanceof ProvElement) { + return ((ProvElement) obj).getImage(obj); + } + if (obj instanceof IProfile) { + return ProvUIImages.getImage(ProvUIImages.IMG_PROFILE); + } + if (obj instanceof IInstallableUnit) { + return ProvUIImages.getImage(ProvUIImages.IMG_IU); + } + if (obj instanceof IArtifactRepository) { + return ProvUIImages.getImage(ProvUIImages.IMG_ARTIFACT_REPOSITORY); + } + if (obj instanceof IMetadataRepository) { + return ProvUIImages.getImage(ProvUIImages.IMG_METADATA_REPOSITORY); + } + if (obj instanceof IArtifactKey) { + return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE); + } + if (obj instanceof IRequirement) { + return ProvUIImages.getImage(ProvUIImages.IMG_IU); + } + return null; + } + + public Image getColumnImage(Object element, int index) { + if (index == 0) { + return getImage(element); + } + return null; + } + + public String getColumnText(Object element, int columnIndex) { + + switch (columnIndex) { + case 0 : + return getText(element); + case 1 : + if (element instanceof IProfile) { + return ((IProfile) element).getProperty(IProfile.PROP_NAME); + } + if (element instanceof IIUElement) { + if (((IIUElement) element).shouldShowVersion()) + return ((IIUElement) element).getIU().getVersion().toString(); + } + IInstallableUnit iu = ProvUI.getAdapter(element, IInstallableUnit.class); + if (iu != null) { + return iu.getVersion().toString(); + } + if (element instanceof IRepository) { + return URIUtil.toUnencodedString(((IRepository) element).getLocation()); + } + if (element instanceof IRepositoryElement) { + return URIUtil.toUnencodedString(((IRepositoryElement) element).getLocation()); + } + if (element instanceof IArtifactKey) { + IArtifactKey key = (IArtifactKey) element; + return key.getVersion().toString(); + } + if (element instanceof IRequiredCapability) { + return ((IRequiredCapability) element).getRange().getMaximum().toString(); + } + + } + return null; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/RepositoryContentProvider.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/RepositoryContentProvider.java new file mode 100644 index 000000000..1aa1088ea --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/RepositoryContentProvider.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.viewers; + +import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; + +/** + * Content provider for provisioning repositories. The repositories are the + * elements and the repository children are retrieved asynchronously + * using the IDeferredWorkbenchAdapter mechanism. + * + * @since 3.4 + * + */ +public class RepositoryContentProvider extends DeferredQueryContentProvider { + + public Object[] getChildren(final Object parent) { + Object[] children = super.getChildren(parent); + if (children != null) + return children; + if (parent instanceof IArtifactDescriptor) { + return ((IArtifactDescriptor) parent).getProcessingSteps(); + } + return null; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/RepositoryDetailsLabelProvider.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/RepositoryDetailsLabelProvider.java index 6537fabe6..6247d7db2 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/RepositoryDetailsLabelProvider.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/RepositoryDetailsLabelProvider.java @@ -12,14 +12,12 @@ package org.eclipse.equinox.internal.p2.ui.viewers; import org.eclipse.core.runtime.URIUtil; +import org.eclipse.equinox.internal.p2.ui.ProvUIImages; import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement; -import org.eclipse.equinox.internal.p2.ui.model.ProvElement; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IRepositoryElement; +import org.eclipse.equinox.internal.p2.ui.model.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.osgi.util.TextProcessor; @@ -60,25 +58,25 @@ public class RepositoryDetailsLabelProvider extends LabelProvider implements ITa switch (columnIndex) { case COL_NAME : - if (element instanceof IRepositoryElement) { - String name = ((IRepositoryElement) element).getName(); + if (element instanceof IRepositoryElement) { + String name = ((IRepositoryElement) element).getName(); if (name != null) { return name; } } - if (element instanceof IRepository) { - String name = ((IRepository) element).getName(); + if (element instanceof IRepository) { + String name = ((IRepository) element).getName(); if (name != null) { return name; } } return ""; //$NON-NLS-1$ case COL_LOCATION : - if (element instanceof IRepository) { - return TextProcessor.process(URIUtil.toUnencodedString(((IRepository) element).getLocation())); + if (element instanceof IRepository) { + return TextProcessor.process(URIUtil.toUnencodedString(((IRepository) element).getLocation())); } - if (element instanceof IRepositoryElement) { - return TextProcessor.process(URIUtil.toUnencodedString(((IRepositoryElement) element).getLocation())); + if (element instanceof IRepositoryElement) { + return TextProcessor.process(URIUtil.toUnencodedString(((IRepositoryElement) element).getLocation())); } break; case COL_ENABLEMENT : diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/StructuredViewerProvisioningListener.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/StructuredViewerProvisioningListener.java new file mode 100644 index 000000000..a907f604e --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/viewers/StructuredViewerProvisioningListener.java @@ -0,0 +1,173 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.internal.p2.ui.viewers; + +import org.eclipse.equinox.internal.p2.ui.ProvUIProvisioningListener; +import org.eclipse.equinox.internal.p2.ui.model.ProfileElement; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.jface.viewers.StructuredViewer; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.PlatformUI; + +/** + * ProvisioningListener which updates a structured viewer based on + * provisioning changes. Provides default behavior which refreshes particular + * model elements or the entire viewer based on the nature of the change and the + * changes that the client is interested in. Subclasses typically only need + * override when there is additional, specialized behavior required. + * + * @since 3.4 + */ +public class StructuredViewerProvisioningListener extends ProvUIProvisioningListener { + + StructuredViewer viewer; + Display display; + + public StructuredViewerProvisioningListener(StructuredViewer viewer, int eventTypes) { + super(eventTypes); + this.viewer = viewer; + this.display = viewer.getControl().getDisplay(); + } + + /** + * A repository has been added. The default behavior is to + * refresh the viewer. Subclasses may override. May be called + * from a non-UI thread. + * + * @param event the RepositoryEvent describing the details + */ + protected void repositoryAdded(RepositoryEvent event) { + safeRefresh(); + } + + /** + * A repository has been removed. The default behavior is to + * refresh the viewer. Subclasses may override. May be called + * from a non-UI thread. + * + * @param event the RepositoryEvent describing the details + */ + protected void repositoryRemoved(RepositoryEvent event) { + safeRefresh(); + } + + /** + * A repository has been discovered. Subclasses may override. May be called + * from a non-UI thread. + * + * @param event the RepositoryEvent describing the details + */ + protected void repositoryDiscovered(RepositoryEvent event) { + // Do nothing for now + } + + /** + * A repository has changed. Subclasses may override. May be called + * from a non-UI thread. + * + * @param event the RepositoryEvent describing the details + */ + protected void repositoryChanged(RepositoryEvent event) { + // Do nothing for now. When this event is actually used in + // the core, we may want to refresh particular elements the way + // we currently refresh a profile element. + } + + /** + * The specified profile has changed. The default behavior is to refresh the viewer + * with a profile element of the matching id. Subclasses may override. May be called + * from a non-UI thread. + * + * @param profileId the id of the profile that changed. + */ + protected void profileChanged(final String profileId) { + display.asyncExec(new Runnable() { + public void run() { + if (isClosing()) + return; + // We want to refresh the affected profile, so we + // construct a profile element on this profile. + ProfileElement element = new ProfileElement(null, profileId); + viewer.refresh(element); + } + }); + } + + /** + * The specified profile has been added. The default behavior is to fully + * refresh the associated viewer. Subclasses may override. May be called + * from a non-UI thread. + * + * @param profileId the id of the profile that has been added. + */ + protected void profileAdded(final String profileId) { + safeRefresh(); + } + + /** + * The specified profile has been removed. The default behavior is to fully + * refresh the associated viewer. Subclasses may override. May be called + * from a non-UI thread. + * + * @param profileId the id of the profile that has been removed. + */ + protected void profileRemoved(final String profileId) { + safeRefresh(); + } + + protected void safeRefresh() { + if (Display.getCurrent() != null) { + refreshViewer(); + return; + } + + display.asyncExec(new Runnable() { + public void run() { + if (isClosing()) + return; + refreshViewer(); + } + }); + } + + protected void refreshAll() { + safeRefresh(); + } + + /** + * Refresh the entire structure of the viewer. Subclasses may + * override to ensure that any caching done in content providers or + * model elements is refreshed before the viewer is refreshed. This will + * always be called from the UI thread. + */ + protected void refreshViewer() { + viewer.refresh(); + } + + /** + * Return whether the viewer is closing or shutting down. + * This method should be used in async execs to ensure that + * the viewer is still alive. + * @return a boolean indicating whether the viewer is closing + */ + protected boolean isClosing() { + IWorkbench workbench = PlatformUI.getWorkbench(); + if (workbench.isClosing()) + return true; + + if (viewer.getControl().isDisposed()) + return true; + + return false; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ElementQueryDescriptor.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ElementQueryDescriptor.java deleted file mode 100644 index 35d713506..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ElementQueryDescriptor.java +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * EclipseSource - ongoing development - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui; - -import java.util.Collection; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; - -/** - * ElementQueryDescriptor represents everything needed to run a query, including - * the object to be queried, the query to use, and the query result. It can optionally - * wrap the query results in a UI element. - * - * @since 3.4 - */ -public class ElementQueryDescriptor { - - private Query query; - private Collector collector; - private IQueryable queryable; - private ElementWrapper wrapper; - - /** - * Creates an ElementQueryDescriptor to represent a Query, its collector the queryable - * on which it will run. - */ - public ElementQueryDescriptor(IQueryable queryable, Query query, Collector collector) { - this(queryable, query, collector, null); - } - - /** - * Creates an ElementQueryDescriptor to represent a Query, its collector the queryable - * on which it will run, and the transformer used to transform the results. - */ - public ElementQueryDescriptor(IQueryable queryable, Query query, Collector collector, ElementWrapper wrapper) { - this.query = query; - this.collector = collector; - this.queryable = queryable; - this.wrapper = wrapper; - } - - /** - * Performs the query returning a collection of results. - * @param monitor - */ - public Collection performQuery(IProgressMonitor monitor) { - Collector results = this.collector; - // If the query is completely described, perform it - if (query != null && collector != null && queryable != null) - results = this.queryable.query(this.query, this.collector, monitor); - else if (results == null) - results = new Collector(); - // Let the wrapper analyze the results, even if we didn't perform the query. - // This allows the wrapper to modify the results with explanations. - if (wrapper != null) - return wrapper.getElements(results); - return results.toCollection(); - } - - public boolean hasCollector() { - return this.collector != null; - } - - public boolean hasQueryable() { - return this.queryable != null; - } - - public boolean hasQuery() { - return this.query != null; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ElementWrapper.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ElementWrapper.java deleted file mode 100644 index 57c1d223d..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ElementWrapper.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 EclipseSource and others. All rights reserved. This -* program and the accompanying materials are made available under the terms of -* the Eclipse Public License v1.0 which accompanies this distribution, and is -* available at http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* EclipseSource - initial API and implementation -* IBM Corporation - ongoing development -******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui; - -import java.util.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; - -/** - * Wraps query results inside corresponding UI elements - */ -public abstract class ElementWrapper { - - private Collection collection = null; - - /** - * Transforms a collector returned by a query to a collection - * of UI elements - */ - public Collection getElements(Collector collector) { - collection = new ArrayList(collector.size()); - Iterator iter = collector.iterator(); - while (iter.hasNext()) { - Object o = iter.next(); - if (shouldWrap(o)) - collection.add(wrap(o)); - } - return getCollection(); - } - - /** - * Gets the collection where the elements are being stored. - */ - protected Collection getCollection() { - return collection == null ? Collections.EMPTY_LIST : collection; - } - - /** - * Determines if this object should be accepted and wrapped - * by a UI element. - */ - protected boolean shouldWrap(Object o) { - return true; - } - - /** - * Wraps a single element of the query result inside a UI element. - */ - protected abstract Object wrap(Object item); -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/IProvHelpContextIds.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/IProvHelpContextIds.java deleted file mode 100644 index 3e138d402..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/IProvHelpContextIds.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui; - -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; - -/** - * Help context ids for the P2 UI - *

    - * This interface contains constants only; it is not intended to be implemented - * or extended. - *

    - * @since 3.4 - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - */ - -public interface IProvHelpContextIds { - public static final String PREFIX = ProvUIActivator.PLUGIN_ID + "."; //$NON-NLS-1$ - - public static final String REVERT_CONFIGURATION_WIZARD = PREFIX + "revert_configuration_wizard_context"; //$NON-NLS-1$ - - public static final String UNINSTALL_WIZARD = PREFIX + "uinstall_wizard_context"; //$NON-NLS-1$ - - public static final String UPDATE_WIZARD = PREFIX + "update_wizard_context"; //$NON-NLS-1$ - - public static final String ADD_REPOSITORY_DIALOG = PREFIX + "add_repository_dialog_context"; //$NON-NLS-1$ - - public static final String INSTALL_WIZARD = PREFIX + "install_wizard_context"; //$NON-NLS-1$ - - public static final String REPOSITORY_MANIPULATION_DIALOG = PREFIX + "repository_manipulation_dialog_context"; //$NON-NLS-1$ - - public static final String INSTALLED_SOFTWARE = PREFIX + "installed_software_context"; //$NON-NLS-1$ - - public static final String AVAILABLE_SOFTWARE = PREFIX + "available_software_context"; //$NON-NLS-1$ - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/IStatusCodes.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/IStatusCodes.java deleted file mode 100644 index d31aaf01f..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/IStatusCodes.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui; - -/** - * IStatusCodes defines codes for common status conditions in the - * p2 UI. - * - * This interface is not intended to be implemented - * - * @since 3.4 - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface IStatusCodes { - - //UI status codes [10000-10999] - note these cannot conflict with the core codes - //in ProvisionException or we'll see strange results. - - public static final int NOTHING_TO_UPDATE = 10000; - - // Status codes associated with profile change request or plans being altered from the original intent - public static final int PROFILE_CHANGE_ALTERED = 10001; - public static final int IU_REQUEST_ALTERED = 10002; - public static final int ALTERED_IMPLIED_UPDATE = 10003; - public static final int ALTERED_IGNORED_IMPLIED_DOWNGRADE = 10004; - public static final int ALTERED_IGNORED_ALREADY_INSTALLED = 10005; - public static final int ALTERED_PARTIAL_INSTALL = 10006; - public static final int ALTERED_PARTIAL_UNINSTALL = 10007; - public static final int ALTERED_SIDE_EFFECT_UPDATE = 10008; - public static final int ALTERED_SIDE_EFFECT_REMOVE = 10009; - public static final int ALTERED_SIDE_EFFECT_INSTALL = 10010; - public static final int ALTERED_IGNORED_INSTALL_REQUEST = 10011; - public static final int ALTERED_IGNORED_UNINSTALL_REQUEST = 10012; - public static final int ALTERED_IGNORED_IMPLIED_UPDATE = 10013; - - // Status codes associated with inability to perform an operation - public static final int UNEXPECTED_NOTHING_TO_DO = 10050; - public static final int EXPECTED_NOTHING_TO_DO = 10051; - public static final int OPERATION_ALREADY_IN_PROGRESS = 10052; -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/IUPropertyUtils.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/IUPropertyUtils.java deleted file mode 100644 index 9007b3ee7..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/IUPropertyUtils.java +++ /dev/null @@ -1,241 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * EclipseSource - ongoing development - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui; - -import java.lang.ref.SoftReference; -import java.util.*; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.metadata.InstallableUnit; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IUPropertyQuery; - -public class IUPropertyUtils { - - // TODO: these constants should come from API, eg. IInstallableUnit or ??? - static final Locale DEFAULT_LOCALE = new Locale("df", "LT"); //$NON-NLS-1$//$NON-NLS-2$ - static final String NAMESPACE_IU_LOCALIZATION = "org.eclipse.equinox.p2.localization"; //$NON-NLS-1$ - - // Cache the IU fragments that provide localizations for a given locale. - // map: locale => soft reference to a collector - private static Map LocaleCollectorCache = new HashMap(2); - - // Get the license in the default locale. - public static ILicense getLicense(IInstallableUnit iu) { - return getLicense(iu, getCurrentLocale()); - } - - // Get the copyright in the default locale. - public static ICopyright getCopyright(IInstallableUnit iu) { - return getCopyright(iu, getCurrentLocale()); - } - - // Get a property in the default locale - public static String getIUProperty(IInstallableUnit iu, String propertyKey) { - return getIUProperty(iu, propertyKey, getCurrentLocale()); - } - - public static ILicense getLicense(IInstallableUnit iu, Locale locale) { - ILicense license = iu.getLicense(); - String body = (license != null ? license.getBody() : null); - if (body == null || body.length() <= 1 || body.charAt(0) != '%') - return license; - final String actualKey = body.substring(1); // Strip off the % - body = getLocalizedIUProperty(iu, actualKey, locale); - return MetadataFactory.createLicense(license.getLocation(), body); - } - - public static ICopyright getCopyright(IInstallableUnit iu, Locale locale) { - ICopyright copyright = iu.getCopyright(); - String body = (copyright != null ? copyright.getBody() : null); - if (body == null || body.length() <= 1 || body.charAt(0) != '%') - return copyright; - final String actualKey = body.substring(1); // Strip off the % - body = getLocalizedIUProperty(iu, actualKey, locale); - return MetadataFactory.createCopyright(copyright.getLocation(), body); - } - - public static String getIUProperty(IInstallableUnit iu, String propertyKey, Locale locale) { - String value = iu.getProperty(propertyKey); - if (value == null || value.length() <= 1 || value.charAt(0) != '%') - return value; - // else have a localizable property - final String actualKey = value.substring(1); // Strip off the % - return getLocalizedIUProperty(iu, actualKey, locale); - } - - private static String getLocalizedIUProperty(IInstallableUnit iu, String actualKey, Locale locale) { - String localizedKey = makeLocalizedKey(actualKey, locale.toString()); - String localizedValue = null; - - //first check for a cached localized value - if (iu instanceof InstallableUnit) - localizedValue = ((InstallableUnit) iu).getLocalizedProperty(localizedKey); - //next check if the localized value is stored in the same IU (common case) - if (localizedValue == null) - localizedValue = iu.getProperty(localizedKey); - if (localizedValue != null) - return localizedValue; - - final List locales = buildLocaleVariants(locale); - final IInstallableUnit theUnit = iu; - - Collector localizationFragments = getLocalizationFragments(locale, locales); - - Collector hostLocalizationCollector = new Collector() { - public boolean accept(Object object) { - boolean haveHost = false; - if (object instanceof IInstallableUnitFragment) { - IInstallableUnitFragment fragment = (IInstallableUnitFragment) object; - IRequiredCapability[] hosts = fragment.getHost(); - for (int i = 0; i < hosts.length; i++) { - IRequiredCapability nextHost = hosts[i]; - if (IInstallableUnit.NAMESPACE_IU_ID.equals(nextHost.getNamespace()) && // - theUnit.getId().equals(nextHost.getName()) && // - nextHost.getRange() != null && // - nextHost.getRange().isIncluded(theUnit.getVersion())) { - haveHost = true; - break; - } - } - } - return (haveHost ? super.accept(object) : true); - } - }; - - IUPropertyQuery iuQuery = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_FRAGMENT, "true"); //$NON-NLS-1$ - Collector collected = iuQuery.perform(localizationFragments.iterator(), hostLocalizationCollector); - - if (!collected.isEmpty()) { - String translation = null; - for (Iterator iter = collected.iterator(); iter.hasNext() && translation == null;) { - IInstallableUnit localizationIU = (IInstallableUnit) iter.next(); - for (Iterator jter = locales.iterator(); jter.hasNext();) { - String localeKey = makeLocalizedKey(actualKey, (String) jter.next()); - translation = localizationIU.getProperty(localeKey); - if (translation != null) - return cacheResult(iu, localizedKey, translation); - } - } - } - - for (Iterator iter = locales.iterator(); iter.hasNext();) { - String nextLocale = (String) iter.next(); - String localeKey = makeLocalizedKey(actualKey, nextLocale); - String nextValue = iu.getProperty(localeKey); - if (nextValue != null) - return cacheResult(iu, localizedKey, nextValue); - } - - return cacheResult(iu, localizedKey, actualKey); - } - - /** - * Cache the translated property value to optimize future retrieval of the same value. - * Currently we just cache on the installable unit object in memory. In future - * we should push support for localized property retrieval into IInstallableUnit - * so we aren't required to reach around the API here. - */ - private static String cacheResult(IInstallableUnit iu, String localizedKey, String localizedValue) { - if (iu instanceof InstallableUnit) - ((InstallableUnit) iu).setLocalizedProperty(localizedKey, localizedValue); - return localizedValue; - } - - /** - * Collects the installable unit fragments that contain locale data for the given locales. - */ - private static synchronized Collector getLocalizationFragments(Locale locale, List localeVariants) { - SoftReference collectorRef = (SoftReference) LocaleCollectorCache.get(locale); - if (collectorRef != null) { - Collector cached = (Collector) collectorRef.get(); - if (cached != null) - return cached; - } - - final List locales = localeVariants; - - Collector localeFragmentCollector = new Collector() { - public boolean accept(Object object) { - boolean haveLocale = false; - if (object instanceof IInstallableUnitFragment) { - IInstallableUnitFragment fragment = (IInstallableUnitFragment) object; - IProvidedCapability[] provides = fragment.getProvidedCapabilities(); - for (int j = 0; j < provides.length && !haveLocale; j++) { - IProvidedCapability nextProvide = provides[j]; - if (NAMESPACE_IU_LOCALIZATION.equals(nextProvide.getNamespace())) { - String providedLocale = nextProvide.getName(); - if (providedLocale != null) { - for (Iterator iter = locales.iterator(); iter.hasNext();) { - if (providedLocale.equals(iter.next())) { - haveLocale = true; - break; - } - } - } - } - } - } - return (haveLocale ? super.accept(object) : true); - } - }; - - //Due to performance problems we restrict locale lookup to the current profile (see bug 233958) - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName()); - if (profileRegistry == null) { - LogHelper.log(new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, "Profile registry unavailable. Default language will be used.", new RuntimeException())); //$NON-NLS-1$ - return new Collector(); - } - IProfile profile = profileRegistry.getProfile(IProfileRegistry.SELF); - if (profile == null) { - LogHelper.log(new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, "Profile unavailable. Default language will be used.", new RuntimeException())); //$NON-NLS-1$ - return new Collector(); - } - IUPropertyQuery iuQuery = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_FRAGMENT, "true"); //$NON-NLS-1$ - Collector collected = profile.query(iuQuery, localeFragmentCollector, null); - LocaleCollectorCache.put(locale, new SoftReference(collected)); - return collected; - } - - /** - */ - private static List buildLocaleVariants(Locale locale) { - String nl = locale.toString(); - ArrayList result = new ArrayList(4); - int lastSeparator; - while (true) { - result.add(nl); - lastSeparator = nl.lastIndexOf('_'); - if (lastSeparator == -1) - break; - nl = nl.substring(0, lastSeparator); - } - // Add the default locale (most general) - result.add(DEFAULT_LOCALE.toString()); - return result; - } - - private static String makeLocalizedKey(String actualKey, String localeImage) { - return localeImage + '.' + actualKey; - } - - private static Locale getCurrentLocale() { - return Locale.getDefault(); - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProfileFactory.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProfileFactory.java deleted file mode 100644 index c39585a9c..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProfileFactory.java +++ /dev/null @@ -1,81 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui; - -import java.util.HashMap; -import java.util.Map; -import org.eclipse.core.runtime.Platform; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.osgi.service.environment.EnvironmentInfo; - -/** - * Factory class that can create a new profile with the correct - * default values. - * - * @since 3.4 - * - */ -public class ProfileFactory { - - static private String FLAVOR_DEFAULT = "tooling"; //$NON-NLS-1$ - static private String EMPTY = ""; //$NON-NLS-1$ - static private EnvironmentInfo info; - - public static IProfile makeProfile(String profileId) { - Map profileProperties = new HashMap(); - profileProperties.put(IProfile.PROP_INSTALL_FOLDER, getDefaultLocation()); - profileProperties.put(IProfile.PROP_FLAVOR, getDefaultFlavor()); - profileProperties.put(IProfile.PROP_ENVIRONMENTS, getDefaultEnvironments()); - profileProperties.put(IProfile.PROP_NL, getDefaultNL()); - - try { - return ProvisioningUtil.addProfile(profileId, profileProperties, null); - } catch (ProvisionException e) { - // log - } - return null; - } - - public static String getDefaultLocation() { - return Platform.getUserLocation().getURL().getPath(); - } - - public static String getDefaultFlavor() { - return FLAVOR_DEFAULT; - } - - private static EnvironmentInfo getEnvironmentInfo() { - if (info == null) { - info = (EnvironmentInfo) ServiceHelper.getService(ProvUIActivator.getContext(), EnvironmentInfo.class.getName()); - } - return info; - } - - public static String getDefaultNL() { - if (getEnvironmentInfo() != null) { - return info.getNL(); - } - return EMPTY; - } - - public static String getDefaultEnvironments() { - if (getEnvironmentInfo() != null) { - return "osgi.os=" //$NON-NLS-1$ - + info.getOS() + ",osgi.ws=" + info.getWS() //$NON-NLS-1$ - + ",osgi.arch=" + info.getOSArch(); //$NON-NLS-1$ - } - return EMPTY; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvUI.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvUI.java deleted file mode 100644 index 3b9f8f4b6..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvUI.java +++ /dev/null @@ -1,319 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui; - -import java.net.URI; -import java.util.*; -import org.eclipse.core.commands.*; -import org.eclipse.core.commands.common.NotDefinedException; -import org.eclipse.core.commands.operations.ObjectUndoContext; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.dialogs.ILayoutConstants; -import org.eclipse.equinox.internal.p2.ui.dialogs.RepositoryNameAndLocationDialog; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.IUColumnConfig; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.window.Window; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.*; -import org.eclipse.ui.commands.ICommandService; -import org.eclipse.ui.handlers.IHandlerService; -import org.eclipse.ui.statushandlers.StatusManager; - -/** - * Generic provisioning UI utility and policy methods. - * - * @since 3.4 - */ -public class ProvUI { - - // Public constants for common command and tooltip names - public static final String INSTALL_COMMAND_LABEL = ProvUIMessages.InstallIUCommandLabel; - public static final String INSTALL_COMMAND_TOOLTIP = ProvUIMessages.InstallIUCommandTooltip; - public static final String UNINSTALL_COMMAND_LABEL = ProvUIMessages.UninstallIUCommandLabel; - public static final String UNINSTALL_COMMAND_TOOLTIP = ProvUIMessages.UninstallIUCommandTooltip; - public static final String UPDATE_COMMAND_LABEL = ProvUIMessages.UpdateIUCommandLabel; - public static final String UPDATE_COMMAND_TOOLTIP = ProvUIMessages.UpdateIUCommandTooltip; - public static final String REVERT_COMMAND_LABEL = ProvUIMessages.RevertIUCommandLabel; - public static final String REVERT_COMMAND_TOOLTIP = ProvUIMessages.RevertIUCommandTooltip; - - static ObjectUndoContext provisioningUndoContext; - - /** - * List of repositories that have already been reported to the user as not found. - */ - private static final List reposNotFound = Collections.synchronizedList(new ArrayList()); - - // These values rely on the command markup in org.eclipse.ui.ide that defines the update commands - private static final String UPDATE_MANAGER_FIND_AND_INSTALL = "org.eclipse.ui.update.findAndInstallUpdates"; //$NON-NLS-1$ - private static final String UPDATE_MANAGER_MANAGE_CONFIGURATION = "org.eclipse.ui.update.manageConfiguration"; //$NON-NLS-1$ - // This value relies on the command markup in org.eclipse.ui - private static final String INSTALLATION_DIALOG = "org.eclipse.ui.help.installationDialog"; //$NON-NLS-1$ - - public static IStatus handleException(Throwable t, String message, int style) { - if (message == null && t != null) { - message = t.getMessage(); - } - IStatus status = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, 0, message, t); - StatusManager.getManager().handle(status, style); - return status; - } - - public static void reportLoadFailure(final URI location, IStatus status, int style, final RepositoryManipulator repoManipulator) { - int code = status.getCode(); - // Special handling when the location is bad (not found, etc.) vs. a failure - // associated with a known repo. - if (code == ProvisionException.REPOSITORY_NOT_FOUND || code == ProvisionException.REPOSITORY_INVALID_LOCATION) { - if (!hasNotFoundStatusBeenReported(location)) { - PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { - public void run() { - IWorkbench workbench = PlatformUI.getWorkbench(); - if (workbench.isClosing()) - return; - Shell shell = ProvUI.getDefaultParentShell(); - if (MessageDialog.openQuestion(shell, ProvUIMessages.ProvUI_LoadErrorTitle, NLS.bind(ProvUIMessages.ProvUI_PromptForSiteEdit, URIUtil.toUnencodedString(location)))) { - RepositoryNameAndLocationDialog dialog = new RepositoryNameAndLocationDialog(shell, Policy.getDefault()) { - protected String getInitialLocationText() { - return URIUtil.toUnencodedString(location); - } - - protected String getInitialNameText() { - String nickname = null; - try { - nickname = ProvisioningUtil.getMetadataRepositoryProperty(location, IRepository.PROP_NICKNAME); - } catch (ProvisionException e) { - // nickname remains null - } - return nickname == null ? "" : nickname; //$NON-NLS-1$ - } - }; - int ret = dialog.open(); - if (ret == Window.OK) { - URI correctedLocation = dialog.getLocation(); - if (correctedLocation != null) { - ProvUI.startBatchOperation(); - try { - RepositoryManipulator repoMan = repoManipulator; - if (repoManipulator == null) - repoMan = Policy.getDefault().getRepositoryManipulator(); - ProvisioningOperation op = repoMan.getRemoveOperation(new URI[] {location}); - op.execute(null); - ProvUI.endBatchOperation(false); - op = repoMan.getAddOperation(correctedLocation); - op.execute(null); - String nickname = dialog.getName(); - if (nickname != null && nickname.length() > 0) - ProvisioningUtil.setMetadataRepositoryProperty(correctedLocation, IRepository.PROP_NICKNAME, nickname); - } catch (ProvisionException e) { - ProvUI.handleException(e, null, StatusManager.SHOW | StatusManager.LOG); - ProvUI.endBatchOperation(true); - } - } - } - } - } - }); - reposNotFound.add(location); - } - } else { - reportStatus(status, style); - } - } - - // This assumes that callers already checked whether it *should* - // be reported so that we don't need to loop through the list - // when the caller just has done so in order to know whether to report. - public static void notFoundStatusReported(URI location) { - reposNotFound.add(location); - } - - // We don't check for things like case variants or end slash variants - // because we know that the repository managers already did this. - public static boolean hasNotFoundStatusBeenReported(URI location) { - return reposNotFound.contains(location); - } - - public static void clearRepositoriesNotFound() { - reposNotFound.clear(); - } - - public static void clearRepositoryNotFound(URI location) { - reposNotFound.remove(location); - } - - public static void reportStatus(IStatus status, int style) { - // workaround for - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=211933 - // Note we'd rather have a proper looking dialog than get the - // blocking right. - if ((style & StatusManager.BLOCK) == StatusManager.BLOCK || (style & StatusManager.SHOW) == StatusManager.SHOW) { - if (status.getSeverity() == IStatus.INFO) { - MessageDialog.openInformation(ProvUI.getDefaultParentShell(), ProvUIMessages.ProvUI_InformationTitle, status.getMessage()); - // unset the dialog bits - style = style & ~StatusManager.BLOCK; - style = style & ~StatusManager.SHOW; - // unset logging for statuses that should never be logged. - // Ideally the caller would do this but this bug keeps coming back. - // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=274074 - if (status.getCode() == IStatusCodes.NOTHING_TO_UPDATE) - style = 0; - } else if (status.getSeverity() == IStatus.WARNING) { - MessageDialog.openWarning(ProvUI.getDefaultParentShell(), ProvUIMessages.ProvUI_WarningTitle, status.getMessage()); - // unset the dialog bits - style = style & ~StatusManager.BLOCK; - style = style & ~StatusManager.SHOW; - } - } - if (style != 0) - StatusManager.getManager().handle(status, style); - } - - public static IUColumnConfig[] getIUColumnConfig() { - return new IUColumnConfig[] {new IUColumnConfig(ProvUIMessages.ProvUI_NameColumnTitle, IUColumnConfig.COLUMN_NAME, ILayoutConstants.DEFAULT_PRIMARY_COLUMN_WIDTH), new IUColumnConfig(ProvUIMessages.ProvUI_VersionColumnTitle, IUColumnConfig.COLUMN_VERSION, ILayoutConstants.DEFAULT_COLUMN_WIDTH)}; - - } - - public static Object getAdapter(Object object, Class adapterType) { - if (object == null) - return null; - if (adapterType.isInstance(object)) - return object; - if (object instanceof IAdaptable) - return ((IAdaptable) object).getAdapter(adapterType); - return null; - } - - /** - * Returns a shell that is appropriate to use as the parent - * for a modal dialog. This returns the existing modal dialog, if any, - * or a workbench window if no modal dialogs open. Returns null - * if there is no appropriate default parent. - * - * This method is copied from ProgressManagerUtil#getDefaultParent() - */ - public static Shell getDefaultParentShell() { - IWorkbench workbench = PlatformUI.getWorkbench(); - - //look first for the topmost modal shell - Shell shell = getDefaultParentShell(workbench.getDisplay().getShells()); - - if (shell != null) { - return shell; - } - - //try the active workbench window - IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); - if (window != null) - return window.getShell(); - IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows(); - if (windows.length > 0) - return windows[0].getShell(); - //there is no modal shell and no active window, so just return a null parent shell - return null; - } - - /** - * Return the modal shell that is currently open. If there isn't one then - * return null. - * - * @param shells shells to search for modal children - * @return the most specific modal child, or null if none - * - * This method is copied from ProgressManagerUtil#getDefaultParent() - */ - - private static Shell getDefaultParentShell(Shell[] shells) { - //first look for a modal shell - for (int i = shells.length - 1; i >= 0; i--) { - Shell shell = shells[i]; - - // Check if this shell has a modal child - Shell modalChild = getDefaultParentShell(shell.getShells()); - if (modalChild != null) { - return modalChild; - } - - // Do not worry about shells that will not block the user. - if (shell.isVisible()) { - int modal = SWT.APPLICATION_MODAL | SWT.SYSTEM_MODAL | SWT.PRIMARY_MODAL; - if ((shell.getStyle() & modal) != 0) { - return shell; - } - } - } - return null; - } - - public static void addProvisioningListener(ProvUIProvisioningListener listener) { - ProvUIActivator.getDefault().addProvisioningListener(listener); - } - - public static void removeProvisioningListener(ProvUIProvisioningListener listener) { - ProvUIActivator.getDefault().removeProvisioningListener(listener); - } - - public static void startBatchOperation() { - ProvUIActivator.getDefault().signalBatchOperationStart(); - } - - public static void endBatchOperation(boolean notify) { - ProvUIActivator.getDefault().signalBatchOperationComplete(notify); - } - - public static void openUpdateManagerInstaller(Event event) { - runCommand(UPDATE_MANAGER_FIND_AND_INSTALL, ProvUIMessages.UpdateManagerCompatibility_UnableToOpenFindAndInstall, event); - } - - public static void openUpdateManagerConfigurationManager(Event event) { - runCommand(UPDATE_MANAGER_MANAGE_CONFIGURATION, ProvUIMessages.UpdateManagerCompatibility_UnableToOpenManageConfiguration, event); - } - - public static void openInstallationDialog(Event event) { - runCommand(INSTALLATION_DIALOG, ProvUIMessages.ProvUI_InstallDialogError, event); - } - - private static void runCommand(String commandId, String errorMessage, Event event) { - ICommandService commandService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class); - Command command = commandService.getCommand(commandId); - if (!command.isDefined()) { - return; - } - IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); - try { - handlerService.executeCommand(commandId, event); - } catch (ExecutionException e) { - reportFail(errorMessage, e); - } catch (NotDefinedException e) { - reportFail(errorMessage, e); - } catch (NotEnabledException e) { - reportFail(errorMessage, e); - } catch (NotHandledException e) { - reportFail(errorMessage, e); - } - } - - private static void reportFail(String message, Throwable t) { - Status failStatus = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, message, t); - reportStatus(failStatus, StatusManager.BLOCK | StatusManager.LOG); - - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvUIImages.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvUIImages.java deleted file mode 100644 index 587d70800..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvUIImages.java +++ /dev/null @@ -1,81 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui; - -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.swt.graphics.Image; - -/** - * ProvUIImages provides convenience methods for accessing shared images - * provided by the org.eclipse.equinox.internal.provisional.p2.ui plug-in. - *

    - * This class provides ImageDescriptors for each named image in - * {@link ProvUIImages}. All Image objects created from the - * provided descriptors are managed the caller and must be disposed - * appropriately. - *

    - *

    - * This class is not intended to be subclassed or instantiated by clients - * - * @since 3.4 - * @noextend This class is not intended to be subclassed by clients. - * @noinstantiate This class is not intended to be instantiated by clients. - */ -public class ProvUIImages { - - // bundle-relative icon path - public final static String ICON_PATH = "$nl$/icons/"; //$NON-NLS-1$ - //objects - public final static String IMG_ARTIFACT_REPOSITORY = "obj/artifact_repo_obj.gif"; //$NON-NLS-1$ - public final static String IMG_METADATA_REPOSITORY = "obj/metadata_repo_obj.gif"; //$NON-NLS-1$ - public final static String IMG_IU = "obj/iu_obj.gif"; //$NON-NLS-1$ - public final static String IMG_DISABLED_IU = "obj/iu_disabled_obj.gif"; //$NON-NLS-1$ - public final static String IMG_UPDATED_IU = "obj/iu_update_obj.gif"; //$NON-NLS-1$ - public final static String IMG_PROFILE = "obj/profile_obj.gif"; //$NON-NLS-1$ - public final static String IMG_CATEGORY = "obj/category_obj.gif"; //$NON-NLS-1$ - // tools - public final static String IMG_TOOL_UPDATE = "tool/update.gif"; //$NON-NLS-1$ - public final static String IMG_TOOL_UPDATE_PROBLEMS = "tool/update_problems.gif"; //$NON-NLS-1$ - public final static String IMG_TOOL_CLOSE = "tool/close.gif"; //$NON-NLS-1$ - public final static String IMG_TOOL_CLOSE_HOT = "tool/close_hot.gif"; //$NON-NLS-1$ - - // wizard graphics - public final static String WIZARD_BANNER_INSTALL = "wizban/install_wiz.gif"; //$NON-NLS-1$ - public final static String WIZARD_BANNER_UNINSTALL = "wizban/uninstall_wiz.gif"; //$NON-NLS-1$ - public final static String WIZARD_BANNER_UPDATE = "wizban/update_wiz.gif"; //$NON-NLS-1$ - public final static String WIZARD_BANNER_REVERT = "wizban/revert_wiz.gif"; //$NON-NLS-1$ - - /** - * Returns the image descriptor for the given image ID. Returns - * null if there is no such image. - * - * @param id - * the identifier for the image to retrieve - * @return the image descriptor associated with the given ID - */ - public static ImageDescriptor getImageDescriptor(String id) { - return ProvUIActivator.getDefault().getImageRegistry().getDescriptor(id); - } - - /** - * Returns the image for the given image ID. Returns null if - * there is no such image. - * - * @param id - * the identifier for the image to retrieve - * @return the image associated with the given ID. This image is managed in - * an image registry and should not be freed by the client. - */ - public static Image getImage(String id) { - return ProvUIActivator.getDefault().getImageRegistry().get(id); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvUIProvisioningListener.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvUIProvisioningListener.java deleted file mode 100644 index 397fbfacd..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvUIProvisioningListener.java +++ /dev/null @@ -1,194 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui; - -import java.util.EventObject; -import org.eclipse.equinox.internal.p2.ui.BatchChangeBeginningEvent; -import org.eclipse.equinox.internal.p2.ui.BatchChangeCompleteEvent; -import org.eclipse.equinox.internal.provisional.p2.core.eventbus.ProvisioningListener; -import org.eclipse.equinox.internal.provisional.p2.engine.ProfileEvent; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; - -/** - * ProvisioningListener which handles event batching and other - * extensions to the provisioning event framework that are used by - * the UI. - * - * @since 3.5 - */ -public abstract class ProvUIProvisioningListener implements ProvisioningListener { - - public static final int PROV_EVENT_METADATA_REPOSITORY = 0x0001; - public static final int PROV_EVENT_IU = 0x0002; - public static final int PROV_EVENT_PROFILE = 0x0004; - public static final int PROV_EVENT_ARTIFACT_REPOSITORY = 0x0008; - - int eventTypes = 0; - int batchCount = 0; - - public ProvUIProvisioningListener(int eventTypes) { - this.eventTypes = eventTypes; - } - - public void notify(EventObject o) { - if (o instanceof BatchChangeBeginningEvent) { - batchCount++; - } else if (o instanceof BatchChangeCompleteEvent) { - batchCount--; - // A batch operation completed. Refresh if we are - // to honor it. - if (batchCount <= 0 && ((BatchChangeCompleteEvent) o).notify) - refreshAll(); - } else if (batchCount > 0) { - // We are in the middle of a batch operation - return; - } else if (o instanceof ProfileEvent && (((eventTypes & PROV_EVENT_IU) == PROV_EVENT_IU) || ((eventTypes & PROV_EVENT_PROFILE) == PROV_EVENT_PROFILE))) { - ProfileEvent event = (ProfileEvent) o; - if (event.getReason() == ProfileEvent.CHANGED) { - profileChanged(event.getProfileId()); - } else if (event.getReason() == ProfileEvent.ADDED) { - profileAdded(event.getProfileId()); - } else if (event.getReason() == ProfileEvent.REMOVED) { - profileRemoved(event.getProfileId()); - } - } else if (o instanceof RepositoryEvent) { - RepositoryEvent event = (RepositoryEvent) o; - // Do not handle unless this is the type of repo that we are interested in - if ((event.getRepositoryType() == IRepository.TYPE_METADATA && (eventTypes & PROV_EVENT_METADATA_REPOSITORY) == PROV_EVENT_METADATA_REPOSITORY) || (event.getRepositoryType() == IRepository.TYPE_ARTIFACT && (eventTypes & PROV_EVENT_ARTIFACT_REPOSITORY) == PROV_EVENT_ARTIFACT_REPOSITORY)) { - if (event.getKind() == RepositoryEvent.ADDED) { - repositoryAdded(event); - } else if (event.getKind() == RepositoryEvent.REMOVED) { - repositoryRemoved(event); - } else if (event.getKind() == RepositoryEvent.DISCOVERED) { - repositoryDiscovered(event); - } else if (event.getKind() == RepositoryEvent.CHANGED) { - repositoryChanged(event); - } else if (event.getKind() == RepositoryEvent.ENABLEMENT) { - repositoryEnablement(event); - } - } - } - } - - /** - * A repository has been added. Subclasses may override. May be called - * from a non-UI thread. - * - * @param event the RepositoryEvent describing the details - */ - protected void repositoryAdded(RepositoryEvent event) { - // Do nothing. This method is not abstract because subclasses - // may not be interested in repository events at all and should - // not have to implement it. - } - - /** - * A repository has been removed. Subclasses may override. May be called - * from a non-UI thread. - * - * @param event the RepositoryEvent describing the details - */ - protected void repositoryRemoved(RepositoryEvent event) { - // Do nothing. This method is not abstract because subclasses - // may not be interested in repository events at all and should - // not have to implement it. - } - - /** - * A repository has been discovered. Subclasses may override. May be called - * from a non-UI thread. - * - * @param event the RepositoryEvent describing the details - */ - protected void repositoryDiscovered(RepositoryEvent event) { - // Do nothing. This method is not abstract because subclasses - // may not be interested in repository events at all and should - // not have to implement it. - } - - /** - * A repository has changed. Subclasses may override. May be called - * from a non-UI thread. - * - * @param event the RepositoryEvent describing the details - */ - protected void repositoryChanged(RepositoryEvent event) { - // Do nothing. This method is not abstract because subclasses - // may not be interested in repository events at all and should - // not have to implement it. - } - - /** - * A repository's enablement state has changed. This is treated - * as repository addition or removal by default. Subclasses may - * override. May be called from a non-UI thread. - * @param event - */ - protected void repositoryEnablement(RepositoryEvent event) { - // We treat enablement of a repository as if one were added. - if (event.isRepositoryEnabled()) - repositoryAdded(event); - else - repositoryRemoved(event); - } - - /** - * The specified profile has changed. Subclasses may override. May be called - * from a non-UI thread. - * - * @param profileId the id of the profile that changed. - */ - protected void profileChanged(final String profileId) { - // Do nothing. This method is not abstract because subclasses - // may not be interested in profile events at all and should - // not have to implement it. - } - - /** - * The specified profile has been added. Subclasses may override. May be called - * from a non-UI thread. - * - * @param profileId the id of the profile that has been added. - */ - protected void profileAdded(final String profileId) { - // Do nothing. This method is not abstract because subclasses - // may not be interested in profile events at all and should - // not have to implement it. - } - - /** - * The specified profile has been removed. Subclasses may override. May be called - * from a non-UI thread. - * - * @param profileId the id of the profile that has been removed. - */ - protected void profileRemoved(final String profileId) { - // Do nothing. This method is not abstract because subclasses - // may not be interested in profile events at all and should - // not have to implement it. - } - - /** - * An event requiring a complete refresh of the listener's state has - * been received. This is used, for example, when a batch change has - * completed. Subclasses may override. May be called from a non-UI - * thread. - */ - protected void refreshAll() { - // Do nothing by default. - } - - public int getEventTypes() { - return eventTypes; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvisioningOperationRunner.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvisioningOperationRunner.java deleted file mode 100644 index 672828362..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ProvisioningOperationRunner.java +++ /dev/null @@ -1,251 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui; - -import java.io.IOException; -import java.util.HashSet; -import org.eclipse.core.runtime.*; -import org.eclipse.core.runtime.jobs.*; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.dialogs.ApplyProfileChangesDialog; -import org.eclipse.equinox.internal.provisional.configurator.Configurator; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProfileModificationOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningOperation; -import org.eclipse.osgi.util.NLS; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.progress.IProgressConstants; -import org.eclipse.ui.progress.WorkbenchJob; -import org.eclipse.ui.statushandlers.StatusManager; - -/** - * Utility methods for running provisioning operations. Operations can either - * be run synchronously or in a job. When scheduled as a job, the operation - * determines whether the job is run in - * the background or in the UI. - * - * @since 3.4 - */ -public class ProvisioningOperationRunner { - - private static final String PROPERTY_PREFIX = "org.eclipse.equinox.p2.ui"; //$NON-NLS-1$ - private static final QualifiedName OPERATION_KEY = new QualifiedName(PROPERTY_PREFIX, "operationKey"); //$NON-NLS-1$ - static HashSet scheduledJobs = new HashSet(); - static boolean restartRequested = false; - static boolean restartRequired = false; - static boolean subsequentRestartsRequested = false; - // used during automated testing to prevent a restart dialog from interrupting tests - static boolean suppressRestart = false; - static ListenerList jobListeners = new ListenerList(); - - /** - * This method is temporary and will not appear in the final API. - * - * @param suppress - * - * @deprecated see https://bugs.eclipse.org/bugs/show_bug.cgi?id=274876 - */ - public static void suppressRestart(boolean suppress) { - suppressRestart = suppress; - } - - /** - * Run the provisioning operation synchronously - * @param op The operation to execute - * @param errorStyle the flags passed to the StatusManager for error reporting - */ - public static void run(ProvisioningOperation op, int errorStyle) { - try { - op.execute(new NullProgressMonitor()); - } catch (OperationCanceledException e) { - // nothing to do - } catch (ProvisionException e) { - ProvUI.handleException(e, null, errorStyle); - } - - } - - /** - * Schedule a job to execute the supplied ProvisioningOperation. - * - * @param op The operation to execute - * @param errorStyle the flags passed to the StatusManager for error reporting - */ - public static Job schedule(final ProvisioningOperation op, final int errorStyle) { - Job job; - final boolean noPrompt = (errorStyle & (StatusManager.BLOCK | StatusManager.SHOW)) == 0; - - if (op.runInBackground()) { - job = new Job(op.getLabel()) { - protected IStatus run(IProgressMonitor monitor) { - final Job thisJob = this; - try { - IStatus status = op.execute(monitor); - if (!status.isOK() && noPrompt) { - this.setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); - this.setProperty(IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE); - } - return status; - } catch (OperationCanceledException e) { - return Status.CANCEL_STATUS; - } catch (final ProvisionException e) { - if (noPrompt) { - thisJob.setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); - thisJob.setProperty(IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE); - } - String message = e.getLocalizedMessage(); - if (message == null) - message = NLS.bind(ProvUIMessages.ProvisioningOperationRunner_ErrorExecutingOperation, op.getLabel()); - return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, 0, message, e); - } - } - }; - job.setPriority(Job.LONG); - } else { - job = new WorkbenchJob(op.getLabel()) { - public IStatus runInUIThread(IProgressMonitor monitor) { - try { - IStatus status = op.execute(monitor); - if (!status.isOK() && noPrompt) { - this.setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); - this.setProperty(IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE); - } - return status; - } catch (OperationCanceledException e) { - return Status.CANCEL_STATUS; - } catch (ProvisionException e) { - if (noPrompt) { - this.setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); - this.setProperty(IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE); - } - return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, 0, NLS.bind(ProvUIMessages.ProvisioningOperationRunner_ErrorExecutingOperation, op.getLabel()), e); - } - } - }; - job.setPriority(Job.SHORT); - } - job.setUser(op.isUser()); - job.setProperty(OPERATION_KEY, op); - job.setProperty(IProgressConstants.ICON_PROPERTY, ProvUIImages.getImageDescriptor(ProvUIImages.IMG_PROFILE)); - manageJob(job); - job.schedule(); - return job; - } - - /** - * This method is temporary and is not intended for the API. - * - * @deprecated see https://bugs.eclipse.org/bugs/show_bug.cgi?id=274876 - */ - public static void clearRestartRequests() { - restartRequired = false; - restartRequested = false; - subsequentRestartsRequested = false; - } - - /** - * This method will not appear in the final API. - * - * @param force - * @deprecated see https://bugs.eclipse.org/bugs/show_bug.cgi?id=274876 - - */ - public static void requestRestart(boolean force) { - if (suppressRestart || hasScheduledOperations()) { - restartRequested = true; - subsequentRestartsRequested = true; - restartRequired = restartRequired || force; - return; - } - PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { - public void run() { - if (PlatformUI.getWorkbench().isClosing()) - return; - int retCode = ApplyProfileChangesDialog.promptForRestart(ProvUI.getDefaultParentShell(), restartRequired); - // Now that we have asked, regardless of answer, we won't need to - // ask again until the next profile changing operation. Don't reset - // the restart required flag so that the next time we ask, if it - // was required before, it will still be required. - restartRequested = false; - if (retCode == ApplyProfileChangesDialog.PROFILE_APPLYCHANGES) { - Configurator configurator = (Configurator) ServiceHelper.getService(ProvUIActivator.getContext(), Configurator.class.getName()); - try { - configurator.applyConfiguration(); - } catch (IOException e) { - ProvUI.handleException(e, ProvUIMessages.ProvUI_ErrorDuringApplyConfig, StatusManager.LOG | StatusManager.BLOCK); - } catch (IllegalStateException e) { - IStatus illegalApplyStatus = new Status(IStatus.WARNING, ProvUIActivator.PLUGIN_ID, 0, ProvUIMessages.ProvisioningOperationRunner_CannotApplyChanges, e); - ProvUI.reportStatus(illegalApplyStatus, StatusManager.LOG | StatusManager.BLOCK); - } - } else if (retCode == ApplyProfileChangesDialog.PROFILE_RESTART) { - PlatformUI.getWorkbench().restart(); - } - } - }); - } - - public static boolean hasScheduledOperations() { - return !scheduledJobs.isEmpty(); - } - - public static boolean hasScheduledOperationsFor(String profileId) { - Job[] jobs = getScheduledJobs(); - for (int i = 0; i < jobs.length; i++) { - Object op = jobs[i].getProperty(OPERATION_KEY); - if (op instanceof ProfileModificationOperation) { - String id = ((ProfileModificationOperation) op).getProfileId(); - if (profileId.equals(id)) - return true; - } - } - return false; - } - - public static void addJobChangeListener(IJobChangeListener listener) { - jobListeners.add(listener); - Job[] jobs = getScheduledJobs(); - for (int i = 0; i < jobs.length; i++) - jobs[i].addJobChangeListener(listener); - } - - public static void removeJobChangeListener(IJobChangeListener listener) { - jobListeners.remove(listener); - Job[] jobs = getScheduledJobs(); - for (int i = 0; i < jobs.length; i++) - jobs[i].removeJobChangeListener(listener); - } - - private static Job[] getScheduledJobs() { - return (Job[]) scheduledJobs.toArray(new Job[scheduledJobs.size()]); - } - - public static void manageJob(Job job) { - scheduledJobs.add(job); - subsequentRestartsRequested = false; - job.addJobChangeListener(new JobChangeAdapter() { - public void done(IJobChangeEvent event) { - scheduledJobs.remove(event.getJob()); - int severity = event.getResult().getSeverity(); - if (severity != IStatus.CANCEL && severity != IStatus.ERROR && restartRequested) { - requestRestart(restartRequired); - } else { - restartRequested = subsequentRestartsRequested; - } - } - }); - Object[] listeners = jobListeners.getListeners(); - for (int i = 0; i < listeners.length; i++) - job.addJobChangeListener((IJobChangeListener) listeners[i]); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/QueryableArtifactRepositoryManager.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/QueryableArtifactRepositoryManager.java deleted file mode 100644 index 8d6cab8ca..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/QueryableArtifactRepositoryManager.java +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * EclipseSource - ongoing development - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui; - -import java.net.URI; -import java.util.*; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.SubMonitor; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.IUViewQueryContext; - -/** - * An object that adds provides queryable support - * for an artifact repository manager. The query context determines which - * repositories are included in the query. Since artifact repositories - * do not support queries, the query will be performed over the repository - * locations. - */ -public class QueryableArtifactRepositoryManager extends QueryableRepositoryManager { - - public QueryableArtifactRepositoryManager(IUViewQueryContext queryContext, boolean includeDisabledRepos) { - super(queryContext, includeDisabledRepos); - } - - protected URI[] getRepoLocations(IRepositoryManager manager) { - Set locations = new HashSet(); - int flags = queryContext.getArtifactRepositoryFlags(); - locations.addAll(Arrays.asList(manager.getKnownRepositories(flags))); - if (includeDisabledRepos) { - locations.addAll(Arrays.asList(manager.getKnownRepositories(IRepositoryManager.REPOSITORIES_DISABLED | flags))); - } - return (URI[]) locations.toArray(new URI[locations.size()]); - } - - protected IRepositoryManager getRepositoryManager() { - return (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName()); - } - - protected IRepository doLoadRepository(IRepositoryManager manager, URI location, IProgressMonitor monitor) throws ProvisionException { - if (manager instanceof IArtifactRepositoryManager) { - ((IArtifactRepositoryManager) manager).loadRepository(location, monitor); - } - return null; - } - - protected Collector query(URI[] uris, Query query, Collector collector, IProgressMonitor monitor) { - SubMonitor sub = SubMonitor.convert(monitor, uris.length * 100); - - if (sub.isCanceled()) - return collector; - // artifact repositories do not support querying, so we always use the location. - query.perform(Arrays.asList(uris).iterator(), collector); - - return collector; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/QueryableMetadataRepositoryManager.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/QueryableMetadataRepositoryManager.java deleted file mode 100644 index 9ee400d69..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/QueryableMetadataRepositoryManager.java +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui; - -import java.net.URI; -import java.util.*; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.IUViewQueryContext; - -/** - * An object that adds provides specialized/optimized queryable support - * for a metadata repository. The query context determines which repositories - * are included in the query. Callers interested in only the resulting repository URIs - * should specify a {@link RepositoryLocationQuery}, in which case the - * query is performed over the URI's. Otherwise the query is performed over - * the repositories themselves. - */ -public class QueryableMetadataRepositoryManager extends QueryableRepositoryManager { - - public QueryableMetadataRepositoryManager(IUViewQueryContext queryContext, boolean includeDisabledRepos) { - super(queryContext, includeDisabledRepos); - } - - protected IRepository getRepository(IRepositoryManager manager, URI location) { - // note the use of MetadataRepositoryManager (the concrete implementation). - if (manager instanceof MetadataRepositoryManager) { - return ((MetadataRepositoryManager) manager).getRepository(location); - } - return super.getRepository(manager, location); - } - - protected IRepositoryManager getRepositoryManager() { - return (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName()); - } - - protected IRepository doLoadRepository(IRepositoryManager manager, URI location, IProgressMonitor monitor) throws ProvisionException { - if (manager instanceof IMetadataRepositoryManager) { - return ProvisioningUtil.loadMetadataRepository(location, monitor); - } - return null; - } - - protected Collector query(URI uris[], Query query, Collector collector, IProgressMonitor monitor) { - if (query instanceof RepositoryLocationQuery) { - query.perform(Arrays.asList(uris).iterator(), collector); - monitor.done(); - } else { - SubMonitor sub = SubMonitor.convert(monitor, (uris.length + 1) * 100); - ArrayList loadedRepos = new ArrayList(uris.length); - for (int i = 0; i < uris.length; i++) { - IRepository repo = null; - try { - repo = loadRepository(getRepositoryManager(), uris[i], sub.newChild(100)); - } catch (ProvisionException e) { - handleLoadFailure(e, uris[i]); - } catch (OperationCanceledException e) { - // user has canceled - repo = null; - } - if (repo != null) - loadedRepos.add(repo); - } - if (loadedRepos.size() > 0) { - IQueryable[] queryables = (IQueryable[]) loadedRepos.toArray(new IQueryable[loadedRepos.size()]); - collector = new CompoundQueryable(queryables).query(query, collector, sub.newChild(100)); - } - } - return collector; - } - - protected URI[] getRepoLocations(IRepositoryManager manager) { - Set locations = new HashSet(); - int flags = queryContext.getMetadataRepositoryFlags(); - locations.addAll(Arrays.asList(manager.getKnownRepositories(flags))); - if (includeDisabledRepos) { - locations.addAll(Arrays.asList(manager.getKnownRepositories(IRepositoryManager.REPOSITORIES_DISABLED | flags))); - } - return (URI[]) locations.toArray(new URI[locations.size()]); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/QueryableRepositoryManager.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/QueryableRepositoryManager.java deleted file mode 100644 index fbbd05494..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/QueryableRepositoryManager.java +++ /dev/null @@ -1,238 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui; - -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.IUViewQueryContext; -import org.eclipse.osgi.util.NLS; -import org.eclipse.ui.statushandlers.StatusManager; - -/** - * An object that provides specialized repository query support in place of - * a repository manager and its repositories. The repositories to be included - * can be specified using the repository flags defined in the UI policy. The query - * itself is run on the the repositories themselves, if supported by the particular - * kind of repository. If the repository doesn't support queryies, or the query is - * a {@link RepositoryLocationQuery}, the query is run over - * the repository locations instead. - */ -public abstract class QueryableRepositoryManager implements IQueryable { - /** - * List of locations of repositories that were not found - */ - private ArrayList notFound = new ArrayList(); - - /** - * Map of loaded repositories. - */ - private HashMap loaded = new HashMap(); - - private MultiStatus accumulatedNotFound = null; - protected boolean includeDisabledRepos; - protected IUViewQueryContext queryContext; - - public QueryableRepositoryManager(IUViewQueryContext queryContext, boolean includeDisabledRepos) { - this.includeDisabledRepos = includeDisabledRepos; - Assert.isNotNull(queryContext); - this.queryContext = queryContext; - } - - /** - * Iterates over the repositories configured in this queryable. - * For most queries, the query is run on each repository, passing any objects that satisfy the - * query to the provided collector. If the query is a {@link RepositoryLocationQuery}, the query - * is run on the repository locations instead. - *

    - * This method is long-running; progress and cancellation are provided - * by the given progress monitor. - *

    - * - * @param query The query to perform.. - * @param result Collects the results of the query, run on either the repository URIs, or on - * the repositories themselves. - * @param monitor a progress monitor, or null if progress - * reporting is not desired - * @return The collector argument - */ - public Collector query(Query query, Collector result, IProgressMonitor monitor) { - IRepositoryManager manager = getRepositoryManager(); - if (manager == null) { - ProvUI.reportStatus(new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningUtil_NoRepositoryManager), StatusManager.SHOW | StatusManager.LOG); - return result; - } - if (monitor == null) - monitor = new NullProgressMonitor(); - query(getRepoLocations(manager), query, result, monitor); - reportAccumulatedStatus(); - return result; - } - - /** - * Load all of the repositories referenced by this queryable. This is an expensive operation. - * The status of any not found repositories is accumulated and must be reported manually - * using reportAccumulatedStatus() - * - * @param monitor the progress monitor that should be used - */ - public void loadAll(IProgressMonitor monitor) { - IRepositoryManager manager = getRepositoryManager(); - if (manager == null) { - ProvUI.reportStatus(new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningUtil_NoRepositoryManager), StatusManager.SHOW | StatusManager.LOG); - return; - } - URI[] repoLocations = getRepoLocations(manager); - SubMonitor sub = SubMonitor.convert(monitor, repoLocations.length * 100); - if (sub.isCanceled()) - return; - for (int i = 0; i < repoLocations.length; i++) { - if (sub.isCanceled()) - return; - try { - loadRepository(manager, repoLocations[i], sub.newChild(100)); - } catch (ProvisionException e) { - handleLoadFailure(e, repoLocations[i]); - } - } - } - - /** - * Returns an array of repository locations. - */ - protected abstract URI[] getRepoLocations(IRepositoryManager manager); - - protected void handleLoadFailure(ProvisionException e, URI problemRepo) { - int code = e.getStatus().getCode(); - // special handling when the repo is bad. We don't want to continually report it - if (code == ProvisionException.REPOSITORY_NOT_FOUND || code == ProvisionException.REPOSITORY_INVALID_LOCATION) { - // If we thought we had loaded it, get rid of the reference - loaded.remove(problemRepo); - // If we've already reported a URL is not found, don't report again. - if (notFound.contains(problemRepo)) - return; - // If someone else reported a URL is not found, don't report again. - if (ProvUI.hasNotFoundStatusBeenReported(problemRepo)) { - notFound.add(problemRepo); - return; - } - notFound.add(problemRepo); - ProvUI.notFoundStatusReported(problemRepo); - } - - // Some ProvisionExceptions include an empty multi status with a message. - // Since empty multi statuses have a severity OK, The platform status handler doesn't handle - // this well. We correct this by recreating a status with error severity - // so that the platform status handler does the right thing. - IStatus status = e.getStatus(); - if (status instanceof MultiStatus && ((MultiStatus) status).getChildren().length == 0) - status = new Status(IStatus.ERROR, status.getPlugin(), status.getCode(), status.getMessage(), status.getException()); - if (accumulatedNotFound == null) { - accumulatedNotFound = new MultiStatus(ProvUIActivator.PLUGIN_ID, ProvisionException.REPOSITORY_NOT_FOUND, new IStatus[] {status}, ProvUIMessages.QueryableMetadataRepositoryManager_MultipleRepositoriesNotFound, null); - } else { - accumulatedNotFound.add(status); - } - // Always log the complete exception so the detailed stack trace is in the log. - ProvUI.handleException(e, NLS.bind(ProvUIMessages.ProvisioningUtil_LoadRepositoryFailure, problemRepo), StatusManager.LOG); - - } - - public void reportAccumulatedStatus() { - // If we've discovered not found repos we didn't know about, report them - if (accumulatedNotFound != null) { - // If there is only missing repo to report, use the specific message rather than the generic. - if (accumulatedNotFound.getChildren().length == 1) { - ProvUI.reportStatus(accumulatedNotFound.getChildren()[0], StatusManager.SHOW); - } else { - ProvUI.reportStatus(accumulatedNotFound, StatusManager.SHOW); - } - } - // Reset the accumulated status so that next time we only report the newly not found repos. - accumulatedNotFound = null; - } - - /** - * Return a boolean indicating whether all the repositories that - * can be queried by the receiver are already loaded. If a repository - * is not loaded because it was not found, this will not return false, - * because this repository cannot be queried. - * - * @return true if all repositories to be queried by the - * receiver are loaded, false if they - * are not. - */ - public boolean areRepositoriesLoaded() { - IRepositoryManager mgr = getRepositoryManager(); - if (mgr == null) - return false; - URI[] repoURIs = getRepoLocations(mgr); - for (int i = 0; i < repoURIs.length; i++) { - IRepository repo = getRepository(mgr, repoURIs[i]); - // A not-loaded repo doesn't count if it's considered missing (not found) - if (repo == null && !ProvUI.hasNotFoundStatusBeenReported(repoURIs[i])) - return false; - } - return true; - } - - protected IRepository loadRepository(IRepositoryManager manager, URI location, IProgressMonitor monitor) throws ProvisionException { - monitor.setTaskName(NLS.bind(ProvUIMessages.QueryableMetadataRepositoryManager_LoadRepositoryProgress, URIUtil.toUnencodedString(location))); - IRepository repo = doLoadRepository(manager, location, monitor); - if (repo != null) - loaded.put(location, repo); - return repo; - } - - /** - * Return the appropriate repository manager, or null if none could be found. - * @return the repository manager - */ - protected abstract IRepositoryManager getRepositoryManager(); - - /** - * Get an already-loaded repository at the specified location. - * - * @param manager the manager - * @param location the repository location - * @return the repository at that location, or null if no repository is - * yet located at that location. - */ - protected IRepository getRepository(IRepositoryManager manager, URI location) { - // This is only used by the artifact mgr subclass. - // MetadataRepositoryManager has a method for getting its cached repo instance - return (IRepository) loaded.get(location); - } - - /** - * Load the repository located at the specified location. - * - * @param manager the manager - * @param location the repository location - * @param monitor the progress monitor - * @return the repository that was loaded, or null if no repository could - * be found at that location. - */ - protected abstract IRepository doLoadRepository(IRepositoryManager manager, URI location, IProgressMonitor monitor) throws ProvisionException; - - protected abstract Collector query(URI[] uris, Query query, Collector collector, IProgressMonitor monitor); - - public void setQueryContext(IUViewQueryContext queryContext) { - this.queryContext = queryContext; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/RepositoryLocationQuery.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/RepositoryLocationQuery.java deleted file mode 100644 index e5398c4fd..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/RepositoryLocationQuery.java +++ /dev/null @@ -1,68 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - ******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.QueryHelpers; - -import java.net.URI; -import java.util.Iterator; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; - -/** - * RepositoryLocationQuery is a query that gathers repository - * locations rather than repositories. It is used when composing - * queries against a QueryableRepositoryManager to indicate that the - * repository need not be loaded to run the query. - * - * @since 3.5 - */ -public class RepositoryLocationQuery implements Query { - - /** - * Gets the ID for this Query. - */ - public String getId() { - return QueryHelpers.getId(this); - } - - /** - * Gets a particular property of the query. - * @param property The property to retrieve - */ - public Object getProperty(String property) { - return QueryHelpers.getProperty(this, property); - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.query.Query#perform(java.util.Iterator, org.eclipse.equinox.internal.provisional.p2.query.Collector) - */ - public Collector perform(Iterator iterator, Collector result) { - while (iterator.hasNext()) { - Object candidate = iterator.next(); - URI location = getLocation(candidate); - if (location != null) - if (!result.accept(location)) - break; - } - return result; - } - - private URI getLocation(Object o) { - if (o instanceof URI) - return (URI) o; - if (o instanceof IRepository) - return ((IRepository) o).getLocation(); - return null; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ResolutionResult.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ResolutionResult.java deleted file mode 100644 index 1e2e43da0..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ResolutionResult.java +++ /dev/null @@ -1,127 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - ******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui; - -import java.util.HashMap; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; - -/** - * ResolutionResult describes problems in a provisioning plan in a structured - * way that can be presented to a user. - * - * @since 3.5 - */ -public class ResolutionResult { - private static final String NESTING_INDENT = " "; //$NON-NLS-1$ - - private HashMap iuToStatusMap = new HashMap(); - private MultiStatus summaryStatus; - - public IStatus getSummaryStatus() { - if (summaryStatus != null) - return summaryStatus; - return Status.OK_STATUS; - } - - public void addSummaryStatus(IStatus status) { - if (summaryStatus == null) { - summaryStatus = new MultiStatus(ProvUIActivator.PLUGIN_ID, 0, ProvUIMessages.ResolutionReport_SummaryStatus, null); - } - summaryStatus.add(status); - } - - public IStatus statusOf(IInstallableUnit iu) { - return (IStatus) iuToStatusMap.get(iu); - } - - public void addStatus(IInstallableUnit iu, IStatus status) { - MultiStatus iuSummaryStatus = (MultiStatus) iuToStatusMap.get(iu); - if (iuSummaryStatus == null) { - iuSummaryStatus = new MultiStatus(ProvUIActivator.PLUGIN_ID, IStatusCodes.IU_REQUEST_ALTERED, new IStatus[] {status}, getIUString(iu), null); - } else - iuSummaryStatus.add(status); - } - - private String getIUString(IInstallableUnit iu) { - if (iu == null) - return ProvUIMessages.PlanStatusHelper_Items; - // Get the iu name in the default locale - String name = IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_NAME); - if (name != null) - return name; - return iu.getId(); - } - - public String getSummaryReport() { - if (summaryStatus != null) { - StringBuffer buffer = new StringBuffer(); - appendDetailText(summaryStatus, buffer, -1, false); - return buffer.toString(); - } - return ""; //$NON-NLS-1$ - } - - // Answers null if there is nothing to say about the ius - public String getDetailedReport(IInstallableUnit[] ius) { - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < ius.length; i++) { - MultiStatus iuStatus = (MultiStatus) iuToStatusMap.get(ius[i]); - if (iuStatus != null) - appendDetailText(iuStatus, buffer, 0, true); - } - String report = buffer.toString(); - if (report.length() == 0) - return null; - return report; - } - - void appendDetailText(IStatus status, StringBuffer buffer, int indent, boolean includeTopLevelMessage) { - if (includeTopLevelMessage) { - for (int i = 0; i < indent; i++) - buffer.append(NESTING_INDENT); - if (status.getMessage() != null) - buffer.append(status.getMessage()); - } - Throwable t = status.getException(); - if (t != null) { - // A provision (or core) exception occurred. Get its status message or if none, its top level message. - // Indent by one more level (note the <=) - buffer.append('\n'); - for (int i = 0; i <= indent; i++) - buffer.append(NESTING_INDENT); - if (t instanceof CoreException) { - IStatus exceptionStatus = ((CoreException) t).getStatus(); - if (exceptionStatus != null && exceptionStatus.getMessage() != null) - buffer.append(exceptionStatus.getMessage()); - else { - String details = t.getLocalizedMessage(); - if (details != null) - buffer.append(details); - } - } else { - String details = t.getLocalizedMessage(); - if (details != null) - buffer.append(details); - } - } - // Now print the children status info (if there are children) - IStatus[] children = status.getChildren(); - for (int i = 0; i < children.length; i++) { - if (buffer.length() > 0) - buffer.append('\n'); - appendDetailText(children[i], buffer, indent + 1, true); - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/UpdateManagerCompatibility.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/UpdateManagerCompatibility.java deleted file mode 100644 index 651ccbb4e..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/UpdateManagerCompatibility.java +++ /dev/null @@ -1,300 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui; - -import java.io.*; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Vector; -import javax.xml.parsers.*; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.engine.Operand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.FileDialog; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.statushandlers.StatusManager; -import org.w3c.dom.*; -import org.xml.sax.SAXException; - -/** - * Utility methods involving compatibility with the Eclipse Update Manager. - * - * @since 3.4 - * - */ -public class UpdateManagerCompatibility { - - // This value was copied from MetadataGeneratorHelper. Must be the same. - private static final String ECLIPSE_INSTALL_HANDLER_PROP = "org.eclipse.update.installHandler"; //$NON-NLS-1$ - private static final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - - private static void parse(String fileName, Vector bookmarks) { - File file = new File(fileName); - if (!file.exists()) - return; - - try { - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder parser = documentBuilderFactory.newDocumentBuilder(); - Document doc = parser.parse(file); - Node root = doc.getDocumentElement(); - processRoot(root, bookmarks); - } catch (ParserConfigurationException e) { - logFail(e); - } catch (SAXException e) { - logFail(e); - } catch (IOException e) { - logFail(e); - } - } - - private static MetadataRepositoryElement[] getSites(Vector bookmarks) { - ArrayList result = new ArrayList(); - for (int i = 0; i < bookmarks.size(); i++) { - if (bookmarks.get(i) instanceof MetadataRepositoryElement) - result.add(bookmarks.get(i)); - } - return (MetadataRepositoryElement[]) result.toArray(new MetadataRepositoryElement[result.size()]); - } - - private static void processRoot(Node root, Vector bookmarks) { - if (root.getNodeName().equals("bookmarks")) { //$NON-NLS-1$ - NodeList children = root.getChildNodes(); - processChildren(children, bookmarks); - } - } - - private static void processChildren(NodeList children, Vector bookmarks) { - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - if (child.getNodeType() == Node.ELEMENT_NODE) { - if (child.getNodeName().equals("site")) { //$NON-NLS-1$ - createSite(child, bookmarks); - } else if (child.getNodeName().equals("folder")) { //$NON-NLS-1$ - createFolder(child, bookmarks); - } - } - } - } - - private static void createSite(Node child, Vector bookmarks) { - URI uri = null; - try { - uri = URIUtil.fromString((getAttribute(child, "url"))); //$NON-NLS-1$ - } catch (URISyntaxException e) { - logFail(e); - return; - } - - String sel = getAttribute(child, "selected"); //$NON-NLS-1$ - boolean selected = (sel != null && sel.equals("true")); //$NON-NLS-1$ - - MetadataRepositoryElement element = new MetadataRepositoryElement(null, uri, selected); - String nickname = getAttribute(child, "name"); //$NON-NLS-1$ - if (nickname != null && nickname.length() > 0) - element.setNickname(nickname); - bookmarks.add(element); - } - - private static void createFolder(Node child, Vector bookmarks) { - if (child.hasChildNodes()) - processChildren(child.getChildNodes(), bookmarks); - } - - private static String getAttribute(Node node, String name) { - NamedNodeMap atts = node.getAttributes(); - Node att = atts.getNamedItem(name); - if (att != null) { - return att.getNodeValue(); - } - return ""; //$NON-NLS-1$ - } - - private static void store(String fileName, Vector bookmarks) { - FileOutputStream fos = null; - OutputStreamWriter osw = null; - PrintWriter writer = null; - try { - fos = new FileOutputStream(fileName); - osw = new OutputStreamWriter(fos, "UTF8"); //$NON-NLS-1$ - writer = new PrintWriter(osw); - writer.println(""); //$NON-NLS-1$ - writer.println(""); //$NON-NLS-1$ - for (int i = 0; i < bookmarks.size(); i++) { - Object obj = bookmarks.get(i); - writeObject(" ", obj, writer); //$NON-NLS-1$ - } - } catch (IOException e) { - logFail(e); - } finally { - if (writer != null) { - writer.println(""); //$NON-NLS-1$ - writer.flush(); - writer.close(); - } - try { - if (osw != null) - osw.close(); - } catch (IOException e1) { - logFail(e1); - } - try { - if (fos != null) - fos.close(); - } catch (IOException e2) { - logFail(e2); - } - } - } - - private static void writeObject(String indent, Object obj, PrintWriter writer) { - if (obj instanceof MetadataRepositoryElement) { - MetadataRepositoryElement element = (MetadataRepositoryElement) obj; - String sel = element.isEnabled() ? "true" : "false"; //$NON-NLS-1$ //$NON-NLS-2$ - String name = element.getName(); - writer.print(indent + ""); //$NON-NLS-1$ - } - } - - public static boolean requiresInstallHandlerSupport(ProvisioningPlan plan) { - Operand[] operands = plan.getOperands(); - for (int i = 0; i < operands.length; i++) { - if (operands[i] instanceof InstallableUnitOperand) { - IInstallableUnit iu = ((InstallableUnitOperand) operands[i]).second(); - if (iu != null && iu.getProperty(ECLIPSE_INSTALL_HANDLER_PROP) != null) - return true; - } - } - return false; - - } - - /** - * Prompt the user for a file and import the sites specified in that - * file. Return the collection of repo elements in the import. - * @param shell the shell used to parent any dialogs used. - */ - public static MetadataRepositoryElement[] importSites(Shell shell) { - FileDialog dialog = new FileDialog(shell); - dialog.setText(ProvUIMessages.UpdateManagerCompatibility_ImportSitesTitle); - dialog.setFilterExtensions(new String[] {"*.xml", "*"}); //$NON-NLS-1$ //$NON-NLS-2$ - - MetadataRepositoryElement[] sites = null; - - String bookmarksFile = dialog.open(); - while (bookmarksFile != null && sites == null) { - File file = new File(bookmarksFile); - sites = readBookmarkFile(file); - if (sites == null || sites.length == 0) { - MessageDialog.openInformation(shell, ProvUIMessages.UpdateManagerCompatibility_InvalidSitesTitle, ProvUIMessages.UpdateManagerCompatibility_InvalidSiteFileMessage); - bookmarksFile = dialog.open(); - } - } - return sites == null ? new MetadataRepositoryElement[0] : sites; - } - - public static MetadataRepositoryElement[] readBookmarkFile(File file) { - Vector bookmarks = new Vector(); - parse(file.getAbsolutePath(), bookmarks); - return getSites(bookmarks); - } - - public static void writeBookmarkFile(String filename, MetadataRepositoryElement[] sites) { - Vector bookmarks = new Vector(sites.length); - for (int i = 0; i < sites.length; i++) - bookmarks.add(sites[i]); - store(filename, bookmarks); - - } - - /** - * Export the specified list of sites to a bookmarks file that - * can be read later. - * - * @param shell the shell used to parent the export dialog - * @param sites the sites to export - */ - - public static void exportSites(Shell shell, MetadataRepositoryElement[] sites) { - FileDialog dialog = new FileDialog(shell, SWT.SAVE); - dialog.setText(ProvUIMessages.UpdateManagerCompatibility_ExportSitesTitle); - dialog.setFileName("bookmarks.xml"); //$NON-NLS-1$ - dialog.setFilterExtensions(new String[] {"*.xml", "*"}); //$NON-NLS-1$ //$NON-NLS-2$ - - String bookmarksFile = dialog.open(); - if (bookmarksFile == null) - return; - - writeBookmarkFile(bookmarksFile, sites); - } - - /** - * Open the old UpdateManager installer UI using the specified shell. - * We do not call the UpdateManagerUI class directly because we want to be able to be configured - * without requiring those plug-ins. Instead, we invoke a known command. - */ - public static void openInstaller() { - ProvUI.openUpdateManagerInstaller(null); - } - - /** - * Open the old UpdateManager configuration manager UI using the specified shell. - * We do not call the UpdateManagerUI class directly because we want to be able to be configured - * without requiring those plug-ins. Instead, we invoke a known command. - */ - public static void openConfigurationManager() { - ProvUI.openUpdateManagerConfigurationManager(null); - } - - private static void logFail(Throwable t) { - Status failStatus = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, t.getLocalizedMessage(), t); - ProvUI.reportStatus(failStatus, StatusManager.LOG); - } - - private static String getWritableXMLString(String value) { - StringBuffer buf = new StringBuffer(); - if (value == null) - return buf.toString(); - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - switch (c) { - case '&' : - buf.append("&"); //$NON-NLS-1$ - break; - case '<' : - buf.append("<"); //$NON-NLS-1$ - break; - case '>' : - buf.append(">"); //$NON-NLS-1$ - break; - case '\'' : - buf.append("'"); //$NON-NLS-1$ - break; - case '\"' : - buf.append("""); //$NON-NLS-1$ - break; - default : - buf.append(c); - break; - } - } - return buf.toString(); - } -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ValidationDialogServiceUI.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ValidationDialogServiceUI.java deleted file mode 100644 index b83e7c36d..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/ValidationDialogServiceUI.java +++ /dev/null @@ -1,192 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui; - -import java.security.cert.Certificate; -import org.eclipse.core.runtime.*; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.dialogs.TrustCertificateDialog; -import org.eclipse.equinox.internal.p2.ui.dialogs.UserValidationDialog; -import org.eclipse.equinox.internal.p2.ui.viewers.CertificateLabelProvider; -import org.eclipse.equinox.internal.provisional.p2.core.IServiceUI; -import org.eclipse.jface.dialogs.ErrorDialog; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.viewers.*; -import org.eclipse.jface.window.Window; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.PlatformUI; - -/** - * The default GUI-based implementation of {@link IServiceUI}. - * The service declaration is made in the serviceui_component.xml file. - - */ -public class ValidationDialogServiceUI implements IServiceUI { - /** - * Subclassed to add a cancel button to the error dialog. - */ - static class OkCancelErrorDialog extends ErrorDialog { - - public OkCancelErrorDialog(Shell parentShell, String dialogTitle, String message, IStatus status, int displayMask) { - super(parentShell, dialogTitle, message, status, displayMask); - } - - protected void createButtonsForButtonBar(Composite parent) { - // create OK and Details buttons - createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, true); - createDetailsButton(parent); - } - } - - public static final QualifiedName SUPPRESS_AUTHENTICATION_JOB_MARKER = new QualifiedName(ProvUIActivator.PLUGIN_ID, "SUPPRESS_AUTHENTICATION_REQUESTS"); //$NON-NLS-1$ - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.core.IServiceUI#getUsernamePassword(java.lang.String) - */ - public AuthenticationInfo getUsernamePassword(final String location) { - - final AuthenticationInfo[] result = new AuthenticationInfo[1]; - if (!suppressAuthentication() && !isHeadless()) { - PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { - public void run() { - Shell shell = ProvUI.getDefaultParentShell(); - String message = NLS.bind(ProvUIMessages.ServiceUI_LoginDetails, location); - UserValidationDialog dialog = new UserValidationDialog(shell, ProvUIMessages.ServiceUI_LoginRequired, null, message); - if (dialog.open() == Window.OK) { - result[0] = dialog.getResult(); - } - } - - }); - } - return result[0]; - } - - private boolean suppressAuthentication() { - Job job = Job.getJobManager().currentJob(); - if (job != null) { - return job.getProperty(SUPPRESS_AUTHENTICATION_JOB_MARKER) != null; - } - return false; - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.core.IServiceUI#showCertificates(java.lang.Object) - */ - public TrustInfo getTrustInfo(Certificate[][] untrustedChains, final String[] unsignedDetail) { - boolean trustUnsigned = true; - boolean persistTrust = false; - Certificate[] trusted = new Certificate[0]; - // Some day we may summarize all of this in one UI, or perhaps we'll have a preference to honor regarding - // unsigned content. For now we prompt separately first as to whether unsigned detail should be trusted - if (!isHeadless() && unsignedDetail != null && unsignedDetail.length > 0) { - final boolean[] result = new boolean[] {false}; - PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { - public void run() { - Shell shell = ProvUI.getDefaultParentShell(); - OkCancelErrorDialog dialog = new OkCancelErrorDialog(shell, ProvUIMessages.ServiceUI_warning_title, null, createStatus(), IStatus.WARNING); - result[0] = dialog.open() == IDialogConstants.OK_ID; - } - - private IStatus createStatus() { - MultiStatus parent = new MultiStatus(ProvUIActivator.PLUGIN_ID, 0, ProvUIMessages.ServiceUI_unsigned_message, null); - for (int i = 0; i < unsignedDetail.length; i++) { - parent.add(new Status(IStatus.WARNING, ProvUIActivator.PLUGIN_ID, unsignedDetail[i])); - } - return parent; - } - }); - trustUnsigned = result[0]; - } - // For now, there is no need to show certificates if there was unsigned content and we don't trust it. - if (!trustUnsigned) - return new TrustInfo(trusted, persistTrust, trustUnsigned); - - // We've established trust for unsigned content, now examine the untrusted chains - if (!isHeadless() && untrustedChains != null && untrustedChains.length > 0) { - - final Object[] result = new Object[1]; - final TreeNode[] input = createTreeNodes(untrustedChains); - - PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { - public void run() { - Shell shell = ProvUI.getDefaultParentShell(); - ILabelProvider labelProvider = new CertificateLabelProvider(); - TreeNodeContentProvider contentProvider = new TreeNodeContentProvider(); - TrustCertificateDialog trustCertificateDialog = new TrustCertificateDialog(shell, input, labelProvider, contentProvider); - trustCertificateDialog.open(); - Certificate[] values = new Certificate[trustCertificateDialog.getResult() == null ? 0 : trustCertificateDialog.getResult().length]; - for (int i = 0; i < values.length; i++) { - values[i] = (Certificate) ((TreeNode) trustCertificateDialog.getResult()[i]).getValue(); - } - result[0] = values; - } - }); - persistTrust = true; - trusted = (Certificate[]) result[0]; - } - return new TrustInfo(trusted, persistTrust, trustUnsigned); - } - - private TreeNode[] createTreeNodes(Certificate[][] certificates) { - TreeNode[] children = new TreeNode[certificates.length]; - for (int i = 0; i < certificates.length; i++) { - TreeNode head = new TreeNode(certificates[i][0]); - TreeNode parent = head; - children[i] = head; - for (int j = 0; j < certificates[i].length; j++) { - TreeNode node = new TreeNode(certificates[i][j]); - node.setParent(parent); - parent.setChildren(new TreeNode[] {node}); - parent = node; - } - } - return children; - } - - public AuthenticationInfo getUsernamePassword(final String location, final AuthenticationInfo previousInfo) { - - final AuthenticationInfo[] result = new AuthenticationInfo[1]; - if (!suppressAuthentication() && !isHeadless()) { - PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { - public void run() { - Shell shell = ProvUI.getDefaultParentShell(); - String message = null; - if (previousInfo.saveResult()) - message = NLS.bind(ProvUIMessages.ProvUIMessages_SavedNotAccepted_EnterFor_0, location); - else - message = NLS.bind(ProvUIMessages.ProvUIMessages_NotAccepted_EnterFor_0, location); - - UserValidationDialog dialog = new UserValidationDialog(previousInfo, shell, ProvUIMessages.ServiceUI_LoginRequired, null, message); - if (dialog.open() == Window.OK) { - result[0] = dialog.getResult(); - } - } - - }); - } - return result[0]; - } - - private boolean isHeadless() { - // If there is no UI available and we are still the IServiceUI, - // assume that the operation should proceed. See - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=291049 - return !PlatformUI.isWorkbenchRunning(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ColocatedRepositoryAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ColocatedRepositoryAction.java deleted file mode 100644 index 2dd1e6bcf..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ColocatedRepositoryAction.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.actions; - -import java.net.URI; -import java.util.ArrayList; -import java.util.List; -import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningOperation; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.ui.statushandlers.StatusManager; - -public abstract class ColocatedRepositoryAction extends ProvisioningAction { - - public ColocatedRepositoryAction(String label, String tooltipText, ISelectionProvider selectionProvider) { - super(label, selectionProvider); - setToolTipText(tooltipText); - init(); - } - - public void run() { - ProvisioningOperationRunner.schedule(getOperation(), StatusManager.SHOW | StatusManager.LOG); - } - - protected abstract ProvisioningOperation getOperation(); - - protected URI[] getSelectedLocations(Object[] selectionArray) { - List urls = new ArrayList(); - for (int i = 0; i < selectionArray.length; i++) { - if (selectionArray[i] instanceof MetadataRepositoryElement) - urls.add(((MetadataRepositoryElement) selectionArray[i]).getLocation()); - } - return (URI[]) urls.toArray(new URI[urls.size()]); - } - - protected void checkEnablement(Object[] selectionArray) { - setEnabled(getSelectedLocations(selectionArray).length > 0); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ExistingIUInProfileAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ExistingIUInProfileAction.java deleted file mode 100644 index 7ee6d03cd..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ExistingIUInProfileAction.java +++ /dev/null @@ -1,129 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.actions; - -import org.eclipse.equinox.internal.p2.ui.model.IIUElement; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.model.InstalledIUElement; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.viewers.ISelectionProvider; - -/** - * - * Abstract class that implements the enablement rules for actions that - * affect IU's already in a profile. The action only enables when all of the - * IU's involved are top level IU's from the same profile. - * - * @since 3.5 - * - */ -public abstract class ExistingIUInProfileAction extends ProfileModificationAction { - - private String lastValidatedProfileId; - - public ExistingIUInProfileAction(String label, Policy policy, ISelectionProvider selectionProvider, String profileId) { - super(policy, label, selectionProvider, profileId); - } - - protected boolean isEnabledFor(Object[] selectionArray) { - Object parent = null; - lastValidatedProfileId = null; - // We don't want to prompt for a profile during validation, - // so we only consider the profile id that was set, or the profile - // referred to by the element itself.. - IProfile profile = getProfile(false); - if (selectionArray.length > 0) { - for (int i = 0; i < selectionArray.length; i++) { - if (selectionArray[i] instanceof InstalledIUElement) { - InstalledIUElement element = (InstalledIUElement) selectionArray[i]; - // If we couldn't find a profile in the action itself, check the element's queryable - if (profile == null) { - IQueryable queryable = element.getQueryable(); - if (queryable instanceof IProfile) { - profile = (IProfile) queryable; - lastValidatedProfileId = profile.getProfileId(); - } else - return false; - } - // If the parents are different, then they are either from - // different profiles or are nested in different parts of the tree. - // Either way, this makes the selection invalid. - if (parent == null) { - parent = element.getParent(element); - } else if (parent != element.getParent(element)) { - lastValidatedProfileId = null; - return false; - } - // Now consider the validity of the element on its own - if (!isSelectable(element.getIU(), profile)) - return false; - } else { - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(selectionArray[i], IInstallableUnit.class); - if (iu == null || !isSelectable(iu)) - return false; - } - } - return true; - } - return false; - } - - protected boolean isSelectable(IIUElement element) { - if (!super.isSelectable(element)) - return false; - Object parent = element.getParent(element); - if (parent != null) { - IProfile profile = (IProfile) ProvUI.getAdapter(parent, IProfile.class); - if (profile != null) - return isSelectable(element.getIU(), profile); - } - return false; - } - - protected boolean isSelectable(IInstallableUnit iu) { - if (!super.isSelectable(iu)) - return false; - IProfile profile = getProfile(false); - if (profile != null) { - return isSelectable(iu, profile); - } - return false; - } - - private boolean isSelectable(IInstallableUnit iu, IProfile profile) { - int lock = getLock(profile, iu); - if ((lock & getLockConstant()) == getLockConstant()) - return false; - String propName = getPolicy().getQueryContext().getVisibleInstalledIUProperty(); - if (propName != null && getProfileProperty(profile, iu, propName) == null) { - return false; - } - return true; - } - - /* - * Overridden to consider the profile parent of the elements - * if one was not specified in the actions. - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.actions.ProfileModificationAction#getProfileId(boolean) - */ - protected String getProfileId(boolean chooseProfile) { - if (profileId == null && lastValidatedProfileId != null) - return lastValidatedProfileId; - return super.getProfileId(chooseProfile); - } - - protected abstract int getLockConstant(); -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/InstallAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/InstallAction.java deleted file mode 100644 index df48d34b0..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/InstallAction.java +++ /dev/null @@ -1,158 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.actions; - -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.ui.*; -import org.eclipse.equinox.internal.p2.ui.model.AvailableIUElement; -import org.eclipse.equinox.internal.p2.ui.model.IIUElement; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.PlannerHelper; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.PreselectedIUInstallWizard; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.ProvisioningWizardDialog; -import org.eclipse.equinox.internal.provisional.p2.ui.model.InstalledIUElement; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.wizard.WizardDialog; -import org.eclipse.ui.PlatformUI; - -public class InstallAction extends ProfileModificationAction { - - public static ProfileChangeRequest computeProfileChangeRequest(IInstallableUnit[] ius, String targetProfileId, MultiStatus status, IProgressMonitor monitor) { - ProfileChangeRequest request = ProfileChangeRequest.createByProfileId(targetProfileId); - IProfile profile; - // Now check each individual IU for special cases - try { - profile = ProvisioningUtil.getProfile(targetProfileId); - } catch (ProvisionException e) { - status.add(new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, e.getLocalizedMessage(), e)); - return null; - } - SubMonitor sub = SubMonitor.convert(monitor, ProvUIMessages.ProfileChangeRequestBuildingRequest, ius.length); - for (int i = 0; i < ius.length; i++) { - // If the user is installing a patch, we mark it optional. This allows - // the patched IU to be updated later by removing the patch. - if (Boolean.toString(true).equals(ius[i].getProperty(IInstallableUnit.PROP_TYPE_PATCH))) - request.setInstallableUnitInclusionRules(ius[i], PlannerHelper.createOptionalInclusionRule(ius[i])); - - // Check to see if it is already installed. This may alter the request. - Collector alreadyInstalled = profile.query(new InstallableUnitQuery(ius[i].getId()), new Collector(), null); - // TODO ideally we should only do this check if the iu is a singleton, but in practice many iu's that should - // be singletons are not, so we don't check this (yet) - // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=230878 - if (alreadyInstalled.size() > 0) { // && installedIU.isSingleton() - IInstallableUnit installedIU = (IInstallableUnit) alreadyInstalled.iterator().next(); - int compareTo = ius[i].getVersion().compareTo(installedIU.getVersion()); - // If the iu is a newer version of something already installed, consider this an - // update request - if (compareTo > 0) { - boolean lockedForUpdate = false; - String value = profile.getInstallableUnitProperty(installedIU, IInstallableUnit.PROP_PROFILE_LOCKED_IU); - if (value != null) - lockedForUpdate = (Integer.parseInt(value) & IInstallableUnit.LOCK_UPDATE) == IInstallableUnit.LOCK_UPDATE; - if (lockedForUpdate) { - // Add a status telling the user that this implies an update, but the - // iu should not be updated - status.merge(PlanAnalyzer.getStatus(IStatusCodes.ALTERED_IGNORED_IMPLIED_UPDATE, ius[i])); - } else { - request.addInstallableUnits(new IInstallableUnit[] {ius[i]}); - request.removeInstallableUnits(new IInstallableUnit[] {installedIU}); - // Add a status informing the user that the update has been inferred - status.merge(PlanAnalyzer.getStatus(IStatusCodes.ALTERED_IMPLIED_UPDATE, ius[i])); - // Mark it as a root if it hasn't been already - if (!Boolean.toString(true).equals(profile.getInstallableUnitProperty(installedIU, IInstallableUnit.PROP_PROFILE_ROOT_IU))) - request.setInstallableUnitProfileProperty(ius[i], IInstallableUnit.PROP_PROFILE_ROOT_IU, Boolean.toString(true)); - } - } else if (compareTo < 0) { - // An implied downgrade. We will not put this in the plan, add a status informing the user - status.merge(PlanAnalyzer.getStatus(IStatusCodes.ALTERED_IGNORED_IMPLIED_DOWNGRADE, ius[i])); - } else { - if (Boolean.toString(true).equals(profile.getInstallableUnitProperty(installedIU, IInstallableUnit.PROP_PROFILE_ROOT_IU))) - // It is already a root, nothing to do. We tell the user it was already installed - status.merge(PlanAnalyzer.getStatus(IStatusCodes.ALTERED_IGNORED_ALREADY_INSTALLED, ius[i])); - else { - // It was already installed but not as a root. Tell the user that parts of it are already installed and mark - // it as a root. - status.merge(PlanAnalyzer.getStatus(IStatusCodes.ALTERED_PARTIAL_INSTALL, ius[i])); - request.setInstallableUnitProfileProperty(ius[i], Policy.getDefault().getQueryContext().getVisibleInstalledIUProperty(), Boolean.toString(true)); - } - } - } else { - // Install it and mark as a root - request.addInstallableUnits(new IInstallableUnit[] {ius[i]}); - request.setInstallableUnitProfileProperty(ius[i], Policy.getDefault().getQueryContext().getVisibleInstalledIUProperty(), Boolean.toString(true)); - } - sub.worked(1); - } - sub.done(); - return request; - } - - public InstallAction(Policy policy, ISelectionProvider selectionProvider, String profileId) { - super(policy, ProvUI.INSTALL_COMMAND_LABEL, selectionProvider, profileId); - setToolTipText(ProvUI.INSTALL_COMMAND_TOOLTIP); - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.actions.ProfileModificationAction#isEnabledFor(java.lang.Object[]) - */ - protected boolean isEnabledFor(Object[] selectionArray) { - if (selectionArray.length == 0) - return false; - // We allow non-IU's to be selected at this point, but there - // must be at least one installable unit selected that is - // selectable - for (int i = 0; i < selectionArray.length; i++) { - if (selectionArray[i] instanceof InstalledIUElement && isSelectable((IIUElement) selectionArray[i])) - return true; - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(selectionArray[i], IInstallableUnit.class); - if (iu != null && isSelectable(iu)) - return true; - } - return false; - } - - /* - * Overridden to reject categories and nested IU's (parent is a non-category IU) - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.actions.ProfileModificationAction#isSelectable(org.eclipse.equinox.internal.p2.ui.model.IUElement) - */ - protected boolean isSelectable(IIUElement element) { - return super.isSelectable(element) && !(element.getParent(element) instanceof AvailableIUElement); - } - - protected String getTaskName() { - return ProvUIMessages.InstallIUProgress; - } - - protected int performAction(IInstallableUnit[] ius, String targetProfileId, PlannerResolutionOperation resolution) { - PreselectedIUInstallWizard wizard = new PreselectedIUInstallWizard(getPolicy(), targetProfileId, ius, resolution, new QueryableMetadataRepositoryManager(getPolicy().getQueryContext(), false)); - WizardDialog dialog = new ProvisioningWizardDialog(getShell(), wizard); - dialog.create(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IProvHelpContextIds.INSTALL_WIZARD); - - return dialog.open(); - } - - protected ProfileChangeRequest getProfileChangeRequest(IInstallableUnit[] ius, String targetProfileId, MultiStatus status, IProgressMonitor monitor) { - return computeProfileChangeRequest(ius, targetProfileId, status, monitor); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ProfileModificationAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ProfileModificationAction.java deleted file mode 100644 index 27786ec52..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ProfileModificationAction.java +++ /dev/null @@ -1,304 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.actions; - -import java.util.ArrayList; -import java.util.List; -import org.eclipse.core.runtime.*; -import org.eclipse.core.runtime.jobs.*; -import org.eclipse.equinox.internal.p2.ui.*; -import org.eclipse.equinox.internal.p2.ui.model.CategoryElement; -import org.eclipse.equinox.internal.p2.ui.model.IIUElement; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.window.Window; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.statushandlers.StatusManager; - -public abstract class ProfileModificationAction extends ProvisioningAction { - public static final int ACTION_NOT_RUN = -1; - String profileId; - String userChosenProfileId; - Policy policy; - int result = ACTION_NOT_RUN; - - protected ProfileModificationAction(Policy policy, String text, ISelectionProvider selectionProvider, String profileId) { - super(text, selectionProvider); - this.policy = policy; - this.profileId = profileId; - init(); - } - - public void run() { - // Determine which IUs and which profile are involved - IInstallableUnit[] ius = getSelectedIUs(); - String id = getProfileId(true); - // We could not figure out a profile to operate on, so return - if (id == null || ius.length == 0) { - ProvUI.reportStatus(getNoProfileOrSelectionStatus(profileId, ius), StatusManager.BLOCK); - runCanceled(); - return; - } - run(ius, id); - } - - protected IStatus getNoProfileOrSelectionStatus(String id, IInstallableUnit[] ius) { - return new Status(IStatus.WARNING, ProvUIActivator.PLUGIN_ID, NLS.bind(ProvUIMessages.ProfileModificationAction_InvalidSelections, id, new Integer(ius.length))); - } - - protected void run(final IInstallableUnit[] ius, final String id) { - // Get a profile change request. Supply a multi-status so that information - // about the request can be provided along the way. - final MultiStatus additionalStatus = getProfileChangeAlteredStatus(); - final ProfileChangeRequest[] request = new ProfileChangeRequest[1]; - // TODO even getting a profile change request can be expensive - // when updating, because we are looking for updates. For now, most - // clients work around this by preloading repositories in a job. - // Consider something different here. We'll pass a fake progress monitor - // into the profile change request method so that later we can do - // something better here. - BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { - public void run() { - request[0] = getProfileChangeRequest(ius, id, additionalStatus, new NullProgressMonitor()); - } - }); - // If we couldn't build a request, then report an error and bail. - // Hopefully the provider of the request gave an explanation in the status. - if (request[0] == null) { - IStatus failureStatus; - if (additionalStatus.getChildren().length > 0) { - if (additionalStatus.getChildren().length == 1) - failureStatus = additionalStatus.getChildren()[0]; - else { - MultiStatus nullRequestStatus = new MultiStatus(ProvUIActivator.PLUGIN_ID, IStatusCodes.UNEXPECTED_NOTHING_TO_DO, additionalStatus.getChildren(), ProvUIMessages.ProfileModificationAction_NoChangeRequestProvided, null); - nullRequestStatus.addAll(additionalStatus); - failureStatus = nullRequestStatus; - } - } else { - // No explanation for failure was provided. It shouldn't happen, but... - failureStatus = new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProfileModificationAction_NoExplanationProvided); - } - ProvUI.reportStatus(failureStatus, StatusManager.SHOW | StatusManager.LOG); - runCanceled(); - return; - } - // We have a profile change request, let's get a plan for it. This could take awhile. - final PlannerResolutionOperation operation = new PlannerResolutionOperation(ProvUIMessages.ProfileModificationAction_ResolutionOperationLabel, id, request[0], null, additionalStatus, isResolveUserVisible()); - // Since we are resolving asynchronously, our job is done. Setting this allows - // callers to decide to close the launching window. - // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=236495 - result = Window.OK; - Job job = ProvisioningOperationRunner.schedule(operation, StatusManager.SHOW); - job.addJobChangeListener(new JobChangeAdapter() { - public void done(IJobChangeEvent event) { - // Do we have a plan?? - final ProvisioningPlan plan = operation.getProvisioningPlan(); - if (plan != null) { - if (PlatformUI.isWorkbenchRunning()) { - PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { - public void run() { - if (validatePlan(plan)) - performAction(ius, getProfileId(true), operation); - userChosenProfileId = null; - } - }); - } - } - } - }); - } - - /** - * Get the integer return code returned by any wizards launched by this - * action. If the action has not been run, return ACTION_NOT_RUN. If the - * action does not open a wizard, return Window.OK if the operation was performed, - * and Window.CANCEL if it was canceled. - * - * @return integer return code - */ - public int getReturnCode() { - return result; - } - - /** - * Validate the plan and return true if the operation should - * be performed with plan. Report any errors to the user before returning false. - * @param plan - * @return a boolean indicating whether the plan should be used in a - * provisioning operation. - */ - protected boolean validatePlan(ProvisioningPlan plan) { - if (plan != null) { - // Don't validate the plan if the user cancelled - if (plan.getStatus().getSeverity() == IStatus.CANCEL) - return false; - if (getPlanValidator() != null) - return getPlanValidator().continueWorkingWithPlan(plan, getShell()); - if (plan.getStatus().isOK()) - return true; - ProvUI.reportStatus(plan.getStatus(), StatusManager.BLOCK | StatusManager.LOG); - return false; - } - return false; - } - - /* - * Get a provisioning plan for this action. - */ - protected abstract ProfileChangeRequest getProfileChangeRequest(IInstallableUnit[] ius, String targetProfileId, MultiStatus status, IProgressMonitor monitor); - - protected abstract int performAction(IInstallableUnit[] ius, String targetProfileId, PlannerResolutionOperation resolution); - - protected abstract String getTaskName(); - - protected IInstallableUnit getIU(Object element) { - return (IInstallableUnit) ProvUI.getAdapter(element, IInstallableUnit.class); - - } - - /** - * Return an array of the selected and valid installable units. - * The number of IInstallableUnits in the array may be different than - * the actual number of selections in the action's selection provider. - * That is, if the action is disabled due to invalid selections, - * this method will return those selections that were valid. - * - * @return an array of selected IInstallableUnit that meet the - * enablement criteria for the action. - */ - protected IInstallableUnit[] getSelectedIUs() { - List elements = getStructuredSelection().toList(); - List iusList = new ArrayList(elements.size()); - - for (int i = 0; i < elements.size(); i++) { - if (elements.get(i) instanceof IIUElement) { - IIUElement element = (IIUElement) elements.get(i); - if (isSelectable(element)) - iusList.add(getIU(element)); - } else { - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(elements.get(i), IInstallableUnit.class); - if (iu != null && isSelectable(iu)) - iusList.add(iu); - } - } - return (IInstallableUnit[]) iusList.toArray(new IInstallableUnit[iusList.size()]); - } - - protected boolean isSelectable(IIUElement element) { - return !(element instanceof CategoryElement); - } - - protected boolean isSelectable(IInstallableUnit iu) { - return !ProvisioningUtil.isCategory(iu); - } - - protected LicenseManager getLicenseManager() { - return policy.getLicenseManager(); - } - - protected QueryProvider getQueryProvider() { - return policy.getQueryProvider(); - } - - protected PlanValidator getPlanValidator() { - return policy.getPlanValidator(); - } - - protected IProfileChooser getProfileChooser() { - return policy.getProfileChooser(); - } - - protected Policy getPolicy() { - return policy; - } - - protected final void checkEnablement(Object[] selections) { - if (isEnabledFor(selections)) { - String id = getProfileId(false); - if (id == null) - setEnabled(true); - else - setEnabled(!ProvisioningOperationRunner.hasScheduledOperationsFor(id)); - } else - setEnabled(false); - } - - protected abstract boolean isEnabledFor(Object[] selections); - - protected int getLock(IProfile profile, IInstallableUnit iu) { - if (profile == null) - return IInstallableUnit.LOCK_NONE; - try { - String value = profile.getInstallableUnitProperty(iu, IInstallableUnit.PROP_PROFILE_LOCKED_IU); - if (value != null) - return Integer.parseInt(value); - } catch (NumberFormatException e) { - // ignore and assume no lock - } - return IInstallableUnit.LOCK_NONE; - } - - protected String getProfileProperty(IProfile profile, IInstallableUnit iu, String propertyName) { - if (profile == null || iu == null) - return null; - return profile.getInstallableUnitProperty(iu, propertyName); - } - - protected IProfile getProfile(boolean chooseProfile) { - try { - String id = getProfileId(chooseProfile); - if (id == null) - return null; - return ProvisioningUtil.getProfile(id); - } catch (ProvisionException e) { - // ignore, we have bigger problems to report elsewhere - } - return null; - } - - protected String getProfileId(boolean chooseProfile) { - if (profileId != null) - return profileId; - if (userChosenProfileId != null) - return userChosenProfileId; - if (chooseProfile && getProfileChooser() != null) { - userChosenProfileId = getProfileChooser().getProfileId(getShell()); - return userChosenProfileId; - } - return null; - } - - private void runCanceled() { - // The action was canceled, do any cleanup needed before - // it is run again. - userChosenProfileId = null; - result = Window.CANCEL; - } - - protected MultiStatus getProfileChangeAlteredStatus() { - return PlanAnalyzer.getProfileChangeAlteredStatus(); - } - - protected boolean isResolveUserVisible() { - return true; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/PropertyDialogAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/PropertyDialogAction.java deleted file mode 100644 index 917fd0253..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/PropertyDialogAction.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.actions; - -import org.eclipse.jface.viewers.*; -import org.eclipse.jface.window.IShellProvider; - -/** - * PropertyDialogAction which sets its enablement on construction. - * - * @since 3.4 - * - */ - -public class PropertyDialogAction extends org.eclipse.ui.dialogs.PropertyDialogAction { - public PropertyDialogAction(IShellProvider shell, ISelectionProvider provider) { - super(shell, provider); - // prime the selection validation - ISelection selection = provider.getSelection(); - if (selection instanceof IStructuredSelection) { - selectionChanged((IStructuredSelection) selection); - } else { - selectionChanged(selection); - } - - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ProvisioningAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ProvisioningAction.java deleted file mode 100644 index 315116440..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/ProvisioningAction.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.actions; - -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.jface.viewers.*; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.actions.SelectionProviderAction; - -public abstract class ProvisioningAction extends SelectionProviderAction { - - protected ProvisioningAction(String text, ISelectionProvider selectionProvider) { - super(selectionProvider, text); - } - - /* - * perform initialization that should be done after creation. - */ - protected void init() { - // prime the selection validation - ISelection selection = getSelection(); - if (selection instanceof IStructuredSelection) { - selectionChanged((IStructuredSelection) selection); - } else { - selectionChanged(selection); - } - } - - protected Shell getShell() { - return ProvUI.getDefaultParentShell(); - } - - /* - * Overridden to use the selection from the selection provider, not the one - * from the triggering event. Some selection providers reinterpret the raw selections - * (non-Javadoc) - * @see org.eclipse.ui.actions.SelectionProviderAction#selectionChanged(org.eclipse.jface.viewers.IStructuredSelection) - */ - public final void selectionChanged(IStructuredSelection selection) { - ISelection providerSelection = getSelectionProvider().getSelection(); - if (providerSelection instanceof IStructuredSelection) { - checkEnablement(((IStructuredSelection) providerSelection).toArray()); - } else { - // shouldn't really happen, but a provider could decide to de-structure the selection - selectionChanged(providerSelection); - } - } - - protected void checkEnablement(Object[] selections) { - // Default is to nothing - } - - /** - * Recheck the enablement. Called by clients when some condition outside of - * the action that may effect its enablement should be changed. - */ - public final void checkEnablement() { - ISelection selection = getSelection(); - if (selection instanceof IStructuredSelection) { - checkEnablement(((IStructuredSelection) selection).toArray()); - } else { - selectionChanged(selection); - } - } -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/RefreshAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/RefreshAction.java deleted file mode 100644 index 95d52276c..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/RefreshAction.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - ******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.actions; - -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.KeyAdapter; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.widgets.Control; - -/** - * @since 3.4 - * - */ -public abstract class RefreshAction extends ProvisioningAction { - - /** - */ - public RefreshAction(ISelectionProvider selectionProvider, Control control) { - super(ProvUIMessages.RefreshAction_Label, selectionProvider); - setToolTipText(ProvUIMessages.RefreshAction_Tooltip); - hookKeyListener(control); - init(); - } - - private void hookKeyListener(Control control) { - control.addKeyListener(new KeyAdapter() { - public void keyReleased(KeyEvent e) { - handleKeyReleased(e); - } - }); - } - - public void run() { - refresh(); - } - - protected abstract void refresh(); - - /** - * Handle a key released event. Used internally and also - * made available so that clients can watch key events from - * any other controls and dispatch to this action. - * - * @param event the key event - */ - public void handleKeyReleased(KeyEvent event) { - if (event.keyCode == SWT.F5 && event.stateMask == 0) { - refresh(); - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/RemoveColocatedRepositoryAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/RemoveColocatedRepositoryAction.java deleted file mode 100644 index 00e008ce6..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/RemoveColocatedRepositoryAction.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.actions; - -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.RemoveColocatedRepositoryOperation; -import org.eclipse.jface.viewers.ISelectionProvider; - -public class RemoveColocatedRepositoryAction extends ColocatedRepositoryAction { - - public RemoveColocatedRepositoryAction(ISelectionProvider selectionProvider) { - super(ProvUIMessages.RemoveColocatedRepositoryAction_Label, ProvUIMessages.RemoveColocatedRepositoryAction_Tooltip, selectionProvider); - - } - - protected ProvisioningOperation getOperation() { - return new RemoveColocatedRepositoryOperation(ProvUIMessages.RemoveColocatedRepositoryAction_OperationLabel, getSelectedLocations(getStructuredSelection().toArray())); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/UninstallAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/UninstallAction.java deleted file mode 100644 index b832abab8..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/UninstallAction.java +++ /dev/null @@ -1,73 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.actions; - -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.IProvHelpContextIds; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.ProvisioningWizardDialog; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.UninstallWizard; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.wizard.WizardDialog; -import org.eclipse.ui.PlatformUI; - -public class UninstallAction extends ExistingIUInProfileAction { - - public UninstallAction(Policy policy, ISelectionProvider selectionProvider, String profileId) { - super(ProvUI.UNINSTALL_COMMAND_LABEL, policy, selectionProvider, profileId); - setToolTipText(ProvUI.UNINSTALL_COMMAND_TOOLTIP); - } - - protected String getTaskName() { - return ProvUIMessages.UninstallIUProgress; - } - - protected int performAction(IInstallableUnit[] ius, String targetProfileId, PlannerResolutionOperation resolution) { - UninstallWizard wizard = new UninstallWizard(getPolicy(), targetProfileId, ius, resolution); - WizardDialog dialog = new ProvisioningWizardDialog(getShell(), wizard); - dialog.create(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IProvHelpContextIds.UNINSTALL_WIZARD); - - return dialog.open(); - } - - protected ProfileChangeRequest getProfileChangeRequest(IInstallableUnit[] ius, String targetProfileId, MultiStatus status, IProgressMonitor monitor) { - SubMonitor sub = SubMonitor.convert(monitor, ProvUIMessages.ProfileChangeRequestBuildingRequest, 1); - ProfileChangeRequest request = null; - try { - request = ProfileChangeRequest.createByProfileId(targetProfileId); - request.removeInstallableUnits(ius); - // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=255984 - // We ask to remove the the profile root property in addition to removing the IU. In theory this - // should be redundant, but there are cases where the planner decides not to uninstall something because - // it is needed by others. We still want to remove the root in this case. - String key = getPolicy().getQueryContext().getVisibleInstalledIUProperty(); - for (int i = 0; i < ius.length; i++) - request.removeInstallableUnitProfileProperty(ius[i], key); - } finally { - sub.done(); - } - return request; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.actions.AlterExistingProfileIUAction#getLockConstant() - */ - protected int getLockConstant() { - return IInstallableUnit.LOCK_UNINSTALL; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/UpdateAction.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/UpdateAction.java deleted file mode 100644 index 8a7a6f50d..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/actions/UpdateAction.java +++ /dev/null @@ -1,99 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.actions; - -import java.util.ArrayList; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.ui.PlanAnalyzer; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.ProvisioningWizardDialog; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.UpdateWizard; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.wizard.WizardDialog; -import org.eclipse.ui.PlatformUI; - -public class UpdateAction extends ExistingIUInProfileAction { - - protected IUElementListRoot root; // root that will be used to seed the wizard - protected ArrayList initialSelections; // the elements that should be selected in the wizard - boolean resolveIsVisible = true; - QueryableMetadataRepositoryManager manager; - boolean skipSelectionPage = false; - - public UpdateAction(Policy policy, ISelectionProvider selectionProvider, String profileId, boolean resolveIsVisible) { - super(ProvUI.UPDATE_COMMAND_LABEL, policy, selectionProvider, profileId); - setToolTipText(ProvUI.UPDATE_COMMAND_TOOLTIP); - this.resolveIsVisible = resolveIsVisible; - } - - public void setRepositoryManager(QueryableMetadataRepositoryManager manager) { - this.manager = manager; - } - - public void setSkipSelectionPage(boolean skipSelectionPage) { - this.skipSelectionPage = skipSelectionPage; - } - - protected int performAction(IInstallableUnit[] ius, String targetProfileId, PlannerResolutionOperation resolution) { - // Caches should have been created while formulating the plan - Assert.isNotNull(initialSelections); - Assert.isNotNull(root); - Assert.isNotNull(resolution); - - UpdateWizard wizard = new UpdateWizard(getPolicy(), targetProfileId, root, initialSelections.toArray(), resolution, manager); - wizard.setSkipSelectionsPage(skipSelectionPage); - WizardDialog dialog = new ProvisioningWizardDialog(getShell(), wizard); - dialog.create(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IProvHelpContextIds.UPDATE_WIZARD); - - return dialog.open(); - } - - protected ProfileChangeRequest getProfileChangeRequest(IInstallableUnit[] ius, String targetProfileId, MultiStatus status, IProgressMonitor monitor) { - initialSelections = new ArrayList(); - root = new IUElementListRoot(); - ProfileChangeRequest request = UpdateWizard.createProfileChangeRequest(ius, targetProfileId, root, initialSelections, monitor); - if (request == null) { - status.add(PlanAnalyzer.getStatus(IStatusCodes.NOTHING_TO_UPDATE, null)); - return null; - } - - return request; - } - - protected String getTaskName() { - return ProvUIMessages.UpdateIUProgress; - } - - protected boolean isResolveUserVisible() { - return resolveIsVisible; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.actions.AlterExistingProfileIUAction#getLockConstant() - */ - protected int getLockConstant() { - return IInstallableUnit.LOCK_UPDATE; - } - - protected IStatus getNoProfileOrSelectionStatus(String id, IInstallableUnit[] ius) { - if (ius.length == 0) - return PlanAnalyzer.getStatus(IStatusCodes.NOTHING_TO_UPDATE, null); - return super.getNoProfileOrSelectionStatus(id, ius); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/AcceptLicensesWizardPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/AcceptLicensesWizardPage.java deleted file mode 100644 index 18aee0de3..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/AcceptLicensesWizardPage.java +++ /dev/null @@ -1,418 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import java.util.*; -import java.util.List; -import org.eclipse.equinox.internal.p2.metadata.License; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.dialogs.ILayoutConstants; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.InstallableUnitOperand; -import org.eclipse.equinox.internal.provisional.p2.engine.Operand; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.ILicense; -import org.eclipse.equinox.internal.provisional.p2.ui.IUPropertyUtils; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.IUColumnConfig; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogSettings; -import org.eclipse.jface.viewers.*; -import org.eclipse.jface.wizard.WizardPage; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.*; - -/** - * AcceptLicensesWizardPage shows a list of the IU's that have - * licenses that have not been approved by the user. - * - * @since 3.4 - */ -public class AcceptLicensesWizardPage extends WizardPage { - private static final String DIALOG_SETTINGS_SECTION = "LicensessPage"; //$NON-NLS-1$ - private static final String LIST_WEIGHT = "ListSashWeight"; //$NON-NLS-1$ - private static final String LICENSE_WEIGHT = "LicenseSashWeight"; //$NON-NLS-1$ - private static final String NAME_COLUMN_WIDTH = "NameColumnWidth"; //$NON-NLS-1$ - private static final String VERSION_COLUMN_WIDTH = "VersionColumnWidth"; //$NON-NLS-1$ - - class LicenseContentProvider implements ITreeContentProvider { - public Object[] getChildren(Object parentElement) { - if (licensesToIUs.containsKey(parentElement)) - return ((ArrayList) licensesToIUs.get(parentElement)).toArray(); - return null; - } - - public Object getParent(Object element) { - return null; - } - - public boolean hasChildren(Object element) { - return licensesToIUs.containsKey(element); - } - - public Object[] getElements(Object inputElement) { - return licensesToIUs.keySet().toArray(); - } - - public void dispose() { - // Nothing to do - } - - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - // Nothing to do - } - } - - class LicenseLabelProvider extends LabelProvider { - public Image getImage(Object element) { - return null; - } - - public String getText(Object element) { - if (element instanceof License) { - return getFirstLine(((License) element).getBody()); - } else if (element instanceof IInstallableUnit) { - return getIUName((IInstallableUnit) element); - } - return ""; //$NON-NLS-1$ - } - - private String getFirstLine(String body) { - int i = body.indexOf('\n'); - int j = body.indexOf('\r'); - if (i > 0) { - if (j > 0) - return body.substring(0, i < j ? i : j); - return body.substring(0, i); - } else if (j > 0) { - return body.substring(0, j); - } - return body; - } - } - - TreeViewer iuViewer; - Text licenseTextBox; - Button acceptButton; - Button declineButton; - SashForm sashForm; - private IInstallableUnit[] originalIUs; - HashMap licensesToIUs; // License -> IU Name - private Policy policy; - IUColumnConfig nameColumn; - IUColumnConfig versionColumn; - - static String getIUName(IInstallableUnit iu) { - StringBuffer buf = new StringBuffer(); - String name = IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_NAME); - if (name != null) - buf.append(name); - else - buf.append(iu.getId()); - buf.append(" "); //$NON-NLS-1$ - buf.append(iu.getVersion().toString()); - return buf.toString(); - } - - public AcceptLicensesWizardPage(Policy policy, IInstallableUnit[] ius, ProvisioningPlan plan) { - super("AcceptLicenses"); //$NON-NLS-1$ - setTitle(ProvUIMessages.AcceptLicensesWizardPage_Title); - this.policy = policy; - update(ius, plan); - } - - public void createControl(Composite parent) { - initializeDialogUnits(parent); - ArrayList ius; - if (licensesToIUs == null || licensesToIUs.size() == 0) { - Label label = new Label(parent, SWT.NONE); - setControl(label); - } else if (licensesToIUs.size() == 1 && (ius = (ArrayList) (licensesToIUs.values().iterator().next())).size() == 1) { - createLicenseContentSection(parent, (IInstallableUnit) ius.get(0)); - } else { - sashForm = new SashForm(parent, SWT.HORIZONTAL); - sashForm.setLayout(new GridLayout()); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - sashForm.setLayoutData(gd); - - createLicenseListSection(sashForm); - createLicenseContentSection(sashForm, null); - sashForm.setWeights(getSashWeights()); - setControl(sashForm); - } - Dialog.applyDialogFont(getControl()); - } - - private void createLicenseListSection(Composite parent) { - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - composite.setLayout(layout); - GridData gd = new GridData(GridData.FILL_BOTH); - composite.setLayoutData(gd); - - Label label = new Label(composite, SWT.NONE); - label.setText(ProvUIMessages.AcceptLicensesWizardPage_ItemsLabel); - iuViewer = new TreeViewer(composite, SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); - iuViewer.setContentProvider(new LicenseContentProvider()); - iuViewer.setLabelProvider(new LicenseLabelProvider()); - iuViewer.setComparator(new ViewerComparator()); - iuViewer.setInput(licensesToIUs); - - iuViewer.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - handleSelectionChanged((IStructuredSelection) event.getSelection()); - } - - }); - gd = new GridData(GridData.FILL_BOTH); - gd.widthHint = convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_PRIMARY_COLUMN_WIDTH); - gd.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_HEIGHT); - iuViewer.getControl().setLayoutData(gd); - } - - private void createLicenseAcceptSection(Composite parent, boolean multiple) { - // Buttons for accepting licenses - Composite buttonContainer = new Composite(parent, SWT.NULL); - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - buttonContainer.setLayout(new GridLayout()); - buttonContainer.setLayoutData(gd); - - acceptButton = new Button(buttonContainer, SWT.RADIO); - if (multiple) - acceptButton.setText(ProvUIMessages.AcceptLicensesWizardPage_AcceptMultiple); - else - acceptButton.setText(ProvUIMessages.AcceptLicensesWizardPage_AcceptSingle); - - acceptButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - setPageComplete(acceptButton.getSelection()); - } - }); - declineButton = new Button(buttonContainer, SWT.RADIO); - if (multiple) - declineButton.setText(ProvUIMessages.AcceptLicensesWizardPage_RejectMultiple); - else - declineButton.setText(ProvUIMessages.AcceptLicensesWizardPage_RejectSingle); - declineButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - setPageComplete(!declineButton.getSelection()); - } - }); - - acceptButton.setSelection(false); - declineButton.setSelection(true); - } - - private void createLicenseContentSection(Composite parent, IInstallableUnit singleIU) { - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - composite.setLayout(layout); - GridData gd = new GridData(GridData.FILL_BOTH); - composite.setLayoutData(gd); - - Label label = new Label(composite, SWT.NONE); - if (singleIU == null) - label.setText(ProvUIMessages.AcceptLicensesWizardPage_LicenseTextLabel); - else - label.setText(NLS.bind(ProvUIMessages.AcceptLicensesWizardPage_SingleLicenseTextLabel, getIUName(singleIU))); - licenseTextBox = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.WRAP | SWT.READ_ONLY); - licenseTextBox.setBackground(licenseTextBox.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); - initializeDialogUnits(licenseTextBox); - gd = new GridData(SWT.FILL, SWT.FILL, true, true); - gd.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_HEIGHT); - gd.widthHint = convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_COLUMN_WIDTH); - licenseTextBox.setLayoutData(gd); - - createLicenseAcceptSection(composite, licensesToIUs.size() > 1); - - if (singleIU != null) { - licenseTextBox.setText(getLicenseBody(singleIU)); - setControl(composite); - } - } - - void handleSelectionChanged(IStructuredSelection selection) { - if (!selection.isEmpty()) { - Object selected = selection.getFirstElement(); - if (selected instanceof License) - licenseTextBox.setText(((License) selected).getBody()); - else if (selected instanceof IInstallableUnit) - licenseTextBox.setText(getLicenseBody((IInstallableUnit) selected)); - } - } - - public boolean performFinish() { - rememberAcceptedLicenses(); - return true; - } - - public boolean hasLicensesToAccept() { - return licensesToIUs != null && licensesToIUs.size() > 0; - } - - public void update(IInstallableUnit[] theIUs, ProvisioningPlan currentPlan) { - this.originalIUs = theIUs; - if (theIUs == null) - licensesToIUs = new HashMap(); - else - findUnacceptedLicenses(theIUs, currentPlan); - setDescription(); - setPageComplete(licensesToIUs.size() == 0); - if (getControl() != null) { - Composite parent = getControl().getParent(); - getControl().dispose(); - createControl(parent); - parent.layout(true); - } - } - - private String getLicenseBody(IInstallableUnit iu) { - ILicense license = IUPropertyUtils.getLicense(iu); - if (license != null && license.getBody() != null) - return license.getBody(); - // shouldn't happen because we already reduced the list to those - // that have licenses and bodies are required. - return ""; //$NON-NLS-1$ - } - - private void findUnacceptedLicenses(IInstallableUnit[] selectedIUs, ProvisioningPlan currentPlan) { - IInstallableUnit[] iusToCheck; - if (currentPlan == null) - iusToCheck = selectedIUs; - else { - List allIUs = new ArrayList(); - Operand[] operands = currentPlan.getOperands(); - for (int i = 0; i < operands.length; i++) - if (operands[i] instanceof InstallableUnitOperand) { - IInstallableUnit addedIU = ((InstallableUnitOperand) operands[i]).second(); - if (addedIU != null) - allIUs.add(addedIU); - } - iusToCheck = (IInstallableUnit[]) allIUs.toArray(new IInstallableUnit[allIUs.size()]); - } - - // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=218532 - // Current metadata generation can result with a feature group IU and the feature jar IU - // having the same name and license. We will weed out duplicates if the license and name are both - // the same. - licensesToIUs = new HashMap();//map of License->ArrayList of IUs with that license - HashMap namesSeen = new HashMap(); // map of License->HashSet of names with that license - for (int i = 0; i < iusToCheck.length; i++) { - IInstallableUnit iu = iusToCheck[i]; - ILicense license = IUPropertyUtils.getLicense(iu); - // It has a license, is it already accepted? - if (license != null) { - if (!policy.getLicenseManager().isAccepted(iu)) { - String name = IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_NAME); - if (name == null) - name = iu.getId(); - // Have we already found this license? - if (licensesToIUs.containsKey(license)) { - HashSet names = (HashSet) namesSeen.get(license); - if (!names.contains(name)) { - names.add(name); - ((ArrayList) licensesToIUs.get(license)).add(iu); - } - } else { - ArrayList list = new ArrayList(1); - list.add(iu); - licensesToIUs.put(license, list); - HashSet names = new HashSet(1); - names.add(name); - namesSeen.put(license, names); - } - } - } - } - } - - private void rememberAcceptedLicenses() { - if (licensesToIUs == null) - return; - Iterator iter = licensesToIUs.keySet().iterator(); - while (iter.hasNext()) { - License license = (License) iter.next(); - ArrayList iusWithThisLicense = (ArrayList) licensesToIUs.get(license); - for (int i = 0; i < iusWithThisLicense.size(); i++) - policy.getLicenseManager().accept((IInstallableUnit) iusWithThisLicense.get(i)); - } - } - - private void setDescription() { - // No licenses but the page is open. Shouldn't happen, but just in case... - if (licensesToIUs == null || licensesToIUs.size() == 0) - setDescription(ProvUIMessages.AcceptLicensesWizardPage_NoLicensesDescription); - // We have licenses. Use a generic message if we think we aren't showing extra - // licenses from required IU's. This check is not entirely accurate, for example - // one root IU could have no license and the next one has two different - // IU's with different licenses. But this cheaply catches the common cases. - else if (licensesToIUs.size() <= originalIUs.length) - setDescription(ProvUIMessages.AcceptLicensesWizardPage_ReviewLicensesDescription); - else { - // Without a doubt we know we are showing extra licenses. - setDescription(ProvUIMessages.AcceptLicensesWizardPage_ReviewExtraLicensesDescription); - } - } - - private String getDialogSettingsName() { - return getWizard().getClass().getName() + "." + DIALOG_SETTINGS_SECTION; //$NON-NLS-1$ - } - - public void saveBoundsRelatedSettings() { - if (iuViewer == null || iuViewer.getTree().isDisposed()) - return; - IDialogSettings settings = ProvUIActivator.getDefault().getDialogSettings(); - IDialogSettings section = settings.getSection(getDialogSettingsName()); - if (section == null) { - section = settings.addNewSection(getDialogSettingsName()); - } - section.put(NAME_COLUMN_WIDTH, iuViewer.getTree().getColumn(0).getWidth()); - section.put(VERSION_COLUMN_WIDTH, iuViewer.getTree().getColumn(1).getWidth()); - - if (sashForm == null || sashForm.isDisposed()) - return; - int[] weights = sashForm.getWeights(); - section.put(LIST_WEIGHT, weights[0]); - section.put(LICENSE_WEIGHT, weights[1]); - } - - private int[] getSashWeights() { - IDialogSettings settings = ProvUIActivator.getDefault().getDialogSettings(); - IDialogSettings section = settings.getSection(getDialogSettingsName()); - if (section != null) { - try { - int[] weights = new int[2]; - if (section.get(LIST_WEIGHT) != null) { - weights[0] = section.getInt(LIST_WEIGHT); - if (section.get(LICENSE_WEIGHT) != null) { - weights[1] = section.getInt(LICENSE_WEIGHT); - return weights; - } - } - } catch (NumberFormatException e) { - // Ignore if there actually was a value that didn't parse. - } - } - return new int[] {55, 45}; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/AddRepositoryDialog.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/AddRepositoryDialog.java deleted file mode 100644 index a659f749c..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/AddRepositoryDialog.java +++ /dev/null @@ -1,163 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import java.net.URI; -import java.net.URISyntaxException; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.p2.repository.helpers.RepositoryHelper; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.dialogs.RepositoryNameAndLocationDialog; -import org.eclipse.equinox.internal.provisional.p2.ui.IProvHelpContextIds; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.AddRepositoryOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.*; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.statushandlers.StatusManager; - -/** - * Abstract dialog class for adding repositories of different types. This class - * assumes the user view of a repository is a name and URI. Individual subclasses - * will dictate what kind of repository and how it's created. - * - * @since 3.4 - * - */ -public abstract class AddRepositoryDialog extends RepositoryNameAndLocationDialog { - - Button okButton; - Text url, nickname; - URI addedLocation; - static final String[] ARCHIVE_EXTENSIONS = new String[] {"*.jar;*.zip"}; //$NON-NLS-1$ - static String lastLocalLocation = null; - static String lastArchiveLocation = null; - Policy policy; - - public AddRepositoryDialog(Shell parentShell, Policy policy) { - super(parentShell, policy); - setTitle(ProvUIMessages.AddRepositoryDialog_Title); - PlatformUI.getWorkbench().getHelpSystem().setHelp(parentShell, IProvHelpContextIds.ADD_REPOSITORY_DIALOG); - } - - protected Control createDialogArea(Composite parent) { - Composite comp = new Composite(parent, SWT.NONE); - initializeDialogUnits(comp); - GridLayout layout = new GridLayout(); - layout.numColumns = 3; - layout.marginTop = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - - comp.setLayout(layout); - GridData data = new GridData(); - comp.setLayoutData(data); - - // Name: [] - nickname = createNameField(comp); - - Button localButton = new Button(comp, SWT.PUSH); - localButton.setText(ProvUIMessages.RepositoryGroup_LocalRepoBrowseButton); - localButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.APPLICATION_MODAL); - dialog.setMessage(ProvUIMessages.RepositoryGroup_SelectRepositoryDirectory); - dialog.setFilterPath(lastLocalLocation); - String path = dialog.open(); - if (path != null) { - lastLocalLocation = path; - url.setText(makeLocalURIString(path)); - validateRepositoryURL(false); - } - } - }); - setButtonLayoutData(localButton); - - // Location: [] - url = createLocationField(comp); - - Button archiveButton = new Button(comp, SWT.PUSH); - archiveButton.setText(ProvUIMessages.RepositoryGroup_ArchivedRepoBrowseButton); - archiveButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - FileDialog dialog = new FileDialog(getShell(), SWT.APPLICATION_MODAL); - dialog.setText(ProvUIMessages.RepositoryGroup_RepositoryFile); - dialog.setFilterExtensions(ARCHIVE_EXTENSIONS); - dialog.setFileName(lastArchiveLocation); - String path = dialog.open(); - if (path != null) { - lastArchiveLocation = path; - url.setText(makeLocalURIString(path)); - validateRepositoryURL(false); - } - } - }); - setButtonLayoutData(archiveButton); - comp.setTabList(new Control[] {nickname, url, localButton, archiveButton}); - Dialog.applyDialogFont(comp); - return comp; - } - - String makeLocalURIString(String path) { - try { - URI localURI = URIUtil.fromString(path); - return URIUtil.toUnencodedString(RepositoryHelper.localRepoURIHelper(localURI)); - } catch (URISyntaxException e) { - return path; - } - } - - protected boolean handleOk() { - IStatus status = addRepository(); - return status.isOK(); - } - - /** - * Get the location of the repository that was added by this dialog. Return null - * if the dialog has not yet added a repository location. - * - * @return the location of the repository that has been added by this dialog, or null - * if no repository has been added. - */ - public URI getAddedLocation() { - return addedLocation; - } - - protected IStatus addRepository() { - IStatus status = validateRepositoryURL(false); - if (status.isOK()) { - addedLocation = getUserLocation(); - AddRepositoryOperation op = getOperation(addedLocation); - String nick = nickname.getText().trim(); - if (nick.length() > 0) - op.setNicknames(new String[] {nick}); - ProvisioningOperationRunner.schedule(op, StatusManager.SHOW | StatusManager.LOG); - } - return status; - } - - /** - * Get an add operation appropriate for this dialog. The default behavior - * is to retrieve it from the policy, but subclasses may override. - * - * @param repositoryLocation to be added - * @return the add operation - */ - protected AddRepositoryOperation getOperation(URI repositoryLocation) { - return getRepositoryManipulator().getAddOperation(repositoryLocation); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/AvailableIUGroup.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/AvailableIUGroup.java deleted file mode 100644 index 3dfae1d29..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/AvailableIUGroup.java +++ /dev/null @@ -1,481 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import java.net.URI; -import java.util.ArrayList; -import org.eclipse.core.runtime.*; -import org.eclipse.core.runtime.jobs.*; -import org.eclipse.equinox.internal.p2.ui.*; -import org.eclipse.equinox.internal.p2.ui.dialogs.*; -import org.eclipse.equinox.internal.p2.ui.model.*; -import org.eclipse.equinox.internal.p2.ui.viewers.DeferredQueryContentProvider; -import org.eclipse.equinox.internal.p2.ui.viewers.IUDetailsLabelProvider; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IRepositoryElement; -import org.eclipse.equinox.internal.provisional.p2.ui.model.MetadataRepositories; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.IUViewQueryContext; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.*; -import org.eclipse.jface.viewers.*; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.swt.events.*; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.widgets.*; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.PlatformUI; - -/** - * An AvailableIUGroup is a reusable UI component that displays the - * IU's available for installation. By default, content from all available - * repositories is shown. - * - * @since 3.4 - */ -public class AvailableIUGroup extends StructuredIUGroup { - - /** - * Show contents from all repositories - */ - public static final int AVAILABLE_ALL = 1; - - /** - * Don't show any repository content - */ - public static final int AVAILABLE_NONE = 2; - - /** - * Show local repository content - */ - public static final int AVAILABLE_LOCAL = 3; - - /** - * Show content for a specific repository - */ - public static final int AVAILABLE_SPECIFIED = 4; - - QueryableMetadataRepositoryManager queryableManager; - - IUViewQueryContext queryContext; - int filterConstant = AVAILABLE_ALL; - URI repositoryFilter; - // We restrict the type of the filter used because PatternFilter does - // unnecessary accesses of children that cause problems with the deferred - // tree. - AvailableIUPatternFilter filter; - private boolean useBold = false; - private IUDetailsLabelProvider labelProvider; - Display display; - DelayedFilterCheckboxTree filteredTree; - Job lastRequestedLoadJob; - - /** - * Create a group that represents the available IU's from all available - * repositories. The default policy controls the visibility flags for - * repositories and IU's. - * - * @param parent the parent composite for the group - */ - public AvailableIUGroup(final Composite parent) { - this(Policy.getDefault(), parent, parent.getFont(), null, null, getDefaultColumnConfig(), AVAILABLE_ALL); - } - - private static IUColumnConfig[] getDefaultColumnConfig() { - // increase primary column width because we might be nesting names under categories and require more space than a flat list - IUColumnConfig nameColumn = new IUColumnConfig(ProvUIMessages.ProvUI_NameColumnTitle, IUColumnConfig.COLUMN_NAME, ILayoutConstants.DEFAULT_PRIMARY_COLUMN_WIDTH + 15); - IUColumnConfig versionColumn = new IUColumnConfig(ProvUIMessages.ProvUI_VersionColumnTitle, IUColumnConfig.COLUMN_VERSION, ILayoutConstants.DEFAULT_COLUMN_WIDTH); - return new IUColumnConfig[] {nameColumn, versionColumn}; - } - - /** - * Create a group that represents the available IU's. - * - * @param policy the policy to use for deciding what should be shown - * @param parent the parent composite for the group - * @param font The font to use for calculating pixel sizes. This font is - * not managed by the receiver. - * @param queryable the queryable repository manager that should be used. Used - * by clients who want to preload repositories. - * @param queryContext the IUViewQueryContext that determines additional - * information about what is shown, such as the visible repositories - * @param columnConfig the description of the columns that should be shown. If null, a default - * will be used. - * @param filterConstant a constant specifying which repositories are used when showing content - */ - public AvailableIUGroup(Policy policy, final Composite parent, Font font, QueryableMetadataRepositoryManager queryable, IUViewQueryContext queryContext, IUColumnConfig[] columnConfig, int filterConstant) { - super(policy, parent, font, columnConfig); - this.display = parent.getDisplay(); - if (queryContext == null) - this.queryContext = policy.getQueryContext(); - else - this.queryContext = queryContext; - if (queryable == null) - this.queryableManager = new QueryableMetadataRepositoryManager(this.queryContext, false); - else - this.queryableManager = queryable; - this.filterConstant = filterConstant; - this.filter = new AvailableIUPatternFilter(getColumnConfig()); - this.filter.setIncludeLeadingWildcard(true); - createGroupComposite(parent); - } - - protected StructuredViewer createViewer(Composite parent) { - // Table of available IU's - filteredTree = new DelayedFilterCheckboxTree(parent, SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER, filter); - final TreeViewer availableIUViewer = filteredTree.getViewer(); - - // If the user expanded or collapsed anything while we were loading a repo - // in the background, we would not want to disrupt their work by making - // a newly loaded visible and expanding it. Setting the load job to null - // will take care of this. - availableIUViewer.getTree().addTreeListener(new TreeListener() { - public void treeCollapsed(TreeEvent e) { - lastRequestedLoadJob = null; - } - - public void treeExpanded(TreeEvent e) { - lastRequestedLoadJob = null; - } - }); - - labelProvider = new IUDetailsLabelProvider(filteredTree, getColumnConfig(), getShell()); - labelProvider.setUseBoldFontForFilteredItems(useBold); - labelProvider.setToolTipProperty(IInstallableUnit.PROP_DESCRIPTION); - - // Filters and sorters before establishing content, so we don't refresh unnecessarily. - IUComparator comparator = new IUComparator(IUComparator.IU_NAME); - comparator.useColumnConfig(getColumnConfig()); - availableIUViewer.setComparator(comparator); - availableIUViewer.setComparer(new ProvElementComparer()); - - // Now the content provider. - DeferredQueryContentProvider contentProvider = new DeferredQueryContentProvider(); - availableIUViewer.setContentProvider(contentProvider); - - // Now the presentation, columns before label provider. - setTreeColumns(availableIUViewer.getTree()); - availableIUViewer.setLabelProvider(labelProvider); - - // Notify the filtered tree so that it can hook listeners on the - // content provider. This is needed so that filtering is only allowed - // after content has been retrieved. - filteredTree.contentProviderSet(contentProvider); - - final StructuredViewerProvisioningListener listener = new StructuredViewerProvisioningListener(availableIUViewer, ProvUIProvisioningListener.PROV_EVENT_METADATA_REPOSITORY) { - protected void repositoryAdded(final RepositoryEvent event) { - // Only make the repo visible if the UI triggered this event. - // This allows us to ignore the addition of system repositories, as - // well as recognize specifically a user-add that resulted in - // the enablement of a repository. - // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=248989 - if (!(event instanceof UIRepositoryEvent)) { - return; - } - makeRepositoryVisible(event.getRepositoryLocation()); - } - - protected void refreshViewer() { - final TreeViewer treeViewer = filteredTree.getViewer(); - final Tree tree = treeViewer.getTree(); - IWorkbench workbench = PlatformUI.getWorkbench(); - if (workbench.isClosing()) - return; - if (tree != null && !tree.isDisposed()) { - updateAvailableViewState(); - } - - } - }; - ProvUIActivator.getDefault().addProvisioningListener(listener); - - availableIUViewer.getControl().addDisposeListener(new DisposeListener() { - public void widgetDisposed(DisposeEvent e) { - ProvUIActivator.getDefault().removeProvisioningListener(listener); - } - }); - updateAvailableViewState(); - return availableIUViewer; - } - - private void setTreeColumns(Tree tree) { - tree.setHeaderVisible(true); - - IUColumnConfig[] cols = getColumnConfig(); - for (int i = 0; i < cols.length; i++) { - TreeColumn tc = new TreeColumn(tree, SWT.NONE, i); - tc.setResizable(true); - tc.setText(cols[i].getColumnTitle()); - tc.setWidth(cols[i].getWidthInPixels(tree)); - } - } - - Object getNewInput() { - if (repositoryFilter != null) { - return new MetadataRepositoryElement(queryContext, getPolicy(), repositoryFilter, true); - } else if (filterConstant == AVAILABLE_NONE) { - // Dummy object that explains empty site list - return new ProvElement(null) { - public Object[] getChildren(Object o) { - String description; - String name; - int severity; - if (getPolicy().getRepositoryManipulator() == null) { - // shouldn't get here ideally. No sites and no way to add. - severity = IStatus.ERROR; - name = ProvUIMessages.AvailableIUGroup_NoSitesConfiguredExplanation; - description = ProvUIMessages.AvailableIUGroup_NoSitesConfiguredDescription; - } else { - severity = IStatus.INFO; - name = ProvUIMessages.AvailableIUGroup_NoSitesExplanation; - description = ProvUIMessages.ColocatedRepositoryManipulator_NoContentExplanation; - } - return new Object[] {new EmptyElementExplanation(null, severity, name, description)}; - } - - public String getLabel(Object o) { - // Label not needed for input - return null; - } - }; - } else { - queryableManager.setQueryContext(queryContext); - return new MetadataRepositories(queryContext, getPolicy(), queryableManager); - } - } - - /** - * Set a boolean indicating whether a bold font should be used when - * showing filtered items. This method does not refresh the tree or - * labels, so that must be done explicitly by the caller. - * @param useBoldFont - */ - public void setUseBoldFontForFilteredItems(boolean useBoldFont) { - if (labelProvider != null) - labelProvider.setUseBoldFontForFilteredItems(useBoldFont); - } - - /** - * Return the composite that contains the controls in this group. - * @return the composite - */ - public Composite getComposite() { - return super.getComposite(); - } - - /** - * Get the viewer used to represent the available IU's - * @return the viewer - */ - public StructuredViewer getStructuredViewer() { - return super.getStructuredViewer(); - } - - /** - * Get the selected IU's - * @return the array of selected IU's - */ - // overridden for visibility in the public package - public IInstallableUnit[] getSelectedIUs() { - return super.getSelectedIUs(); - } - - // overridden to weed out non-IU elements, such as repositories or empty explanations - public Object[] getSelectedIUElements() { - Object[] elements = ((IStructuredSelection) viewer.getSelection()).toArray(); - ArrayList list = new ArrayList(elements.length); - for (int i = 0; i < elements.length; i++) - if (ElementUtils.getIU(elements[i]) != null) - list.add(elements[i]); - return list.toArray(); - } - - public CheckboxTreeViewer getCheckboxTreeViewer() { - return filteredTree.getCheckboxTreeViewer(); - } - - /** - * Get the selected IU's - * @return the array of checked IU's - */ - public IInstallableUnit[] getCheckedLeafIUs() { - Object[] selections = filteredTree.getCheckboxTreeViewer().getCheckedElements(); - if (selections.length == 0) - return new IInstallableUnit[0]; - ArrayList leaves = new ArrayList(selections.length); - for (int i = 0; i < selections.length; i++) { - if (!getCheckboxTreeViewer().getGrayed(selections[i])) { - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(selections[i], IInstallableUnit.class); - if (iu != null && !ProvisioningUtil.isCategory(iu) && !leaves.contains(iu)) - leaves.add(iu); - } - } - return (IInstallableUnit[]) leaves.toArray(new IInstallableUnit[leaves.size()]); - } - - public Tree getTree() { - if (viewer == null) - return null; - return ((TreeViewer) viewer).getTree(); - } - - /* - * Make the repository with the specified location visible in the viewer. - */ - void makeRepositoryVisible(final URI location) { - // If we are viewing by anything other than site, there is no specific way - // to make a repo visible. - if (!(queryContext.getViewType() == IUViewQueryContext.AVAILABLE_VIEW_BY_REPO)) - return; - // First reset the input so that the new repo shows up - display.asyncExec(new Runnable() { - public void run() { - final TreeViewer treeViewer = filteredTree.getViewer(); - final Tree tree = treeViewer.getTree(); - IWorkbench workbench = PlatformUI.getWorkbench(); - if (workbench.isClosing()) - return; - if (tree != null && !tree.isDisposed()) { - updateAvailableViewState(); - } - } - }); - - // We don't know if loading will be a fast or slow operation. - // We do it in a job to be safe, and when it's done, we update - // the UI. - Job job = new Job(NLS.bind(ProvUIMessages.AvailableIUGroup_LoadingRepository, URIUtil.toUnencodedString(location))) { - protected IStatus run(IProgressMonitor monitor) { - try { - ProvisioningUtil.loadMetadataRepository(location, monitor); - return Status.OK_STATUS; - } catch (ProvisionException e) { - return e.getStatus(); - } catch (OperationCanceledException e) { - return Status.CANCEL_STATUS; - } - } - }; - job.setPriority(Job.LONG); - job.setSystem(true); - job.setUser(false); - job.addJobChangeListener(new JobChangeAdapter() { - public void done(final IJobChangeEvent event) { - if (event.getResult().isOK()) - display.asyncExec(new Runnable() { - public void run() { - final TreeViewer treeViewer = filteredTree.getViewer(); - IWorkbench workbench = PlatformUI.getWorkbench(); - if (workbench.isClosing()) - return; - // Expand only if there have been no other jobs started for other repos. - if (event.getJob() == lastRequestedLoadJob) { - final Tree tree = treeViewer.getTree(); - if (tree != null && !tree.isDisposed()) { - TreeItem[] items = tree.getItems(); - for (int i = 0; i < items.length; i++) { - if (items[i].getData() instanceof IRepositoryElement) { - URI url = ((IRepositoryElement) items[i].getData()).getLocation(); - if (url.equals(location)) { - treeViewer.expandToLevel(items[i].getData(), AbstractTreeViewer.ALL_LEVELS); - tree.select(items[i]); - return; - } - } - } - } - } - } - }); - } - }); - lastRequestedLoadJob = job; - job.schedule(); - } - - public void updateAvailableViewState() { - if (getTree() == null || getTree().isDisposed()) - return; - final Composite parent = getComposite().getParent(); - setUseBoldFontForFilteredItems(queryContext.getViewType() != IUViewQueryContext.AVAILABLE_VIEW_FLAT); - - BusyIndicator.showWhile(display, new Runnable() { - public void run() { - parent.setRedraw(false); - getCheckboxTreeViewer().setInput(getNewInput()); - parent.layout(true); - parent.setRedraw(true); - } - }); - } - - public Control getDefaultFocusControl() { - if (filteredTree != null) - return filteredTree.getFilterControl(); - return null; - } - - protected GridData getViewerGridData() { - GridData data = super.getViewerGridData(); - data.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_HEIGHT); - return data; - } - - /** - * Set the checked elements to the specified selections. This method - * does not force visibility/expansion of the checked elements. If they are not - * visible, they will not be checked. - * @param selections - */ - public void setChecked(Object[] selections) { - filteredTree.getCheckboxTreeViewer().setCheckedElements(selections); - // Relying on knowledge that DelayedFilterCheckbox doesn't care which element is in the listener - Object element = selections.length > 0 ? selections[0] : new Object(); - filteredTree.getCheckboxTreeViewer().fireCheckStateChanged(element, true); - } - - public void setRepositoryFilter(int filterFlag, URI repoLocation) { - // If there has been no change, don't do anything. We will be - // clearing out selection caches in this method and should not do - // so if there's really no change. - if (filterConstant == filterFlag) { - if (filterConstant != AVAILABLE_SPECIFIED) - return; - if (repoLocation != null && repoLocation.equals(repositoryFilter)) - return; - } - filterConstant = filterFlag; - - switch (filterFlag) { - case AVAILABLE_ALL : - case AVAILABLE_NONE : - repositoryFilter = null; - queryContext.setMetadataRepositoryFlags(queryContext.getMetadataRepositoryFlags() & ~IRepositoryManager.REPOSITORIES_LOCAL); - break; - case AVAILABLE_LOCAL : - repositoryFilter = null; - queryContext.setMetadataRepositoryFlags(queryContext.getMetadataRepositoryFlags() | IRepositoryManager.REPOSITORIES_LOCAL); - break; - default : - repositoryFilter = repoLocation; - break; - } - updateAvailableViewState(); - filteredTree.clearCheckStateCache(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IRepositorySelectionListener.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IRepositorySelectionListener.java deleted file mode 100644 index acbcdfaa6..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IRepositorySelectionListener.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import java.net.URI; - -/** - * Listener for the repository selection combo. Whenever the selected repository changes (menu selection, - * text modified, new repo added) this listener will be notified. - * - * @since 3.5 - */ -public interface IRepositorySelectionListener { - /** - * Called whenever the selected repository in the combo changes. - * - * @param repoChoice one of AvailableIUGroup.AVAILABLE_NONE, AvailableIUGroup.AVAILABLE_ALL, AvailableIUGroup.AVAILABLE_LOCAL, AvailableIUGroup.AVAILABLE_SPECIFIED - * @param repoLocation if the repoChoice is set to AvailableIUGroup.AVAILABLE_SPECIFIED, this field will contain the URI of the selected repo, otherwise null - */ - public void repositorySelectionChanged(int repoChoice, URI repoLocation); -} \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IUCopyrightPropertyPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IUCopyrightPropertyPage.java deleted file mode 100644 index e53b5cf0e..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IUCopyrightPropertyPage.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import java.net.MalformedURLException; -import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.dialogs.IUPropertyPage; -import org.eclipse.equinox.internal.provisional.p2.metadata.ICopyright; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.IUPropertyUtils; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.*; - -/** - * PropertyPage that shows an IU's copyright - * - * @since 3.4 - */ -public class IUCopyrightPropertyPage extends IUPropertyPage { - - protected Control createIUPage(Composite parent, IInstallableUnit iu) { - // Get the copyright in the current locale - final ICopyright copyright = IUPropertyUtils.getCopyright(iu); - if (copyright != null && copyright.getBody().length() > 0) { - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - composite.setLayout(layout); - - Text text = new Text(composite, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER | SWT.WRAP); - GridData gd = new GridData(SWT.FILL, SWT.FILL, false, true); - gd.widthHint = computeWidthLimit(text, 80); - gd.grabExcessVerticalSpace = true; - text.setLayoutData(gd); - text.setText(copyright.getBody()); - text.setEditable(false); - - // If an URL was specified, provide a link to it - String filename = (copyright.getLocation() != null) ? copyright.getLocation().getPath() : null; - if (filename != null && (filename.endsWith(".htm") || filename.endsWith(".html"))) { //$NON-NLS-1$ //$NON-NLS-2$ - Label label = new Label(composite, SWT.NONE); - label.setText(ProvUIMessages.IUCopyrightPropertyPage_ViewLinkLabel); - // Create a link to the copyright URL - Link link = new Link(composite, SWT.LEFT | SWT.WRAP); - link.setText(NLS.bind("{0}", URIUtil.toUnencodedString(copyright.getLocation()))); //$NON-NLS-1$ - gd = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); - gd.widthHint = computeWidthLimit(link, 80); - link.setLayoutData(gd); - link.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - try { - showURL(copyright.getLocation().toURL()); - } catch (MalformedURLException e1) { - //cannot show this URL - } - } - }); - } - - return composite; - } - Label label = new Label(parent, SWT.NULL); - label.setText(ProvUIMessages.IUCopyrightPropertyPage_NoCopyright); - return label; - - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IUGeneralInfoPropertyPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IUGeneralInfoPropertyPage.java deleted file mode 100644 index adafc76ac..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IUGeneralInfoPropertyPage.java +++ /dev/null @@ -1,143 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import java.net.MalformedURLException; -import java.net.URL; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.dialogs.IUPropertyPage; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.IUPropertyUtils; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.*; - -/** - * PropertyPage that shows an IU's properties - * - * @since 3.4 - */ -public class IUGeneralInfoPropertyPage extends IUPropertyPage { - - protected Control createIUPage(Composite parent, IInstallableUnit iu) { - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - composite.setLayout(layout); - - createGeneralSection(composite, iu); - createDescriptionSection(composite, iu); - createDocumentationSection(composite, iu); - - return composite; - } - - private void createGeneralSection(Composite parent, IInstallableUnit iu) { - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - layout.marginWidth = 0; - layout.marginHeight = 0; - composite.setLayout(layout); - composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - // Get general info in the default locale - addField(composite, ProvUIMessages.IUGeneralInfoPropertyPage_NameLabel, IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_NAME)); - addField(composite, ProvUIMessages.IUGeneralInfoPropertyPage_IdentifierLabel, iu.getId()); - addField(composite, ProvUIMessages.IUGeneralInfoPropertyPage_VersionLabel, iu.getVersion().toString()); - addField(composite, ProvUIMessages.IUGeneralInfoPropertyPage_ProviderLabel, IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_PROVIDER)); - addField(composite, ProvUIMessages.IUGeneralInfoPropertyPage_ContactLabel, IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_CONTACT)); - - } - - private void createDescriptionSection(Composite parent, IInstallableUnit iu) { - // Get the iu description in the default locale - String description = IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION); - if (description != null && description.length() > 0) { - Group group = new Group(parent, SWT.NONE); - group.setText(ProvUIMessages.IUGeneralInfoPropertyPage_DescriptionLabel); - group.setLayout(new GridLayout()); - group.setLayoutData(new GridData(GridData.FILL_BOTH)); - - Text text = new Text(group, SWT.MULTI | SWT.WRAP | SWT.READ_ONLY | SWT.V_SCROLL); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - gd.widthHint = computeWidthLimit(text, 80); - gd.heightHint = 200; - text.setEditable(false); - text.setText(description); - text.setLayoutData(gd); - } - - } - - private void createDocumentationSection(Composite parent, IInstallableUnit iu) { - String docURL = iu.getProperty(IInstallableUnit.PROP_DOC_URL); - if (docURL != null && docURL.length() > 0) { - final URL url; - try { - url = new URL(docURL); - } catch (MalformedURLException e) { - return; - } - String filename = (url != null) ? url.getFile() : null; - if (filename != null && (filename.endsWith(".htm") || filename.endsWith(".html"))) { //$NON-NLS-1$ //$NON-NLS-2$ - // create some space - new Label(parent, SWT.NONE); - // Now create a link to the documentation - Label label = new Label(parent, SWT.NONE); - label.setText(ProvUIMessages.IUGeneralInfoPropertyPage_DocumentationLink); - Link link = new Link(parent, SWT.LEFT | SWT.WRAP); - link.setText(NLS.bind("{0}", url.toExternalForm())); //$NON-NLS-1$ - GridData gd = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); - gd.widthHint = computeWidthLimit(link, 80); - link.setLayoutData(gd); - link.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - showURL(url); - } - }); - } - } - } - - private void addField(Composite parent, String property, String value) { - - if (value != null && value.length() > 0) { - Label label = new Label(parent, SWT.NONE); - label.setText(property); - - Text text = new Text(parent, SWT.WRAP | SWT.READ_ONLY); - text.setText(getEscapedString(value)); - // Needed to get the right color on the Mac. - // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=258112 - text.setBackground(text.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - text.setLayoutData(gd); - } - } - - private String getEscapedString(String value) { - StringBuffer result = new StringBuffer(value.length() + 10); - for (int i = 0; i < value.length(); ++i) { - char c = value.charAt(i); - if ('&' == c) { - result.append("&&"); //$NON-NLS-1$ - } else { - result.append(c); - } - } - return result.toString(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IULicensePropertyPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IULicensePropertyPage.java deleted file mode 100644 index 01d06465f..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/IULicensePropertyPage.java +++ /dev/null @@ -1,81 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.dialogs.IUPropertyPage; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.ILicense; -import org.eclipse.equinox.internal.provisional.p2.ui.IUPropertyUtils; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.*; - -/** - * PropertyPage that shows an IU's license - * - * @since 3.4 - */ -public class IULicensePropertyPage extends IUPropertyPage { - - protected Control createIUPage(Composite parent, IInstallableUnit iu) { - // Get the license in the default locale - final ILicense license = IUPropertyUtils.getLicense(iu); - if (license != null && license.getBody().length() > 0) { - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - composite.setLayout(layout); - - Text text = new Text(composite, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER | SWT.WRAP); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - gd.widthHint = computeWidthLimit(text, 80); - gd.heightHint = computeHeightLimit(text, 20); - text.setLayoutData(gd); - text.setText(license.getBody()); - text.setEditable(false); - - // If an URL was specified, provide a link to it - String filename = (license.getLocation() != null) ? license.getLocation().getPath() : null; - if (filename != null && (filename.endsWith(".htm") || filename.endsWith(".html"))) { //$NON-NLS-1$ //$NON-NLS-2$ - Label label = new Label(composite, SWT.NONE); - label.setText(ProvUIMessages.IULicensePropertyPage_ViewLicenseLabel); - // Create a link to the license URL - Link link = new Link(composite, SWT.LEFT | SWT.WRAP); - link.setText(NLS.bind("{0}", URIUtil.toUnencodedString(license.getLocation()))); //$NON-NLS-1$ - gd = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); - gd.widthHint = computeWidthLimit(link, 80); - link.setLayoutData(gd); - link.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - try { - showURL(license.getLocation().toURL()); - } catch (Exception e1) { - //can't browse invalid location - } - } - }); - } - - return composite; - } - Label label = new Label(parent, SWT.NULL); - label.setText(ProvUIMessages.IULicensePropertyPage_NoLicense); - return label; - - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/InstallWizard.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/InstallWizard.java deleted file mode 100644 index c9df0ee6f..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/InstallWizard.java +++ /dev/null @@ -1,137 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import java.util.ArrayList; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.dialogs.*; -import org.eclipse.equinox.internal.p2.ui.model.AvailableIUElement; -import org.eclipse.equinox.internal.p2.ui.model.ElementUtils; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; -import org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.InstallAction; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.wizard.IWizardPage; -import org.eclipse.swt.widgets.Composite; - -/** - * An install wizard that allows the users to browse all of the repositories - * and search/select for items to install. - * - * @since 3.4 - */ -public class InstallWizard extends WizardWithLicenses { - - QueryableMetadataRepositoryManager manager; - AvailableIUsPage mainPage; - SelectableIUsPage errorReportingPage; - - public InstallWizard(Policy policy, String profileId, IInstallableUnit[] initialSelections, PlannerResolutionOperation initialResolution, QueryableMetadataRepositoryManager manager) { - super(policy, profileId, null, initialSelections, initialResolution); - this.manager = manager; - setWindowTitle(ProvUIMessages.InstallIUOperationLabel); - setDefaultPageImageDescriptor(ProvUIImages.getImageDescriptor(ProvUIImages.WIZARD_BANNER_INSTALL)); - } - - public InstallWizard(Policy policy, String profileId) { - this(policy, profileId, null, null, new QueryableMetadataRepositoryManager(policy.getQueryContext(), false)); - } - - protected ResolutionResultsWizardPage createResolutionPage() { - return new InstallWizardPage(policy, profileId, root, resolutionOperation); - } - - protected ISelectableIUsPage createMainPage(IUElementListRoot input, Object[] selections) { - mainPage = new AvailableIUsPage(policy, profileId, manager); - if (selections != null && selections.length > 0) - mainPage.setCheckedElements(selections); - return mainPage; - - } - - protected IUElementListRoot makeResolutionElementRoot(Object[] selectedElements) { - IUElementListRoot elementRoot = new IUElementListRoot(); - ArrayList list = new ArrayList(selectedElements.length); - for (int i = 0; i < selectedElements.length; i++) { - IInstallableUnit iu = ElementUtils.getIU(selectedElements[i]); - if (iu != null) - list.add(new AvailableIUElement(elementRoot, iu, profileId, policy.getQueryContext().getShowProvisioningPlanChildren())); - } - elementRoot.setChildren(list.toArray()); - return elementRoot; - } - - public void createPageControls(Composite pageContainer) { - super.createPageControls(pageContainer); - if (manager != null) - // async exec since we are in the middle of opening - pageContainer.getDisplay().asyncExec(new Runnable() { - public void run() { - manager.reportAccumulatedStatus(); - } - }); - } - - protected ProvisioningContext getProvisioningContext() { - return mainPage.getProvisioningContext(); - } - - protected ProfileChangeRequest computeProfileChangeRequest(Object[] selectedElements, MultiStatus additionalStatus, IProgressMonitor monitor) { - IInstallableUnit[] selected = ElementUtils.elementsToIUs(selectedElements); - return InstallAction.computeProfileChangeRequest(selected, profileId, additionalStatus, monitor); - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.ui.dialogs.ProvisioningOperationWizard#getErrorReportingPage() - */ - protected IResolutionErrorReportingPage getErrorReportingPage() { - if (errorReportingPage == null) { - originalRoot = root; - errorReportingPage = new SelectableIUsPage(policy, root, root.getChildren(root), profileId); - errorReportingPage.setTitle(ProvUIMessages.InstallWizardPage_Title); - errorReportingPage.setDescription(ProvUIMessages.PreselectedIUInstallWizard_Description); - errorReportingPage.updateStatus(root, resolutionOperation); - errorReportingPage.setCheckedElements(root.getChildren(root)); - addPage(errorReportingPage); - } - return errorReportingPage; - } - - protected void showingErrorPage() { - // If we did a new resolution and are showing the error page, - // update the root. We don't do this when the page is not the main - // page, or we might be updating the root of the showing page. - if (getContainer().getCurrentPage() == mainPage) { - originalRoot = root; - errorReportingPage.updateStatus(originalRoot, resolutionOperation); - errorReportingPage.setCheckedElements(root.getChildren(root)); - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.wizard.Wizard#getPreviousPage(org.eclipse.jface.wizard.IWizardPage) - */ - public IWizardPage getPreviousPage(IWizardPage page) { - if (page == errorReportingPage) { - mainPage.setCheckedElements(errorReportingPage.getCheckedIUElements()); - return mainPage; - } - return super.getPreviousPage(page); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/InstalledIUGroup.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/InstalledIUGroup.java deleted file mode 100644 index 6be850b41..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/InstalledIUGroup.java +++ /dev/null @@ -1,115 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.dialogs.StructuredIUGroup; -import org.eclipse.equinox.internal.p2.ui.viewers.DeferredQueryContentProvider; -import org.eclipse.equinox.internal.p2.ui.viewers.IUDetailsLabelProvider; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIProvisioningListener; -import org.eclipse.equinox.internal.provisional.p2.ui.model.ProfileElement; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.*; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.widgets.*; - -/** - * An InstalledIUGroup is a reusable UI component that displays the - * IU's in a given profile. - * - * @since 3.4 - */ -public class InstalledIUGroup extends StructuredIUGroup { - - private String profileId; - - /** - * Create a group that represents the installed IU's. - * - * @param parent the parent composite for the group - * @param font The font to use for calculating pixel sizes. This font is - * not managed by the receiver. - * @param profileId the id of the profile whose content is being shown. - * @param columnConfig the columns to be shown - */ - public InstalledIUGroup(Policy policy, final Composite parent, Font font, String profileId, IUColumnConfig[] columnConfig) { - super(policy, parent, font, columnConfig); - if (profileId == null) - this.profileId = policy.getProfileChooser().getProfileId(ProvUI.getDefaultParentShell()); - else - this.profileId = profileId; - createGroupComposite(parent); - } - - protected StructuredViewer createViewer(Composite parent) { - // Table of installed IU's - TreeViewer installedIUViewer = new TreeViewer(parent, SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); - - // Filters and sorters before establishing content, so we don't refresh unnecessarily. - IUComparator comparator = new IUComparator(IUComparator.IU_NAME); - comparator.useColumnConfig(getColumnConfig()); - installedIUViewer.setComparator(comparator); - installedIUViewer.setComparer(new ProvElementComparer()); - - // Now the content. - installedIUViewer.setContentProvider(new DeferredQueryContentProvider()); - - // Now the visuals, columns before labels. - setTreeColumns(installedIUViewer.getTree()); - installedIUViewer.setLabelProvider(new IUDetailsLabelProvider(null, getColumnConfig(), null)); - - // Input last. - installedIUViewer.setInput(getInput()); - - final StructuredViewerProvisioningListener listener = new StructuredViewerProvisioningListener(installedIUViewer, ProvUIProvisioningListener.PROV_EVENT_IU | ProvUIProvisioningListener.PROV_EVENT_PROFILE); - ProvUIActivator.getDefault().addProvisioningListener(listener); - installedIUViewer.getControl().addDisposeListener(new DisposeListener() { - public void widgetDisposed(DisposeEvent e) { - ProvUIActivator.getDefault().removeProvisioningListener(listener); - } - }); - return installedIUViewer; - } - - private void setTreeColumns(Tree tree) { - IUColumnConfig[] columns = getColumnConfig(); - tree.setHeaderVisible(true); - - for (int i = 0; i < columns.length; i++) { - TreeColumn tc = new TreeColumn(tree, SWT.NONE, i); - tc.setResizable(true); - tc.setText(columns[i].getColumnTitle()); - tc.setWidth(columns[i].getWidthInPixels(tree)); - } - } - - Object getInput() { - ProfileElement element = new ProfileElement(null, profileId); - return element; - } - - /** - * Get the viewer used to represent the installed IU's - */ - public StructuredViewer getStructuredViewer() { - return super.getStructuredViewer(); - } - - public Control getDefaultFocusControl() { - return super.getDefaultFocusControl(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/InstalledSoftwarePage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/InstalledSoftwarePage.java deleted file mode 100644 index 30b51c5b8..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/InstalledSoftwarePage.java +++ /dev/null @@ -1,239 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.dialogs.*; -import org.eclipse.equinox.internal.p2.ui.viewers.IUDetailsLabelProvider; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.*; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.IUColumnConfig; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.viewers.*; -import org.eclipse.jface.window.SameShellProvider; -import org.eclipse.jface.window.Window; -import org.eclipse.swt.SWT; -import org.eclipse.swt.dnd.*; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.*; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.about.InstallationPage; -import org.eclipse.ui.menus.AbstractContributionFactory; -import org.eclipse.ui.statushandlers.StatusManager; - -/** - * @since 3.4 - * - */ -public class InstalledSoftwarePage extends InstallationPage implements ICopyable { - - private static final int UPDATE_ID = IDialogConstants.CLIENT_ID; - private static final int UNINSTALL_ID = IDialogConstants.CLIENT_ID + 1; - private static final int PROPERTIES_ID = IDialogConstants.CLIENT_ID + 2; - private static final String BUTTON_ACTION = "org.eclipse.equinox.p2.ui.buttonAction"; //$NON-NLS-1$ - - AbstractContributionFactory factory; - Text detailsArea; - InstalledIUGroup installedIUGroup; - String profileId; - Button updateButton, uninstallButton, propertiesButton; - - /* (non-Javadoc) - * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) - */ - public void createControl(Composite parent) { - initializeDialogUnits(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IProvHelpContextIds.INSTALLED_SOFTWARE); - - profileId = Policy.getDefault().getProfileChooser().getProfileId(ProvUI.getDefaultParentShell()); - if (profileId == null) { - IStatus status = Policy.getDefault().getNoProfileChosenStatus(); - if (status != null) - ProvUI.reportStatus(status, StatusManager.LOG); - Text text = new Text(parent, SWT.WRAP | SWT.READ_ONLY); - text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - text.setText(ProvUIMessages.InstalledSoftwarePage_NoProfile); - setControl(text); - return; - } - - Composite composite = new Composite(parent, SWT.NONE); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - int width = getDefaultWidth(composite); - gd.widthHint = width; - composite.setLayoutData(gd); - GridLayout layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - composite.setLayout(layout); - - // Table of installed IU's - installedIUGroup = new InstalledIUGroup(Policy.getDefault(), composite, JFaceResources.getDialogFont(), profileId, getColumnConfig()); - // we hook selection listeners on the viewer in createPageButtons because we - // rely on the actions we create there getting selection events before we use - // them to update button enablement. - - CopyUtils.activateCopy(this, installedIUGroup.getStructuredViewer().getControl()); - - gd = new GridData(SWT.FILL, SWT.FILL, true, false); - gd.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_DESCRIPTION_HEIGHT); - gd.widthHint = width; - - detailsArea = new Text(composite, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.READ_ONLY | SWT.WRAP); - detailsArea.setBackground(detailsArea.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); - detailsArea.setLayoutData(gd); - - setControl(composite); - } - - public void createPageButtons(Composite parent) { - if (profileId == null) - return; - // For the update action, we create a custom selection provider that will interpret no - // selection as checking for updates to everything. - // We also override the run method to close the containing dialog - // if we successfully try to resolve. This is done to ensure that progress - // is shown properly. - // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=236495 - UpdateAction updateAction = new UpdateAction(Policy.getDefault(), new ISelectionProvider() { - public void addSelectionChangedListener(ISelectionChangedListener listener) { - installedIUGroup.getStructuredViewer().addSelectionChangedListener(listener); - } - - public ISelection getSelection() { - StructuredViewer viewer = installedIUGroup.getStructuredViewer(); - ISelection selection = viewer.getSelection(); - if (selection.isEmpty()) { - final Object[] all = ((IStructuredContentProvider) viewer.getContentProvider()).getElements(viewer.getInput()); - return new StructuredSelection(all); - } - return selection; - } - - public void removeSelectionChangedListener(ISelectionChangedListener listener) { - installedIUGroup.getStructuredViewer().removeSelectionChangedListener(listener); - } - - public void setSelection(ISelection selection) { - installedIUGroup.getStructuredViewer().setSelection(selection); - } - }, profileId, true) { - public void run() { - super.run(); - if (getReturnCode() == Window.OK) - getPageContainer().closeModalContainers(); - } - }; - updateAction.setSkipSelectionPage(true); - updateButton = createButton(parent, UPDATE_ID, updateAction.getText()); - updateButton.setData(BUTTON_ACTION, updateAction); - // Uninstall action - Action uninstallAction = new UninstallAction(Policy.getDefault(), installedIUGroup.getStructuredViewer(), profileId) { - public void run() { - super.run(); - if (getReturnCode() == Window.OK) - getPageContainer().closeModalContainers(); - } - }; - uninstallButton = createButton(parent, UNINSTALL_ID, uninstallAction.getText()); - uninstallButton.setData(BUTTON_ACTION, uninstallAction); - - // Properties action - PropertyDialogAction action = new PropertyDialogAction(new SameShellProvider(getShell()), installedIUGroup.getStructuredViewer()); - propertiesButton = createButton(parent, PROPERTIES_ID, action.getText()); - propertiesButton.setData(BUTTON_ACTION, action); - - // We rely on the actions getting selection events before we do, because - // we rely on the enablement state of the action. So we don't hook - // the selection listener on our table until after actions are created. - installedIUGroup.getStructuredViewer().addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - updateDetailsArea(); - updateEnablement(); - } - - }); - - updateEnablement(); - } - - void updateDetailsArea() { - IInstallableUnit[] selected = installedIUGroup.getSelectedIUs(); - if (selected.length == 1) { - String description = IUPropertyUtils.getIUProperty(selected[0], IInstallableUnit.PROP_DESCRIPTION); - if (description != null) { - detailsArea.setText(description); - return; - } - } - detailsArea.setText(""); //$NON-NLS-1$ - } - - void updateEnablement() { - if (updateButton == null || updateButton.isDisposed()) - return; - Button[] buttons = {updateButton, uninstallButton, propertiesButton}; - for (int i = 0; i < buttons.length; i++) { - Action action = (Action) buttons[i].getData(BUTTON_ACTION); - if (action == null || !action.isEnabled()) - buttons[i].setEnabled(false); - else - buttons[i].setEnabled(true); - } - } - - private IUColumnConfig[] getColumnConfig() { - return new IUColumnConfig[] {new IUColumnConfig(ProvUIMessages.ProvUI_NameColumnTitle, IUColumnConfig.COLUMN_NAME, ILayoutConstants.DEFAULT_PRIMARY_COLUMN_WIDTH), new IUColumnConfig(ProvUIMessages.ProvUI_VersionColumnTitle, IUColumnConfig.COLUMN_VERSION, ILayoutConstants.DEFAULT_SMALL_COLUMN_WIDTH), new IUColumnConfig(ProvUIMessages.ProvUI_IdColumnTitle, IUColumnConfig.COLUMN_ID, ILayoutConstants.DEFAULT_COLUMN_WIDTH)}; - } - - private int getDefaultWidth(Control control) { - IUColumnConfig[] columns = getColumnConfig(); - int totalWidth = 0; - for (int i = 0; i < columns.length; i++) { - totalWidth += columns[i].getWidthInPixels(control); - } - return totalWidth + 20; // buffer for surrounding composites - } - - public void copyToClipboard(Control activeControl) { - Object[] elements = installedIUGroup.getSelectedIUElements(); - if (elements.length == 0) - return; - String text = CopyUtils.getIndentedClipboardText(elements, new IUDetailsLabelProvider(null, getColumnConfig(), null)); - Clipboard clipboard = new Clipboard(PlatformUI.getWorkbench().getDisplay()); - clipboard.setContents(new Object[] {text}, new Transfer[] {TextTransfer.getInstance()}); - clipboard.dispose(); - } - - protected void buttonPressed(int buttonId) { - switch (buttonId) { - case UPDATE_ID : - ((Action) updateButton.getData(BUTTON_ACTION)).run(); - break; - case UNINSTALL_ID : - ((Action) uninstallButton.getData(BUTTON_ACTION)).run(); - break; - case PROPERTIES_ID : - ((Action) propertiesButton.getData(BUTTON_ACTION)).run(); - break; - default : - super.buttonPressed(buttonId); - break; - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/PreselectedIUInstallWizard.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/PreselectedIUInstallWizard.java deleted file mode 100644 index d9db111a1..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/PreselectedIUInstallWizard.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import java.util.ArrayList; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.dialogs.*; -import org.eclipse.equinox.internal.p2.ui.model.AvailableIUElement; -import org.eclipse.equinox.internal.p2.ui.model.ElementUtils; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; -import org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.InstallAction; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; - -/** - * An Install wizard that is invoked when the user has already selected which - * IUs should be installed and does not need to browse the available software. - * - * @since 3.5 - */ -public class PreselectedIUInstallWizard extends WizardWithLicenses { - - SelectableIUsPage mainPage; - QueryableMetadataRepositoryManager manager; - - static IUElementListRoot makeElementRoot(IInstallableUnit[] ius, String profileId) { - IUElementListRoot elementRoot = new IUElementListRoot(); - Object[] elements = new Object[ius.length]; - for (int i = 0; i < ius.length; i++) { - if (ius[i] != null) - elements[i] = new AvailableIUElement(elementRoot, ius[i], profileId, false); - } - elementRoot.setChildren(elements); - return elementRoot; - } - - public PreselectedIUInstallWizard(Policy policy, String profileId, IInstallableUnit[] initialSelections, PlannerResolutionOperation initialResolution, QueryableMetadataRepositoryManager manager) { - super(policy, profileId, makeElementRoot(initialSelections, profileId), initialSelections, initialResolution); - this.manager = manager; - setWindowTitle(ProvUIMessages.InstallIUOperationLabel); - setDefaultPageImageDescriptor(ProvUIImages.getImageDescriptor(ProvUIImages.WIZARD_BANNER_INSTALL)); - } - - protected ISelectableIUsPage createMainPage(IUElementListRoot input, Object[] selections) { - mainPage = new SelectableIUsPage(policy, input, selections, profileId); - mainPage.setTitle(ProvUIMessages.PreselectedIUInstallWizard_Title); - mainPage.setDescription(ProvUIMessages.PreselectedIUInstallWizard_Description); - mainPage.updateStatus(input, resolutionOperation); - return mainPage; - } - - protected ResolutionResultsWizardPage createResolutionPage() { - return new InstallWizardPage(policy, profileId, root, resolutionOperation); - } - - protected IUElementListRoot makeResolutionElementRoot(Object[] selectedElements) { - IUElementListRoot elementRoot = new IUElementListRoot(); - ArrayList list = new ArrayList(selectedElements.length); - for (int i = 0; i < selectedElements.length; i++) { - IInstallableUnit iu = ElementUtils.getIU(selectedElements[i]); - if (iu != null) - list.add(new AvailableIUElement(elementRoot, iu, profileId, policy.getQueryContext().getShowProvisioningPlanChildren())); - } - elementRoot.setChildren(list.toArray()); - return elementRoot; - } - - protected ProfileChangeRequest computeProfileChangeRequest(Object[] selectedElements, MultiStatus additionalStatus, IProgressMonitor monitor) { - IInstallableUnit[] selected = ElementUtils.elementsToIUs(selectedElements); - return InstallAction.computeProfileChangeRequest(selected, profileId, additionalStatus, monitor); - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.ui.dialogs.ProvisioningOperationWizard#getErrorReportingPage() - */ - protected IResolutionErrorReportingPage getErrorReportingPage() { - return mainPage; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/ProvisioningWizardDialog.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/ProvisioningWizardDialog.java deleted file mode 100644 index e5282c000..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/ProvisioningWizardDialog.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - ******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.dialogs.ProvisioningOperationWizard; -import org.eclipse.jface.dialogs.IDialogSettings; -import org.eclipse.jface.wizard.WizardDialog; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Shell; - -/** - * Subclass of WizardDialog that provides bounds saving behavior. - * @since 3.5 - * - */ -public class ProvisioningWizardDialog extends WizardDialog { - private ProvisioningOperationWizard wizard; - - public ProvisioningWizardDialog(Shell parent, ProvisioningOperationWizard wizard) { - super(parent, wizard); - this.wizard = wizard; - setShellStyle(getShellStyle() | SWT.RESIZE); - } - - protected IDialogSettings getDialogBoundsSettings() { - IDialogSettings settings = ProvUIActivator.getDefault().getDialogSettings(); - IDialogSettings section = settings.getSection(wizard.getDialogSettingsSectionName()); - if (section == null) { - section = settings.addNewSection(wizard.getDialogSettingsSectionName()); - } - return section; - } - - /** - * @see org.eclipse.jface.window.Window#close() - */ - public boolean close() { - if (getShell() != null && !getShell().isDisposed()) { - wizard.saveBoundsRelatedSettings(); - } - return super.close(); - } - - /** - * This method is provided only for automated testing. - * - * @noreference This method is not intended to be referenced by clients. - */ - public Button testGetButton(int id) { - return getButton(id); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RepositoryManipulationPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RepositoryManipulationPage.java deleted file mode 100644 index 28f3d879f..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RepositoryManipulationPage.java +++ /dev/null @@ -1,912 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import java.lang.reflect.InvocationTargetException; -import java.net.URI; -import java.util.ArrayList; -import java.util.Hashtable; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.ui.*; -import org.eclipse.equinox.internal.p2.ui.dialogs.*; -import org.eclipse.equinox.internal.p2.ui.model.ElementUtils; -import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement; -import org.eclipse.equinox.internal.p2.ui.viewers.MetadataRepositoryElementComparator; -import org.eclipse.equinox.internal.p2.ui.viewers.RepositoryDetailsLabelProvider; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.model.MetadataRepositories; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.*; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.*; -import org.eclipse.jface.dialogs.*; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.jface.viewers.*; -import org.eclipse.jface.window.Window; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.SWT; -import org.eclipse.swt.accessibility.AccessibleAdapter; -import org.eclipse.swt.accessibility.AccessibleEvent; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.swt.dnd.*; -import org.eclipse.swt.events.*; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.*; -import org.eclipse.ui.*; -import org.eclipse.ui.dialogs.PatternFilter; -import org.eclipse.ui.progress.IElementCollector; -import org.eclipse.ui.progress.WorkbenchJob; -import org.eclipse.ui.statushandlers.StatusManager; - -/** - * Page that allows users to update, add, remove, import, and - * export repositories. This page can be hosted inside a preference - * dialog or inside its own dialog. When hosting this page inside - * a non-preference dialog, some of the dialog methods will likely - * have to call page methods. The following snippet shows how to host - * this page inside a TitleAreaDialog. - *
    - *		TitleAreaDialog dialog = new TitleAreaDialog(shell) {
    - *
    - *			RepositoryManipulationPage page;
    - *
    - *			protected Control createDialogArea(Composite parent) {
    - *				page = new RepositoryManipulationPage(policy);
    - *				page.createControl(parent);
    - *				this.setTitle("Software Sites");
    - *				this.setMessage("The enabled sites will be searched for software.  Disabled sites are ignored.);
    - *				return page.getControl();
    - *			}
    - *
    - *			protected void okPressed() {
    - *				if (page.performOk())
    -*					super.okPressed();
    - *			}
    - *
    - *			protected void cancelPressed() {
    - *				if (page.performCancel())
    - *					super.cancelPressed();
    - *			}
    - *		};
    - *		dialog.open();
    - * 
    - * - * @since 3.5 - */ -public class RepositoryManipulationPage extends PreferencePage implements IWorkbenchPreferencePage, ICopyable { - final static String DEFAULT_FILTER_TEXT = ProvUIMessages.RepositoryManipulationPage_DefaultFilterString; - private final static int FILTER_DELAY = 200; - - StructuredViewerProvisioningListener listener; - TableViewer repositoryViewer; - Table table; - Policy policy; - Display display; - boolean changed = false; - MetadataRepositoryElementComparator comparator; - RepositoryDetailsLabelProvider labelProvider; - RepositoryManipulator manipulator; - RepositoryManipulator localCacheRepoManipulator; - CachedMetadataRepositories input; - Text pattern, details; - PatternFilter filter; - WorkbenchJob filterJob; - Button addButton, removeButton, editButton, refreshButton, disableButton, exportButton; - - class CachedMetadataRepositories extends MetadataRepositories { - Hashtable cachedElements; - - CachedMetadataRepositories() { - super(policy); - setIncludeDisabledRepositories(manipulator != null); - } - - public int getQueryType() { - return QueryProvider.METADATA_REPOS; - } - - public void fetchDeferredChildren(Object o, IElementCollector collector, IProgressMonitor monitor) { - if (cachedElements == null) { - super.fetchDeferredChildren(o, collector, monitor); - // now we know we have children - Object[] children = getChildren(o); - cachedElements = new Hashtable(children.length); - for (int i = 0; i < children.length; i++) { - if (children[i] instanceof MetadataRepositoryElement) - cachedElements.put(URIUtil.toUnencodedString(((MetadataRepositoryElement) children[i]).getLocation()), children[i]); - } - return; - } - // Use the cache rather than fetching children - collector.add(cachedElements.values().toArray(), monitor); - } - - } - - class MetadataRepositoryPatternFilter extends PatternFilter { - MetadataRepositoryPatternFilter() { - setIncludeLeadingWildcard(true); - } - - public boolean isElementVisible(Viewer viewer, Object element) { - if (element instanceof MetadataRepositoryElement) { - return wordMatches(labelProvider.getColumnText(element, RepositoryDetailsLabelProvider.COL_NAME) + " " + labelProvider.getColumnText(element, RepositoryDetailsLabelProvider.COL_LOCATION)); //$NON-NLS-1$ - } - return false; - } - } - - /** - * This method must be called before the contents are created. - * @param policy - */ - public void setPolicy(Policy policy) { - this.policy = policy; - manipulator = policy.getRepositoryManipulator(); - } - - protected Control createContents(Composite parent) { - display = parent.getDisplay(); - // The help refers to the full-blown dialog. No help if it's read only. - if (manipulator != null) - PlatformUI.getWorkbench().getHelpSystem().setHelp(parent.getShell(), IProvHelpContextIds.REPOSITORY_MANIPULATION_DIALOG); - - Composite composite = new Composite(parent, SWT.NONE); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - composite.setLayoutData(gd); - - GridLayout layout = new GridLayout(); - layout.numColumns = manipulator == null ? 1 : 2; - layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - composite.setLayout(layout); - - // Filter box - pattern = new Text(composite, SWT.SINGLE | SWT.BORDER | SWT.SEARCH | SWT.CANCEL); - pattern.getAccessible().addAccessibleListener(new AccessibleAdapter() { - public void getName(AccessibleEvent e) { - e.result = DEFAULT_FILTER_TEXT; - } - }); - pattern.setText(DEFAULT_FILTER_TEXT); - pattern.selectAll(); - pattern.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - applyFilter(); - } - }); - - pattern.addKeyListener(new KeyAdapter() { - public void keyPressed(KeyEvent e) { - if (e.keyCode == SWT.ARROW_DOWN) { - if (table.getItemCount() > 0) { - table.setFocus(); - } else if (e.character == SWT.CR) { - return; - } - } - } - }); - - pattern.addFocusListener(new FocusAdapter() { - public void focusGained(FocusEvent e) { - display.asyncExec(new Runnable() { - public void run() { - if (!pattern.isDisposed()) { - if (DEFAULT_FILTER_TEXT.equals(pattern.getText().trim())) { - pattern.selectAll(); - } - } - } - }); - } - }); - gd = new GridData(SWT.FILL, SWT.FILL, true, false); - pattern.setLayoutData(gd); - - // spacer to fill other column - if (manipulator != null) - new Label(composite, SWT.NONE); - - // Table of available repositories - repositoryViewer = new TableViewer(composite, SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); - table = repositoryViewer.getTable(); - - // Key listener for delete - table.addKeyListener(new KeyAdapter() { - public void keyPressed(KeyEvent e) { - if (e.keyCode == SWT.DEL) { - removeRepositories(); - } - } - }); - setTableColumns(); - CopyUtils.activateCopy(this, table); - - repositoryViewer.setComparer(new ProvElementComparer()); - comparator = new MetadataRepositoryElementComparator(RepositoryDetailsLabelProvider.COL_NAME); - repositoryViewer.setComparator(comparator); - filter = new MetadataRepositoryPatternFilter(); - repositoryViewer.setFilters(new ViewerFilter[] {filter}); - // We don't need a deferred content provider because we are caching local results before - // actually querying - repositoryViewer.setContentProvider(new ProvElementContentProvider()); - labelProvider = new RepositoryDetailsLabelProvider(); - repositoryViewer.setLabelProvider(labelProvider); - - // Edit the nickname - repositoryViewer.setCellModifier(new ICellModifier() { - public boolean canModify(Object element, String property) { - return element instanceof MetadataRepositoryElement; - } - - public Object getValue(Object element, String property) { - return ((MetadataRepositoryElement) element).getName(); - } - - public void modify(Object element, String property, Object value) { - if (value != null && value.toString().length() >= 0) { - MetadataRepositoryElement repo; - if (element instanceof Item) { - repo = (MetadataRepositoryElement) ((Item) element).getData(); - } else if (element instanceof MetadataRepositoryElement) { - repo = (MetadataRepositoryElement) element; - } else { - return; - } - changed = true; - repo.setNickname(value.toString()); - if (comparator.getSortKey() == RepositoryDetailsLabelProvider.COL_NAME) - repositoryViewer.refresh(true); - else - repositoryViewer.update(repo, null); - } - } - - }); - repositoryViewer.setColumnProperties(new String[] {"nickname"}); //$NON-NLS-1$ - repositoryViewer.setCellEditors(new CellEditor[] {new TextCellEditor(repositoryViewer.getTable())}); - - repositoryViewer.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - if (manipulator != null) - validateButtons(); - setDetails(); - } - }); - - // Input last - repositoryViewer.setInput(getInput()); - - GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); - data.widthHint = convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_WIDTH); - data.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_HEIGHT); - table.setLayoutData(data); - - // Drop targets and vertical buttons only if repository manipulation is provided. - if (manipulator != null) { - DropTarget target = new DropTarget(table, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK); - target.setTransfer(new Transfer[] {URLTransfer.getInstance(), FileTransfer.getInstance()}); - target.addDropListener(new RepositoryManipulatorDropTarget(getRepositoryManipulator(), table)); - - // Vertical buttons - Composite verticalButtonBar = createVerticalButtonBar(composite); - data = new GridData(SWT.FILL, SWT.FILL, false, false); - data.verticalAlignment = SWT.TOP; - data.verticalIndent = 0; - verticalButtonBar.setLayoutData(data); - listener = getViewerProvisioningListener(); - - ProvUI.addProvisioningListener(listener); - composite.addDisposeListener(new DisposeListener() { - public void widgetDisposed(DisposeEvent event) { - ProvUI.removeProvisioningListener(listener); - } - }); - - validateButtons(); - } - - // Details area - details = new Text(composite, SWT.READ_ONLY | SWT.WRAP); - data = new GridData(SWT.FILL, SWT.FILL, true, false); - data.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_SITEDETAILS_HEIGHT); - - details.setLayoutData(data); - - Dialog.applyDialogFont(composite); - return composite; - } - - private Button createVerticalButton(Composite parent, String label, boolean defaultButton) { - Button button = new Button(parent, SWT.PUSH); - button.setText(label); - - GridData data = setVerticalButtonLayoutData(button); - data.horizontalAlignment = GridData.FILL; - - button.setToolTipText(label); - if (defaultButton) { - Shell shell = parent.getShell(); - if (shell != null) { - shell.setDefaultButton(button); - } - } - return button; - } - - private GridData setVerticalButtonLayoutData(Button button) { - GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); - Point minSize = button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); - data.widthHint = Math.max(widthHint, minSize.x); - button.setLayoutData(data); - return data; - } - - private void setTableColumns() { - table.setHeaderVisible(true); - String[] columnHeaders; - if (manipulator != null) - columnHeaders = new String[] {ProvUIMessages.RepositoryManipulationPage_NameColumnTitle, ProvUIMessages.RepositoryManipulationPage_LocationColumnTitle, ProvUIMessages.RepositoryManipulationPage_EnabledColumnTitle}; - else - columnHeaders = new String[] {ProvUIMessages.RepositoryManipulationPage_NameColumnTitle, ProvUIMessages.RepositoryManipulationPage_LocationColumnTitle}; - for (int i = 0; i < columnHeaders.length; i++) { - TableColumn tc = new TableColumn(table, SWT.NONE, i); - tc.setResizable(true); - tc.setText(columnHeaders[i]); - if (i == RepositoryDetailsLabelProvider.COL_ENABLEMENT) { - tc.setWidth(convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_SMALL_COLUMN_WIDTH)); - tc.setAlignment(SWT.CENTER); - } else if (i == RepositoryDetailsLabelProvider.COL_NAME) { - tc.setWidth(convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_COLUMN_WIDTH)); - } else { - tc.setWidth(convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_PRIMARY_COLUMN_WIDTH)); - } - tc.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - columnSelected((TableColumn) e.widget); - } - - public void widgetSelected(SelectionEvent e) { - columnSelected((TableColumn) e.widget); - } - - }); - // First column only - if (i == 0) { - table.setSortColumn(tc); - table.setSortDirection(SWT.UP); - } - } - } - - private Composite createVerticalButtonBar(Composite parent) { - // Create composite. - Composite composite = new Composite(parent, SWT.NONE); - initializeDialogUnits(composite); - - // create a layout with spacing and margins appropriate for the font - // size. - GridLayout layout = new GridLayout(); - layout.numColumns = 1; - layout.marginWidth = 5; - layout.marginHeight = 0; - layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - composite.setLayout(layout); - - createVerticalButtons(composite); - return composite; - } - - private void createVerticalButtons(Composite parent) { - addButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Add, false); - addButton.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event event) { - addRepository(); - } - }); - - editButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Edit, false); - editButton.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event event) { - changeRepositoryProperties(); - } - }); - - removeButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Remove, false); - removeButton.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event event) { - removeRepositories(); - } - }); - - refreshButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_RefreshConnection, false); - refreshButton.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event event) { - refreshRepository(); - } - }); - - disableButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_DisableButton, false); - disableButton.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event event) { - toggleRepositoryEnablement(); - } - }); - - Button button = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Import, false); - button.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event event) { - importRepositories(); - } - }); - - exportButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Export, false); - exportButton.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event event) { - exportRepositories(); - } - }); - } - - CachedMetadataRepositories getInput() { - if (input == null) - input = new CachedMetadataRepositories(); - return input; - } - - public boolean performOk() { - if (changed) - ElementUtils.updateRepositoryUsingElements(getElements(), getShell()); - return super.performOk(); - } - - private StructuredViewerProvisioningListener getViewerProvisioningListener() { - return new StructuredViewerProvisioningListener(repositoryViewer, ProvUIProvisioningListener.PROV_EVENT_METADATA_REPOSITORY) { - protected void repositoryDiscovered(RepositoryEvent e) { - RepositoryManipulationPage.this.asyncRefresh(null); - } - - protected void repositoryChanged(RepositoryEvent e) { - RepositoryManipulationPage.this.asyncRefresh(null); - } - }; - } - - MetadataRepositoryElement[] getElements() { - return (MetadataRepositoryElement[]) getInput().cachedElements.values().toArray(new MetadataRepositoryElement[getInput().cachedElements.size()]); - } - - MetadataRepositoryElement[] getSelectedElements() { - Object[] items = ((IStructuredSelection) repositoryViewer.getSelection()).toArray(); - ArrayList list = new ArrayList(items.length); - for (int i = 0; i < items.length; i++) { - if (items[i] instanceof MetadataRepositoryElement) - list.add(items[i]); - } - return (MetadataRepositoryElement[]) list.toArray(new MetadataRepositoryElement[list.size()]); - } - - void validateButtons() { - MetadataRepositoryElement[] elements = getSelectedElements(); - exportButton.setEnabled(elements.length > 0); - removeButton.setEnabled(elements.length > 0); - editButton.setEnabled(elements.length == 1); - refreshButton.setEnabled(elements.length == 1); - if (elements.length >= 1) { - if (toggleMeansDisable(elements)) - disableButton.setText(ProvUIMessages.RepositoryManipulationPage_DisableButton); - else - disableButton.setText(ProvUIMessages.RepositoryManipulationPage_EnableButton); - disableButton.setEnabled(true); - } else { - disableButton.setText(ProvUIMessages.RepositoryManipulationPage_EnableButton); - disableButton.setEnabled(false); - } - } - - void addRepository() { - AddRepositoryDialog dialog = new AddRepositoryDialog(getShell(), policy) { - protected RepositoryManipulator getRepositoryManipulator() { - return RepositoryManipulationPage.this.getRepositoryManipulator(); - } - }; - dialog.setTitle(manipulator.getAddOperationLabel()); - dialog.open(); - } - - void refreshRepository() { - final MetadataRepositoryElement[] selected = getSelectedElements(); - final ProvisionException[] fail = new ProvisionException[1]; - final boolean[] remove = new boolean[1]; - remove[0] = false; - if (selected.length != 1) - return; - final URI location = selected[0].getLocation(); - ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell()); - try { - dialog.run(true, true, new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) { - SubMonitor mon = SubMonitor.convert(monitor, NLS.bind(ProvUIMessages.RepositoryManipulationPage_ContactingSiteMessage, location), 300); - try { - ProvUI.clearRepositoryNotFound(location); - // If the manager doesn't know this repo, refreshing it will not work. - // We temporarily add it, but we must remove it in case the user cancels out of this page. - if (!includesRepo(manipulator.getKnownRepositories(), location)) { - // Start a batch operation so we can swallow events - ProvUI.startBatchOperation(); - AddRepositoryOperation op = manipulator.getAddOperation(location); - op.setNotify(false); - op.execute(mon.newChild(100)); - remove[0] = true; - } - ProvisioningUtil.refreshArtifactRepositories(new URI[] {location}, mon.newChild(100)); - ProvisioningUtil.refreshMetadataRepositories(new URI[] {location}, mon.newChild(100)); - } catch (ProvisionException e) { - // Need to report after dialog is closed or the error dialog will disappear when progress - // disappears - fail[0] = e; - } catch (OperationCanceledException e) { - // Catch canceled login attempts - fail[0] = new ProvisionException(new Status(IStatus.CANCEL, ProvUIActivator.PLUGIN_ID, ProvUIMessages.RepositoryManipulationPage_RefreshOperationCanceled, e)); - } finally { - // Check if the monitor was canceled - if (fail[0] == null && mon.isCanceled()) - fail[0] = new ProvisionException(new Status(IStatus.CANCEL, ProvUIActivator.PLUGIN_ID, ProvUIMessages.RepositoryManipulationPage_RefreshOperationCanceled)); - // If we temporarily added a repo so we could read it, remove it. - if (remove[0]) { - RemoveRepositoryOperation op = manipulator.getRemoveOperation(new URI[] {location}); - op.setNotify(false); - try { - op.execute(new NullProgressMonitor()); - } catch (ProvisionException e) { - // Don't report - } - // stop swallowing events - ProvUI.endBatchOperation(false); - } - } - } - }); - } catch (InvocationTargetException e) { - // nothing to report - } catch (InterruptedException e) { - // nothing to report - } - if (fail[0] != null) { - // If the repo was not found, tell ProvUI that we will be reporting it. - // We are going to report problems directly to the status manager because we - // do not want the automatic repo location editing to kick in. - if (fail[0].getStatus().getCode() == ProvisionException.REPOSITORY_NOT_FOUND) { - ProvUI.notFoundStatusReported(location); - } - if (!fail[0].getStatus().matches(IStatus.CANCEL)) { - // An error is only shown if the dialog was not canceled - ProvUI.handleException(fail[0], null, StatusManager.SHOW); - } - } else { - // Confirm that it was successful - MessageDialog.openInformation(getShell(), ProvUIMessages.RepositoryManipulationPage_TestConnectionTitle, NLS.bind(ProvUIMessages.RepositoryManipulationPage_TestConnectionSuccess, URIUtil.toUnencodedString(location))); - } - repositoryViewer.update(selected[0], null); - setDetails(); - } - - boolean includesRepo(URI[] repos, URI repo) { - for (int i = 0; i < repos.length; i++) - if (repos[i].equals(repo)) - return true; - return false; - } - - void toggleRepositoryEnablement() { - MetadataRepositoryElement[] selected = getSelectedElements(); - if (selected.length >= 1) { - boolean enableSites = !toggleMeansDisable(selected); - for (int i = 0; i < selected.length; i++) - selected[i].setEnabled(enableSites); - if (comparator.getSortKey() == RepositoryDetailsLabelProvider.COL_ENABLEMENT) - repositoryViewer.refresh(true); - else - for (int i = 0; i < selected.length; i++) - repositoryViewer.update(selected[i], null); - changed = true; - } - validateButtons(); - } - - void importRepositories() { - BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { - public void run() { - MetadataRepositoryElement[] imported = UpdateManagerCompatibility.importSites(getShell()); - if (imported.length > 0) { - Hashtable repos = getInput().cachedElements; - changed = true; - for (int i = 0; i < imported.length; i++) - repos.put(URIUtil.toUnencodedString(imported[i].getLocation()), imported[i]); - asyncRefresh(null); - } - } - }); - } - - void exportRepositories() { - BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { - public void run() { - MetadataRepositoryElement[] elements = getSelectedElements(); - if (elements.length == 0) - elements = getElements(); - UpdateManagerCompatibility.exportSites(getShell(), elements); - } - }); - } - - void changeRepositoryProperties() { - final MetadataRepositoryElement[] selected = getSelectedElements(); - if (selected.length != 1) - return; - RepositoryNameAndLocationDialog dialog = new RepositoryNameAndLocationDialog(getShell(), policy) { - protected String getInitialLocationText() { - return URIUtil.toUnencodedString(selected[0].getLocation()); - } - - protected String getInitialNameText() { - return selected[0].getName(); - } - - protected RepositoryLocationValidator getRepositoryLocationValidator() { - return new RepositoryLocationValidator() { - public IStatus validateRepositoryLocation(URI uri, boolean contactRepositories, IProgressMonitor monitor) { - if (URIUtil.sameURI(uri, selected[0].getLocation())) - return Status.OK_STATUS; - return RepositoryManipulationPage.this.getRepositoryManipulator().getRepositoryLocationValidator(getShell()).validateRepositoryLocation(uri, contactRepositories, monitor); - } - }; - } - - }; - int retCode = dialog.open(); - if (retCode == Window.OK) { - selected[0].setNickname(dialog.getName()); - selected[0].setLocation(dialog.getLocation()); - changed = true; - repositoryViewer.update(selected[0], null); - setDetails(); - } - } - - void columnSelected(TableColumn tc) { - TableColumn[] cols = table.getColumns(); - for (int i = 0; i < cols.length; i++) { - if (cols[i] == tc) { - if (i != comparator.getSortKey()) { - comparator.setSortKey(i); - table.setSortColumn(tc); - comparator.sortAscending(); - table.setSortDirection(SWT.UP); - } else { - if (comparator.isAscending()) { - table.setSortDirection(SWT.DOWN); - comparator.sortDescending(); - } else { - table.setSortDirection(SWT.UP); - comparator.sortAscending(); - } - } - repositoryViewer.refresh(); - break; - } - } - } - - void asyncRefresh(final MetadataRepositoryElement elementToSelect) { - display.asyncExec(new Runnable() { - public void run() { - repositoryViewer.refresh(); - if (elementToSelect != null) - repositoryViewer.setSelection(new StructuredSelection(elementToSelect), true); - } - }); - } - - void applyFilter() { - String text = pattern.getText(); - if (text == DEFAULT_FILTER_TEXT) - text = ""; //$NON-NLS-1$ - if (text.length() == 0) - filter.setPattern(null); - else - filter.setPattern(text); - if (filterJob != null) - filterJob.cancel(); - filterJob = new WorkbenchJob("filter job") { //$NON-NLS-1$ - public IStatus runInUIThread(IProgressMonitor monitor) { - if (monitor.isCanceled()) - return Status.CANCEL_STATUS; - if (!repositoryViewer.getTable().isDisposed()) - repositoryViewer.refresh(); - return Status.OK_STATUS; - } - - }; - filterJob.setSystem(true); - filterJob.schedule(FILTER_DELAY); - } - - void setDetails() { - MetadataRepositoryElement[] selections = getSelectedElements(); - if (selections.length == 1) { - details.setText(selections[0].getDescription()); - } else { - details.setText(""); //$NON-NLS-1$ - } - } - - /* (non-Javadoc) - * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) - */ - public void init(IWorkbench workbench) { - noDefaultAndApplyButton(); - if (policy == null) - setPolicy(Policy.getDefault()); - } - - void removeRepositories() { - MetadataRepositoryElement[] selections = getSelectedElements(); - if (selections.length > 0) { - String message = ProvUIMessages.RepositoryManipulationPage_RemoveConfirmMessage; - if (selections.length == 1) - message = NLS.bind(ProvUIMessages.RepositoryManipulationPage_RemoveConfirmSingleMessage, URIUtil.toUnencodedString(selections[0].getLocation())); - if (MessageDialog.openQuestion(getShell(), ProvUIMessages.RepositoryManipulationPage_RemoveConfirmTitle, message)) { - - changed = true; - for (int i = 0; i < selections.length; i++) { - getInput().cachedElements.remove(URIUtil.toUnencodedString(selections[i].getLocation())); - } - asyncRefresh(null); - } - } - } - - // Return a repo manipulator that only operates on the local cache. - // Labels and other presentation info are used from the original manipulator. - RepositoryManipulator getRepositoryManipulator() { - if (localCacheRepoManipulator == null) - localCacheRepoManipulator = new RepositoryManipulator() { - public AddRepositoryOperation getAddOperation(URI location) { - return new AddRepositoryOperation("Cached add repo operation", new URI[] {location}) { //$NON-NLS-1$ - protected IStatus doExecute(IProgressMonitor monitor) { - MetadataRepositoryElement element = null; - for (int i = 0; i < locations.length; i++) { - element = new MetadataRepositoryElement(getInput(), locations[i], true); - if (nicknames != null) - element.setNickname(nicknames[i]); - getInput().cachedElements.put(URIUtil.toUnencodedString(locations[i]), element); - } - changed = true; - asyncRefresh(element); - return Status.OK_STATUS; - } - - protected IStatus doBatchedExecute(IProgressMonitor monitor) { - // Not called due to override of doExecute - return null; - } - - protected void setNickname(URI loc, String nickname) { - // Not called due to override of doExecute - } - }; - } - - public String getAddOperationLabel() { - return manipulator.getAddOperationLabel(); - } - - public URI[] getKnownRepositories() { - return RepositoryManipulationPage.this.getKnownRepositories(); - } - - public String getManipulatorButtonLabel() { - return manipulator.getManipulatorButtonLabel(); - } - - public String getManipulatorLinkLabel() { - return manipulator.getManipulatorLinkLabel(); - } - - public RemoveRepositoryOperation getRemoveOperation(URI[] repoLocations) { - return new RemoveRepositoryOperation("Cached remove repo operation", repoLocations) { //$NON-NLS-1$ - protected IStatus doBatchedExecute(IProgressMonitor monitor) { - removeRepositories(); - return Status.OK_STATUS; - } - }; - } - - public String getRemoveOperationLabel() { - return manipulator.getRemoveOperationLabel(); - } - - public RepositoryLocationValidator getRepositoryLocationValidator(Shell shell) { - return new DefaultMetadataURLValidator() { - protected URI[] getKnownLocations() { - return getKnownRepositories(); - } - }; - } - - public boolean manipulateRepositories(Shell shell) { - // we are the manipulator - return true; - } - - public String getManipulatorInstructionString() { - // we are the manipulator - return null; - } - - public String getRepositoryNotFoundInstructionString() { - // we are in the manipulator, no further instructions - return null; - } - - }; - return localCacheRepoManipulator; - } - - public void copyToClipboard(Control activeControl) { - MetadataRepositoryElement[] elements = getSelectedElements(); - if (elements.length == 0) - elements = getElements(); - String text = ""; //$NON-NLS-1$ - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < elements.length; i++) { - buffer.append(labelProvider.getClipboardText(elements[i], CopyUtils.DELIMITER)); - if (i > 0) - buffer.append(CopyUtils.NEWLINE); - } - text = buffer.toString(); - - if (text.length() == 0) - return; - Clipboard clipboard = new Clipboard(PlatformUI.getWorkbench().getDisplay()); - clipboard.setContents(new Object[] {text}, new Transfer[] {TextTransfer.getInstance()}); - clipboard.dispose(); - } - - // If more than half of the selected repos are enabled, toggle means disable. - // Otherwise it means enable. - private boolean toggleMeansDisable(MetadataRepositoryElement[] elements) { - double count = 0; - for (int i = 0; i < elements.length; i++) - if (elements[i].isEnabled()) - count++; - return (count / elements.length) > 0.5; - } - - URI[] getKnownRepositories() { - MetadataRepositoryElement[] elements = getElements(); - URI[] locations = new URI[elements.length]; - for (int i = 0; i < elements.length; i++) - locations[i] = elements[i].getLocation(); - return locations; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RepositorySelectionGroup.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RepositorySelectionGroup.java deleted file mode 100644 index 2d1ca3901..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RepositorySelectionGroup.java +++ /dev/null @@ -1,634 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Yury Chernikov - Bug 271447 [ui] Bad layout in 'Install available software' dialog - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import com.ibm.icu.text.Collator; -import java.lang.reflect.InvocationTargetException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.*; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.UIRepositoryEvent; -import org.eclipse.equinox.internal.p2.ui.dialogs.ComboAutoCompleteField; -import org.eclipse.equinox.internal.p2.ui.dialogs.URLDropAdapter; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.repository.*; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIProvisioningListener; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.*; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.fieldassist.ControlDecoration; -import org.eclipse.jface.fieldassist.FieldDecorationRegistry; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.wizard.IWizardContainer; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.SWT; -import org.eclipse.swt.dnd.*; -import org.eclipse.swt.events.*; -import org.eclipse.swt.graphics.*; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.*; -import org.eclipse.ui.statushandlers.StatusManager; - -/** - * A RepositorySelectionGroup is a reusable UI component that displays - * available repositories and allows the user to select them. - * - * @since 3.5 - */ -public class RepositorySelectionGroup { - - private static final String SITE_NONE = ProvUIMessages.AvailableIUsPage_NoSites; - private static final String SITE_ALL = ProvUIMessages.AvailableIUsPage_AllSites; - private static final String SITE_LOCAL = ProvUIMessages.AvailableIUsPage_LocalSites; - private static final int INDEX_SITE_NONE = 0; - private static final int INDEX_SITE_ALL = 1; - private static final int DEC_MARGIN_WIDTH = 2; - private static final String LINKACTION = "linkAction"; //$NON-NLS-1$ - - // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=245569 - private static final int COUNT_VISIBLE_ITEMS = 20; - IWizardContainer container; - Policy policy; - IUViewQueryContext queryContext; - - ListenerList listeners = new ListenerList(); - - Combo repoCombo; - Link repoManipulatorLink; - ControlDecoration repoDec; - ComboAutoCompleteField repoAutoComplete; - ProvUIProvisioningListener comboRepoListener; - - Image info, warning, error; - URI[] comboRepos; // the URIs shown in the combo, kept in sync with combo items - HashMap disabledRepoProposals = new HashMap(); // proposal string -> disabled URI - - public RepositorySelectionGroup(IWizardContainer container, Composite parent, Policy policy, IUViewQueryContext queryContext) { - this.container = container; - this.queryContext = queryContext; - this.policy = policy; - createControl(parent); - } - - public Control getDefaultFocusControl() { - return repoCombo; - } - - public void addRepositorySelectionListener(IRepositorySelectionListener listener) { - listeners.add(listener); - } - - protected void createControl(Composite parent) { - // Get the possible field error indicators - info = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_INFORMATION).getImage(); - warning = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_WARNING).getImage(); - error = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_ERROR).getImage(); - - // Combo that filters sites - Composite comboComposite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginTop = 0; - layout.marginBottom = IDialogConstants.VERTICAL_SPACING; - layout.numColumns = 3; - comboComposite.setLayout(layout); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); - comboComposite.setLayoutData(gd); - - Label label = new Label(comboComposite, SWT.NONE); - label.setText(ProvUIMessages.AvailableIUsPage_RepoFilterLabel); - - repoCombo = new Combo(comboComposite, SWT.DROP_DOWN); - repoCombo.addSelectionListener(new SelectionListener() { - - public void widgetDefaultSelected(SelectionEvent e) { - repoComboSelectionChanged(); - } - - public void widgetSelected(SelectionEvent e) { - repoComboSelectionChanged(); - } - - }); - // Auto complete - install before our own key listeners, so that auto complete gets first shot. - repoAutoComplete = new ComboAutoCompleteField(repoCombo); - repoCombo.setVisibleItemCount(COUNT_VISIBLE_ITEMS); - repoCombo.addKeyListener(new KeyAdapter() { - - public void keyPressed(KeyEvent e) { - if (e.keyCode == SWT.CR) - addRepository(false); - } - }); - - // We don't ever want this to be interpreted as a default - // button event - repoCombo.addTraverseListener(new TraverseListener() { - public void keyTraversed(TraverseEvent e) { - if (e.detail == SWT.TRAVERSE_RETURN) { - e.doit = false; - } - } - }); - - gd = new GridData(SWT.FILL, SWT.CENTER, true, false); - // breathing room for info dec - gd.horizontalIndent = DEC_MARGIN_WIDTH * 2; - repoCombo.setLayoutData(gd); - repoCombo.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent event) { - URI location = null; - IStatus status = null; - String text = repoCombo.getText().trim(); - int index = getComboIndex(text); - // only validate text that doesn't match existing text in combo - if (index < 0) { - location = RepositoryLocationValidator.locationFromString(repoCombo.getText()); - if (location == null) { - status = RepositoryLocationValidator.getInvalidLocationStatus(repoCombo.getText()); - } else { - RepositoryLocationValidator validator = policy.getRepositoryManipulator().getRepositoryLocationValidator(repoCombo.getShell()); - status = validator.validateRepositoryLocation(location, false, new NullProgressMonitor()); - } - } else { - // user typed or pasted an existing location. Select it. - repoComboSelectionChanged(); - } - setRepoComboDecoration(status); - } - }); - - repoDec = new ControlDecoration(repoCombo, SWT.LEFT | SWT.TOP); - repoDec.setMarginWidth(DEC_MARGIN_WIDTH); - - DropTarget target = new DropTarget(repoCombo, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK); - target.setTransfer(new Transfer[] {URLTransfer.getInstance(), FileTransfer.getInstance()}); - target.addDropListener(new URLDropAdapter(true) { - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.dialogs.URLDropAdapter#handleURLString(java.lang.String, org.eclipse.swt.dnd.DropTargetEvent) - */ - protected void handleDrop(String urlText, DropTargetEvent event) { - repoCombo.setText(urlText); - event.detail = DND.DROP_LINK; - addRepository(false); - } - }); - - Button button = new Button(comboComposite, SWT.PUSH); - button.setText(ProvUIMessages.AvailableIUsPage_AddButton); - button.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - addRepository(true); - } - - public void widgetSelected(SelectionEvent e) { - addRepository(true); - } - }); - setButtonLayoutData(button); - - // Link to repository manipulator - repoManipulatorLink = createLink(comboComposite, new Action() { - public void runWithEvent(Event event) { - policy.getRepositoryManipulator().manipulateRepositories(repoCombo.getShell()); - } - }, policy.getRepositoryManipulator().getManipulatorLinkLabel()); - gd = new GridData(SWT.END, SWT.FILL, true, false); - gd.horizontalSpan = 3; - repoManipulatorLink.setLayoutData(gd); - - addComboProvisioningListeners(); - parent.addDisposeListener(new DisposeListener() { - public void widgetDisposed(DisposeEvent e) { - removeProvisioningListeners(); - } - - }); - } - - private void setButtonLayoutData(Button button) { - GridData data = new GridData(SWT.FILL, SWT.CENTER, false, false); - GC gc = new GC(button); - gc.setFont(JFaceResources.getDialogFont()); - FontMetrics fm = gc.getFontMetrics(); - gc.dispose(); - int widthHint = Dialog.convertHorizontalDLUsToPixels(fm, IDialogConstants.BUTTON_WIDTH); - Point minSize = button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); - data.widthHint = Math.max(widthHint, minSize.x); - button.setLayoutData(data); - } - - public void setRepositorySelection(int scope, URI location) { - switch (scope) { - case AvailableIUGroup.AVAILABLE_ALL : - fillRepoCombo(SITE_ALL); - break; - case AvailableIUGroup.AVAILABLE_LOCAL : - fillRepoCombo(SITE_LOCAL); - break; - case AvailableIUGroup.AVAILABLE_SPECIFIED : - fillRepoCombo(getSiteString(location)); - break; - default : - fillRepoCombo(SITE_NONE); - } - setRepoComboDecoration(null); - } - - protected void setRepoComboDecoration(final IStatus status) { - if (status == null || status.isOK() || status.getSeverity() == IStatus.CANCEL) { - repoDec.setShowOnlyOnFocus(true); - repoDec.setDescriptionText(ProvUIMessages.AvailableIUsPage_RepoFilterInstructions); - repoDec.setImage(info); - // We may have been previously showing an error or warning - // hover. We will need to dismiss it, but if there is no text - // typed, don't do this, so that the user gets the info cue - if (repoCombo.getText().length() > 0) - repoDec.showHoverText(null); - return; - } - Image image; - if (status.getSeverity() == IStatus.WARNING) - image = warning; - else if (status.getSeverity() == IStatus.ERROR) - image = error; - else - image = info; - repoDec.setImage(image); - repoDec.setDescriptionText(status.getMessage()); - repoDec.setShowOnlyOnFocus(false); - // use a delay to show the validation method because the very next - // selection or keystroke might fix it - repoCombo.getDisplay().timerExec(500, new Runnable() { - public void run() { - if (repoDec != null && repoDec.getImage() != info) - repoDec.showHoverText(status.getMessage()); - } - }); - - } - - /* - * Fill the repo combo and use the specified string - * as the selection. If the selection is null, then the - * current selection should be preserved if applicable. - */ - void fillRepoCombo(final String selection) { - URI[] sites = policy.getRepositoryManipulator().getKnownRepositories(); - boolean hasLocalSites = getLocalSites().length > 0; - final String[] items; - if (hasLocalSites) { - // None, All, repo1, repo2....repo n, Local - comboRepos = new URI[sites.length + 3]; - items = new String[sites.length + 3]; - } else { - // None, All, repo1, repo2....repo n - comboRepos = new URI[sites.length + 2]; - items = new String[sites.length + 2]; - } - items[INDEX_SITE_NONE] = SITE_NONE; - items[INDEX_SITE_ALL] = SITE_ALL; - for (int i = 0; i < sites.length; i++) { - items[i + 2] = getSiteString(sites[i]); - comboRepos[i + 2] = sites[i]; - } - if (hasLocalSites) - items[items.length - 1] = SITE_LOCAL; - if (sites.length > 0) - sortRepoItems(items, comboRepos, hasLocalSites); - Runnable runnable = new Runnable() { - public void run() { - if (repoCombo == null || repoCombo.isDisposed()) - return; - String repoToSelect = selection; - if (repoToSelect == null) { - // If the combo is open and something is selected, use that index if we - // weren't given a string to select. - int selIndex = repoCombo.getSelectionIndex(); - if (selIndex >= 0) - repoToSelect = repoCombo.getItem(selIndex); - else - repoToSelect = repoCombo.getText(); - } - repoCombo.setItems(items); - repoAutoComplete.setProposalStrings(getComboProposals()); - boolean selected = false; - for (int i = 0; i < items.length; i++) - if (items[i].equals(repoToSelect)) { - selected = true; - if (repoCombo.getListVisible()) - repoCombo.select(i); - repoCombo.setText(repoToSelect); - break; - } - if (!selected) { - if (repoCombo.getListVisible()) - repoCombo.select(INDEX_SITE_NONE); - repoCombo.setText(SITE_NONE); - } - repoComboSelectionChanged(); - } - }; - // Only run the UI code async if we have to. If we always async the code, - // the automated tests (which are in the UI thread) can get out of sync - if (Display.getCurrent() == null) - repoCombo.getDisplay().asyncExec(runnable); - else - runnable.run(); - } - - String getSiteString(URI uri) { - try { - String nickname = ProvisioningUtil.getMetadataRepositoryProperty(uri, IRepository.PROP_NICKNAME); - if (nickname != null && nickname.length() > 0) - return NLS.bind(ProvUIMessages.AvailableIUsPage_NameWithLocation, nickname, URIUtil.toUnencodedString(uri)); - } catch (ProvisionException e) { - // No error, just use the location string - } - return URIUtil.toUnencodedString(uri); - } - - private Link createLink(Composite parent, IAction action, String text) { - Link link = new Link(parent, SWT.PUSH); - link.setText(text); - - link.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event event) { - IAction linkAction = getLinkAction(event.widget); - if (linkAction != null) { - linkAction.runWithEvent(event); - } - } - }); - link.setToolTipText(action.getToolTipText()); - link.setData(LINKACTION, action); - return link; - } - - IAction getLinkAction(Widget widget) { - Object data = widget.getData(LINKACTION); - if (data == null || !(data instanceof IAction)) { - return null; - } - return (IAction) data; - } - - private void sortRepoItems(String[] strings, URI[] locations, boolean hasLocalSites) { - int sortStart = 2; - int sortEnd = hasLocalSites ? strings.length - 2 : strings.length - 1; - if (sortStart >= sortEnd) - return; - final HashMap uriToString = new HashMap(); - for (int i = sortStart; i <= sortEnd; i++) { - uriToString.put(locations[i], strings[i]); - } - final Collator collator = Collator.getInstance(Locale.getDefault()); - Comparator stringComparator = new Comparator() { - public int compare(Object a, Object b) { - return collator.compare(a, b); - } - }; - Comparator uriComparator = new Comparator() { - public int compare(Object a, Object b) { - return collator.compare(uriToString.get(a), uriToString.get(b)); - } - }; - - Arrays.sort(strings, sortStart, sortEnd, stringComparator); - Arrays.sort(locations, sortStart, sortEnd, uriComparator); - } - - private URI[] getLocalSites() { - // use our current visibility flags plus the local filter - int flags = queryContext.getMetadataRepositoryFlags() | IRepositoryManager.REPOSITORIES_LOCAL; - try { - return ProvisioningUtil.getMetadataRepositories(flags); - } catch (ProvisionException e) { - return null; - } - } - - String[] getComboProposals() { - // Include all the combo items plus disabled sites - try { - int flags = queryContext.getMetadataRepositoryFlags() | IRepositoryManager.REPOSITORIES_DISABLED; - String[] items = repoCombo.getItems(); - // Clear any previously remembered disabled repos - disabledRepoProposals = new HashMap(); - URI[] disabled = ProvisioningUtil.getMetadataRepositories(flags); - String[] disabledItems = new String[disabled.length]; - for (int i = 0; i < disabledItems.length; i++) { - disabledItems[i] = getSiteString(disabled[i]); - disabledRepoProposals.put(disabledItems[i], disabled[i]); - } - String[] both = new String[items.length + disabledItems.length]; - System.arraycopy(items, 0, both, 0, items.length); - System.arraycopy(disabledItems, 0, both, items.length, disabledItems.length); - return both; - } catch (ProvisionException e) { - return new String[0]; - } - } - - int getComboIndex(String repoText) { - // Callers have typically done this already, but just in case - repoText = repoText.trim(); - // First look for exact match to the combo string. - // This includes the name, etc. - if (repoText.length() > 0) { - String[] items = repoCombo.getItems(); - for (int i = 0; i < items.length; i++) - if (repoText.equals(items[i])) { - return i; - } - } - // Look for URI match - the user may have pasted or dragged - // in a location that matches one we already know about, even - // if the text does not match completely. (slashes, no name, etc.) - try { - URI location = URIUtil.fromString(repoText); - for (int i = 0; i < comboRepos.length; i++) - if (URIUtil.sameURI(location, comboRepos[i])) { - return i; - } - } catch (URISyntaxException e) { - // never mind - } - return -1; - } - - void addComboProvisioningListeners() { - // We need to monitor repository events so that we can adjust the repo combo. - comboRepoListener = new ProvUIProvisioningListener(ProvUIProvisioningListener.PROV_EVENT_METADATA_REPOSITORY) { - protected void repositoryAdded(RepositoryEvent e) { - if (e instanceof UIRepositoryEvent) { - fillRepoCombo(getSiteString(e.getRepositoryLocation())); - } - } - - protected void repositoryRemoved(RepositoryEvent e) { - fillRepoCombo(null); - } - - protected void refreshAll() { - fillRepoCombo(null); - } - }; - ProvUI.addProvisioningListener(comboRepoListener); - } - - void removeProvisioningListeners() { - if (comboRepoListener != null) { - ProvUI.removeProvisioningListener(comboRepoListener); - comboRepoListener = null; - } - - } - - /* - * Add a repository using the text in the combo or launch a dialog if the text - * represents an already known repo. For any add operation spawned by this - * method, we do not want to notify the UI with a special listener. This is to - * prevent a multiple update flash because we intend to reset the available IU - * filter as soon as the new repo is added. - */ - void addRepository(boolean alwaysPrompt) { - final RepositoryManipulator manipulator = policy.getRepositoryManipulator(); - final String selectedRepo = repoCombo.getText().trim(); - int selectionIndex = getComboIndex(selectedRepo); - final boolean isNewText = selectionIndex < 0; - // If we are adding something already in the combo, just - // select that item. - if (!alwaysPrompt && !isNewText && selectionIndex != repoCombo.getSelectionIndex()) { - repoComboSelectionChanged(); - } else if (alwaysPrompt) { - AddRepositoryDialog dialog = new AddRepositoryDialog(repoCombo.getShell(), policy) { - protected AddRepositoryOperation getOperation(URI repositoryLocation) { - AddRepositoryOperation op = manipulator.getAddOperation(repositoryLocation); - op.setNotify(false); - return op; - } - - protected String getInitialLocationText() { - if (isNewText) - return selectedRepo; - return super.getInitialLocationText(); - } - - }; - dialog.setTitle(manipulator.getAddOperationLabel()); - dialog.open(); - URI location = dialog.getAddedLocation(); - if (location != null) - fillRepoCombo(getSiteString(location)); - } else if (isNewText) { - try { - container.run(false, false, new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) { - URI location; - IStatus status; - // This might be a disabled repo. If so, no need to validate further. - if (disabledRepoProposals.containsKey(selectedRepo)) { - location = (URI) disabledRepoProposals.get(selectedRepo); - status = Status.OK_STATUS; - } else { - location = RepositoryLocationValidator.locationFromString(selectedRepo); - if (location == null) - status = RepositoryLocationValidator.getInvalidLocationStatus(selectedRepo); - else { - RepositoryLocationValidator validator = manipulator.getRepositoryLocationValidator(repoCombo.getShell()); - status = validator.validateRepositoryLocation(location, false, monitor); - } - } - if (status.isOK() && location != null) { - try { - RepositoryOperation op = manipulator.getAddOperation(location); - op.setNotify(false); - op.execute(monitor); - fillRepoCombo(getSiteString(location)); - } catch (ProvisionException e) { - // TODO Auto-generated catch block - ProvUI.handleException(e, null, StatusManager.SHOW); - } - } - setRepoComboDecoration(status); - } - }); - } catch (InvocationTargetException e) { - // ignore - } catch (InterruptedException e) { - // ignore - } - } - } - - public ProvisioningContext getProvisioningContext() { - int siteSel = getComboIndex(repoCombo.getText().trim()); - if (siteSel < 0 || siteSel == INDEX_SITE_ALL || siteSel == INDEX_SITE_NONE) - return new ProvisioningContext(); - URI[] locals = getLocalSites(); - // If there are local sites, the last item in the combo is "Local Sites Only" - // Use all local sites in this case - // We have to set metadata repositories and artifact repositories in the - // provisioning context because the artifact repositories are used for - // sizing. - if (locals.length > 0 && siteSel == repoCombo.getItemCount() - 1) { - ProvisioningContext context = new ProvisioningContext(locals); - context.setArtifactRepositories(locals); - return context; - } - // A single site is selected. - ProvisioningContext context = new ProvisioningContext(new URI[] {comboRepos[siteSel]}); - context.setArtifactRepositories(new URI[] {comboRepos[siteSel]}); - return context; - } - - void repoComboSelectionChanged() { - int repoChoice = -1; - URI repoLocation = null; - - int selection = -1; - if (repoCombo.getListVisible()) { - selection = repoCombo.getSelectionIndex(); - } else { - selection = getComboIndex(repoCombo.getText().trim()); - } - int localIndex = getLocalSites().length == 0 ? repoCombo.getItemCount() : repoCombo.getItemCount() - 1; - if (comboRepos == null || selection < 0) { - selection = INDEX_SITE_NONE; - } - - if (selection == INDEX_SITE_NONE) { - repoChoice = AvailableIUGroup.AVAILABLE_NONE; - } else if (selection == INDEX_SITE_ALL) { - repoChoice = AvailableIUGroup.AVAILABLE_ALL; - } else if (selection >= localIndex) { - repoChoice = AvailableIUGroup.AVAILABLE_LOCAL; - } else { - repoChoice = AvailableIUGroup.AVAILABLE_SPECIFIED; - repoLocation = comboRepos[selection]; - } - - Object[] selectionListeners = listeners.getListeners(); - for (int i = 0; i < selectionListeners.length; i++) { - ((IRepositorySelectionListener) selectionListeners[i]).repositorySelectionChanged(repoChoice, repoLocation); - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RevertProfilePage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RevertProfilePage.java deleted file mode 100644 index 10fa97899..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RevertProfilePage.java +++ /dev/null @@ -1,547 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.util.*; -import org.eclipse.compare.*; -import org.eclipse.compare.structuremergeviewer.Differencer; -import org.eclipse.compare.structuremergeviewer.IStructureComparator; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.dialogs.CopyUtils; -import org.eclipse.equinox.internal.p2.ui.dialogs.ICopyable; -import org.eclipse.equinox.internal.p2.ui.model.*; -import org.eclipse.equinox.internal.p2.ui.viewers.DeferredQueryContentProvider; -import org.eclipse.equinox.internal.p2.ui.viewers.IUDetailsLabelProvider; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.model.InstalledIUElement; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.*; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.viewers.*; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.dialogs.*; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.viewers.*; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.dnd.*; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.*; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.about.InstallationPage; -import org.eclipse.ui.menus.AbstractContributionFactory; -import org.eclipse.ui.statushandlers.StatusManager; - -/** - * @since 3.4 - */ -public class RevertProfilePage extends InstallationPage implements ICopyable { - - private static final int REVERT_ID = IDialogConstants.CLIENT_ID; - private static final int DELETE_ID = IDialogConstants.CLIENT_ID + 1; - private static final int COMPARE_ID = IDialogConstants.CLIENT_ID + 2; - TableViewer configsViewer; - TreeViewer configContentsViewer; - IUDetailsLabelProvider labelProvider; - IAction revertAction; - Button revertButton, deleteButton, compareButton; - String profileId; - AbstractContributionFactory factory; - Text detailsArea; - InstalledIUGroup installedIUGroup; - - public void createPageButtons(Composite parent) { - if (profileId == null) - return; - compareButton = createButton(parent, COMPARE_ID, ProvUIMessages.RevertProfilePage_CompareLabel); - compareButton.setToolTipText(ProvUIMessages.RevertProfilePage_CompareTooltip); - compareButton.setEnabled(computeCompareEnablement()); - deleteButton = createButton(parent, DELETE_ID, ProvUIMessages.RevertProfilePage_Delete); - deleteButton.setToolTipText(ProvUIMessages.RevertProfilePage_DeleteTooltip); - deleteButton.setEnabled(computeDeleteEnablement()); - revertButton = createButton(parent, REVERT_ID, revertAction.getText()); - revertButton.setToolTipText(revertAction.getToolTipText()); - revertButton.setEnabled(revertAction.isEnabled()); - } - - public void createControl(Composite parent) { - profileId = Policy.getDefault().getProfileChooser().getProfileId(ProvUI.getDefaultParentShell()); - if (profileId == null) { - IStatus status = Policy.getDefault().getNoProfileChosenStatus(); - if (status != null) - ProvUI.reportStatus(status, StatusManager.LOG); - Text text = new Text(parent, SWT.WRAP | SWT.READ_ONLY); - text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - text.setText(ProvUIMessages.RevertProfilePage_NoProfile); - setControl(text); - return; - } - - initializeDialogUnits(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IProvHelpContextIds.REVERT_CONFIGURATION_WIZARD); - - SashForm sashForm = new SashForm(parent, SWT.VERTICAL); - sashForm.setLayout(new GridLayout()); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - sashForm.setLayoutData(gd); - - createConfigurationsSection(sashForm); - createContentsSection(sashForm); - setControl(sashForm); - - // prime the selection. The selection accesses the - // revert action, so create it also. - createRevertAction(); - } - - private void createConfigurationsSection(Composite parent) { - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - composite.setLayout(layout); - GridData gd = new GridData(GridData.FILL_BOTH); - composite.setLayoutData(gd); - - Label label = new Label(composite, SWT.NONE); - label.setText(ProvUIMessages.RevertDialog_ConfigsLabel); - configsViewer = new TableViewer(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); - ProvElementContentProvider provider = new ProvElementContentProvider() { - protected void finishedFetchingElements(Object o) { - Object element = configsViewer.getElementAt(0); - if (element != null) - configsViewer.setSelection(new StructuredSelection(element)); - } - }; - configsViewer.setContentProvider(provider); - configsViewer.setLabelProvider(new ProvElementLabelProvider()); - configsViewer.setComparator(new ViewerComparator() { - // We override the ViewerComparator so that we don't get the labels of the elements - // for comparison, but rather get the timestamps and compare them. - // Reverse sorting is used so that newest is first. - public int compare(Viewer viewer, Object o1, Object o2) { - if (o1 instanceof RollbackProfileElement && o2 instanceof RollbackProfileElement) { - long timestamp1 = ((RollbackProfileElement) o1).getTimestamp(); - long timestamp2 = ((RollbackProfileElement) o2).getTimestamp(); - if (timestamp1 > timestamp2) - return -1; - return 1; - } - // this is naive (doesn't consult the label provider), but shouldn't happen - return o2.toString().compareTo(o1.toString()); - } - }); - configsViewer.setInput(getInput()); - - configsViewer.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - handleSelectionChanged((IStructuredSelection) event.getSelection()); - } - - }); - CopyUtils.activateCopy(this, configsViewer.getControl()); - gd = new GridData(SWT.FILL, SWT.FILL, true, true); - configsViewer.getControl().setLayoutData(gd); - } - - private void createContentsSection(Composite parent) { - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - composite.setLayout(layout); - GridData gd = new GridData(GridData.FILL_BOTH); - composite.setLayoutData(gd); - - Label label = new Label(composite, SWT.NONE); - label.setText(ProvUIMessages.RevertDialog_ConfigContentsLabel); - configContentsViewer = new TreeViewer(composite, SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); - IUComparator comparator = new IUComparator(IUComparator.IU_NAME); - comparator.useColumnConfig(ProvUI.getIUColumnConfig()); - configContentsViewer.setComparator(comparator); - configContentsViewer.setComparer(new ProvElementComparer()); - configContentsViewer.setContentProvider(new DeferredQueryContentProvider()); - - // columns before labels or you get a blank table - setTreeColumns(configContentsViewer.getTree()); - labelProvider = new IUDetailsLabelProvider(); - configContentsViewer.setLabelProvider(labelProvider); - - gd = new GridData(GridData.FILL_BOTH); - configContentsViewer.getControl().setLayoutData(gd); - CopyUtils.activateCopy(this, configContentsViewer.getControl()); - } - - private void createRevertAction() { - revertAction = new Action() { - public void run() { - boolean result = MessageDialog.openQuestion(getShell(), ProvUIMessages.RevertDialog_Title, ProvUIMessages.RevertDialog_ConfirmRestartMessage); - if (!result) - return; - boolean finish = revert(); - if (finish) { - getPageContainer().closeModalContainers(); - } - } - }; - revertAction.setText(ProvUIMessages.RevertProfilePage_RevertLabel); - revertAction.setToolTipText(ProvUIMessages.RevertProfilePage_RevertTooltip); - } - - private Object getInput() { - ProfileSnapshots element = new ProfileSnapshots(profileId); - return element; - } - - protected void buttonPressed(int buttonId) { - switch (buttonId) { - case REVERT_ID : - revertAction.run(); - break; - case COMPARE_ID : - compare(); - break; - case DELETE_ID : - deleteSelectedSnapshots(); - break; - } - } - - void handleSelectionChanged(IStructuredSelection selection) { - if (!selection.isEmpty()) { - if (selection.size() == 1) { - final Object selected = selection.getFirstElement(); - if (selected instanceof RollbackProfileElement) { - Object[] elements = configContentsViewer.getExpandedElements(); - configContentsViewer.getTree().setRedraw(false); - configContentsViewer.setInput(selected); - configContentsViewer.setExpandedElements(elements); - configContentsViewer.getTree().setRedraw(true); - boolean isNotCurrentProfile = !((RollbackProfileElement) selected).isCurrentProfile(); - revertAction.setEnabled(isNotCurrentProfile); - if (revertButton != null) - revertButton.setEnabled(isNotCurrentProfile); - if (deleteButton != null) - deleteButton.setEnabled(isNotCurrentProfile); - if (compareButton != null) - compareButton.setEnabled(false); - return; - } - } else { - // multiple selections, can't revert or look at details - revertAction.setEnabled(false); - if (revertButton != null) { - revertButton.setEnabled(false); - } - configContentsViewer.setInput(null); - deleteButton.setEnabled(computeDeleteEnablement()); - compareButton.setEnabled(computeCompareEnablement()); - return; - } - } - // Nothing is selected - configContentsViewer.setInput(null); - revertAction.setEnabled(false); - if (revertButton != null) - revertButton.setEnabled(false); - if (deleteButton != null) - deleteButton.setEnabled(computeDeleteEnablement()); - } - - boolean computeDeleteEnablement() { - // delete is permitted if none of the selected elements are the current profile - boolean okToDelete = true; - Iterator iter = ((IStructuredSelection) configsViewer.getSelection()).iterator(); - while (iter.hasNext()) { - Object selected = iter.next(); - // If it's not a recognized element or if it is the current profile, we can't delete. Stop iterating. - if (!(selected instanceof RollbackProfileElement) || ((RollbackProfileElement) selected).isCurrentProfile()) { - okToDelete = false; - break; - } - } - return okToDelete; - } - - boolean computeCompareEnablement() { - // compare is enabled if there are two elements selected - Object[] selection = ((IStructuredSelection) configsViewer.getSelection()).toArray(); - if (selection.length == 2) { - for (int i = 0; i < selection.length; i++) { - if (!(selection[i] instanceof RollbackProfileElement)) - return false; - } - return true; - } - return false; - } - - private void setTreeColumns(Tree tree) { - IUColumnConfig[] columns = ProvUI.getIUColumnConfig(); - tree.setHeaderVisible(true); - - for (int i = 0; i < columns.length; i++) { - TreeColumn tc = new TreeColumn(tree, SWT.NONE, i); - tc.setResizable(true); - tc.setText(columns[i].getColumnTitle()); - tc.setWidth(columns[i].getWidthInPixels(tree)); - } - } - - private IProfile getSelectedSnapshot() { - Object selected = ((IStructuredSelection) configsViewer.getSelection()).getFirstElement(); - if (selected != null && selected instanceof RollbackProfileElement) - try { - return ((RollbackProfileElement) selected).getProfileSnapshot(new NullProgressMonitor()); - } catch (ProvisionException e) { - ProvUI.handleException(e, null, StatusManager.LOG); - } - return null; - } - - private RollbackProfileElement[] getRollbackProfileElementsToCompare() { - // expecting two items selected - RollbackProfileElement[] result = new RollbackProfileElement[2]; - IStructuredSelection selection = ((IStructuredSelection) configsViewer.getSelection()); - int i = 0; - for (Iterator iterator = selection.toList().iterator(); iterator.hasNext();) { - Object selected = iterator.next(); - if (selected != null && selected instanceof RollbackProfileElement) { - result[i++] = (RollbackProfileElement) selected; - } - if (i == 2) - break; - } - return result; - } - - boolean revert() { - final IProfile snapshot = getSelectedSnapshot(); - if (snapshot == null) - return false; - final ProvisioningPlan[] plan = new ProvisioningPlan[1]; - IRunnableWithProgress runnable = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) { - IProfile currentProfile; - try { - currentProfile = ProvisioningUtil.getProfile(profileId); - plan[0] = ProvisioningUtil.getRevertPlan(currentProfile, snapshot, monitor); - } catch (ProvisionException e) { - ProvUI.handleException(e, null, StatusManager.SHOW | StatusManager.LOG); - } - } - }; - ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell()); - try { - dialog.run(true, true, runnable); - } catch (InvocationTargetException e) { - ProvUI.handleException(e.getCause(), null, StatusManager.SHOW | StatusManager.LOG); - } catch (InterruptedException e) { - // nothing to report - } - // the dialog does not throw OperationCanceledException so we have to - // check the monitor - if (dialog.getProgressMonitor().isCanceled()) - return false; - - boolean reverted = false; - if (plan[0] != null) { - if (plan[0].getStatus().isOK()) { - // We use a default provisioning context (all repos) because we have no other - // way currently to figure out which sites the user wants to contact - ProvisioningOperation op = new ProfileModificationOperation(ProvUIMessages.RevertDialog_RevertOperationLabel, profileId, plan[0], new ProvisioningContext(), new DefaultPhaseSet(), true); - ProvisioningOperationRunner.schedule(op, StatusManager.SHOW | StatusManager.LOG); - ProvisioningOperationRunner.requestRestart(true); - reverted = true; - } else if (plan[0].getStatus().getSeverity() != IStatus.CANCEL) { - ProvUI.reportStatus(plan[0].getStatus(), StatusManager.LOG | StatusManager.SHOW); - // This message has no effect in an installation dialog - // setMessage(ProvUIMessages.ProfileModificationWizardPage_UnexpectedError, IMessageProvider.ERROR); - } - } - return reverted; - } - - void compare() { - final RollbackProfileElement[] rpe = getRollbackProfileElementsToCompare(); - CompareUI.openCompareDialog(new ProfileCompareEditorInput(rpe)); - } - - private class ProfileCompareEditorInput extends CompareEditorInput { - private Object root; - private ProvElementNode l; - private ProvElementNode r; - - public ProfileCompareEditorInput(RollbackProfileElement[] rpe) { - super(new CompareConfiguration()); - Assert.isTrue(rpe.length == 2); - l = new ProvElementNode(rpe[0]); - r = new ProvElementNode(rpe[1]); - } - - protected Object prepareInput(IProgressMonitor monitor) { - initLabels(); - Differencer d = new Differencer(); - root = d.findDifferences(false, monitor, null, null, l, r); - return root; - } - - private void initLabels() { - CompareConfiguration cc = getCompareConfiguration(); - cc.setLeftEditable(false); - cc.setRightEditable(false); - cc.setLeftLabel(l.getName()); - cc.setLeftImage(l.getImage()); - cc.setRightLabel(r.getName()); - cc.setRightImage(r.getImage()); - } - - public String getOKButtonLabel() { - return IDialogConstants.OK_LABEL; - } - } - - private class ProvElementNode implements IStructureComparator, ITypedElement, IStreamContentAccessor { - private ProvElement pe; - private IInstallableUnit iu; - final static String BLANK = ""; //$NON-NLS-1$ - private String id = BLANK; - - public ProvElementNode(Object input) { - pe = (ProvElement) input; - iu = (IInstallableUnit) ProvUI.getAdapter(pe, IInstallableUnit.class); - if (iu != null) { - id = iu.getId(); - } - } - - public Object[] getChildren() { - Set children = new HashSet(); - if (pe instanceof RollbackProfileElement) { - Object[] c = ((RollbackProfileElement) pe).getChildren(null); - for (int i = 0; i < c.length; i++) { - children.add(new ProvElementNode(c[i])); - } - } else if (pe instanceof InstalledIUElement) { - Object[] c = ((InstalledIUElement) pe).getChildren(null); - for (int i = 0; i < c.length; i++) { - children.add(new ProvElementNode(c[i])); - } - } - return children.toArray(); - } - - /** - * Implementation based on id. - * @param other the object to compare this ProvElementNode against. - * @return true if the ProvElementNodesare equal; false otherwise. - */ - public boolean equals(Object other) { - if (other instanceof ProvElementNode) - return id.equals(((ProvElementNode) other).id); - return super.equals(other); - } - - /** - * Implementation based on id. - * @return a hash code for this object. - */ - public int hashCode() { - return id.hashCode(); - } - - public Image getImage() { - return pe.getImage(null); - } - - public String getName() { - if (iu != null) { - return IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_NAME); - } - return pe.getLabel(null); - } - - public String getType() { - return ITypedElement.UNKNOWN_TYPE; - } - - public InputStream getContents() { - String contents = BLANK; - if (iu != null) { - contents = iu.getVersion().toString(); - } - return new ByteArrayInputStream(contents.getBytes()); - } - } - - public void copyToClipboard(Control activeControl) { - String text = ""; //$NON-NLS-1$ - if (activeControl == configContentsViewer.getControl()) { - text = CopyUtils.getIndentedClipboardText(((IStructuredSelection) configContentsViewer.getSelection()).toArray(), labelProvider); - } else if (activeControl == configsViewer.getControl()) { - Object[] elements = ((IStructuredSelection) configsViewer.getSelection()).toArray(); - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < elements.length; i++) { - if (elements[i] instanceof RollbackProfileElement) { - if (i > 0) - buffer.append(CopyUtils.NEWLINE); - buffer.append(((RollbackProfileElement) elements[i]).getLabel(elements[i])); - } - } - text = buffer.toString(); - } else - return; - if (text.length() == 0) - return; - Clipboard clipboard = new Clipboard(PlatformUI.getWorkbench().getDisplay()); - clipboard.setContents(new Object[] {text}, new Transfer[] {TextTransfer.getInstance()}); - clipboard.dispose(); - } - - void deleteSelectedSnapshots() { - IStructuredSelection selection = (IStructuredSelection) configsViewer.getSelection(); - if (selection.isEmpty()) - return; - String title = selection.size() == 1 ? ProvUIMessages.RevertProfilePage_DeleteSingleConfigurationTitle : ProvUIMessages.RevertProfilePage_DeleteMultipleConfigurationsTitle; - String confirmMessage = selection.size() == 1 ? ProvUIMessages.RevertProfilePage_ConfirmDeleteSingleConfig : ProvUIMessages.RevertProfilePage_ConfirmDeleteMultipleConfigs; - if (MessageDialog.openConfirm(configsViewer.getControl().getShell(), title, confirmMessage)) { - Iterator iter = selection.iterator(); - while (iter.hasNext()) { - Object selected = iter.next(); - // If it is a recognized element and it is not the current profile, then it can be deleted. - if (selected instanceof RollbackProfileElement && !((RollbackProfileElement) selected).isCurrentProfile()) { - RollbackProfileElement snapshot = (RollbackProfileElement) selected; - IProfileRegistry registry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName()); - if (registry != null) { - try { - registry.removeProfile(profileId, snapshot.getTimestamp()); - configsViewer.refresh(); - } catch (ProvisionException e) { - ProvUI.handleException(e, null, StatusManager.SHOW | StatusManager.LOG); - } - } - } - } - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/UninstallWizard.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/UninstallWizard.java deleted file mode 100644 index 266293fc2..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/UninstallWizard.java +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import java.util.ArrayList; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.dialogs.*; -import org.eclipse.equinox.internal.p2.ui.model.ElementUtils; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.model.InstalledIUElement; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.wizard.IWizardPage; - -/** - * @since 3.4 - */ -public class UninstallWizard extends ProvisioningOperationWizard { - - SelectableIUsPage mainPage; - - static IUElementListRoot makeElementRoot(Object[] selectedElements, String profileId) { - IUElementListRoot elementRoot = new IUElementListRoot(); - ArrayList list = new ArrayList(selectedElements.length); - for (int i = 0; i < selectedElements.length; i++) { - IInstallableUnit iu = ElementUtils.getIU(selectedElements[i]); - if (iu != null) - list.add(new InstalledIUElement(elementRoot, profileId, iu)); - } - elementRoot.setChildren(list.toArray()); - return elementRoot; - } - - public UninstallWizard(Policy policy, String profileId, IInstallableUnit[] ius, PlannerResolutionOperation initialResolution) { - super(policy, profileId, makeElementRoot(ius, profileId), ius, initialResolution); - setWindowTitle(ProvUIMessages.UninstallIUOperationLabel); - setDefaultPageImageDescriptor(ProvUIImages.getImageDescriptor(ProvUIImages.WIZARD_BANNER_UNINSTALL)); - } - - protected ISelectableIUsPage createMainPage(IUElementListRoot input, Object[] selections) { - mainPage = new SelectableIUsPage(policy, input, selections, profileId); - mainPage.setTitle(ProvUIMessages.UninstallIUOperationLabel); - mainPage.setDescription(ProvUIMessages.UninstallDialog_UninstallMessage); - mainPage.updateStatus(input, resolutionOperation); - return mainPage; - } - - protected ResolutionResultsWizardPage createResolutionPage() { - return new UninstallWizardPage(policy, root, profileId, resolutionOperation); - } - - protected IUElementListRoot makeResolutionElementRoot(Object[] selectedElements) { - return makeElementRoot(selectedElements, profileId); - } - - protected ProfileChangeRequest computeProfileChangeRequest(Object[] selectedElements, MultiStatus additionalStatus, IProgressMonitor monitor) { - ProfileChangeRequest request = ProfileChangeRequest.createByProfileId(profileId); - request.removeInstallableUnits(ElementUtils.elementsToIUs(selectedElements)); - return request; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.ui.dialogs.ProvisioningOperationWizard#getErrorReportingPage() - */ - protected IResolutionErrorReportingPage getErrorReportingPage() { - return mainPage; - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.wizard.Wizard#getStartingPage() - */ - public IWizardPage getStartingPage() { - if (getCurrentStatus().isOK()) { - if (resolutionPage == null) { - resolutionPage = createResolutionPage(); - addPage(resolutionPage); - } - mainPage.setPageComplete(true); - return resolutionPage; - } - return super.getStartingPage(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/UpdateWizard.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/UpdateWizard.java deleted file mode 100644 index 9b0da565d..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/UpdateWizard.java +++ /dev/null @@ -1,265 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Genuitec, LLC - added license support - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; - -import java.util.*; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.dialogs.*; -import org.eclipse.equinox.internal.p2.ui.model.AvailableUpdateElement; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.PlannerHelper; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot; -import org.eclipse.equinox.internal.provisional.p2.ui.model.Updates; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.wizard.IWizardPage; -import org.eclipse.swt.widgets.Composite; - -/** - * @since 3.4 - */ -public class UpdateWizard extends WizardWithLicenses { - IInstallableUnit[] iusToReplace; - QueryableMetadataRepositoryManager manager; - SelectableIUsPage mainPage; - boolean skipSelectionsPage = false; - - public static IInstallableUnit[] getIUsToReplace(Object[] replacementElements) { - Set iusToReplace = new HashSet(); - for (int i = 0; i < replacementElements.length; i++) { - if (replacementElements[i] instanceof AvailableUpdateElement) { - iusToReplace.add(((AvailableUpdateElement) replacementElements[i]).getIUToBeUpdated()); - } - } - return (IInstallableUnit[]) iusToReplace.toArray(new IInstallableUnit[iusToReplace.size()]); - } - - public static IInstallableUnit[] getReplacementIUs(Object[] replacementElements) { - Set replacements = new HashSet(); - for (int i = 0; i < replacementElements.length; i++) { - if (replacementElements[i] instanceof AvailableUpdateElement) { - replacements.add(((AvailableUpdateElement) replacementElements[i]).getIU()); - } - } - return (IInstallableUnit[]) replacements.toArray(new IInstallableUnit[replacements.size()]); - } - - /** - * Create a profile change request that represents an update of the specified IUs to their latest versions, - * unless otherwise specified by the initial selections. If an element root and selection container are provided, - * update those elements so that a wizard could be opened on them to reflect the profile change request. - * - * @param iusToUpdate - * @param profileId - * @param root - * @param initialSelections - * @param monitor - * @return the profile change request describing an update, or null if there is nothing to update. - */ - public static ProfileChangeRequest createProfileChangeRequest(IInstallableUnit[] iusToUpdate, String profileId, IUElementListRoot root, Collection initialSelections, IProgressMonitor monitor) { - // Here we create a profile change request by finding the latest version available for any replacement, unless - // otherwise specified in the selections. - // We have to consider the scenario where the only updates available are patches, in which case the original - // IU should not be removed as part of the update. - Set toBeUpdated = new HashSet(); - HashSet elementsToPlan = new HashSet(); - ArrayList allReplacements = new ArrayList(); - IProfile profile; - try { - profile = ProvisioningUtil.getProfile(profileId); - if (profile == null) - return null; - } catch (ProvisionException e) { - return null; - } - SubMonitor sub = SubMonitor.convert(monitor, ProvUIMessages.ProfileChangeRequestBuildingRequest, 100 * iusToUpdate.length); - for (int i = 0; i < iusToUpdate.length; i++) { - boolean selectionSpecified = false; - ElementQueryDescriptor descriptor = Policy.getDefault().getQueryProvider().getQueryDescriptor(new Updates(profileId, new IInstallableUnit[] {iusToUpdate[i]})); - Iterator iter = descriptor.performQuery(sub).iterator(); - ArrayList currentReplacements = new ArrayList(); - while (iter.hasNext()) { - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(iter.next(), IInstallableUnit.class); - // If there is already a selected element representing an update for this iu, then we won't need - // to look for the latest. - if (iu != null) { - // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=273967 - // In the case of patches, it's possible that a patch is returned as an available update - // even though it is already installed, because we are querying each IU for updates individually. - // For now, we ignore any proposed update that is already installed. - Collector alreadyInstalled = profile.query(new InstallableUnitQuery(iu), new Collector(), null); - if (alreadyInstalled.isEmpty()) { - toBeUpdated.add(iusToUpdate[i]); - AvailableUpdateElement element = new AvailableUpdateElement(root, iu, iusToUpdate[i], profileId, true); - currentReplacements.add(element); - allReplacements.add(element); - if (initialSelections != null && initialSelections.contains(element)) { - elementsToPlan.add(element); - selectionSpecified = true; - } - } - } - } - if (!selectionSpecified) { - // If no selection was specified, we must figure out the latest version to apply. - // The rules are that a true update will always win over a patch, but if only - // patches are available, they should all be selected. - // We first gather the latest versions of everything proposed. - // Patches are keyed by their id because they are unique and should not be compared to - // each other. Updates are keyed by the IU they are updating so we can compare the - // versions and select the latest one - HashMap latestVersions = new HashMap(); - boolean foundUpdate = false; - boolean foundPatch = false; - for (int j = 0; j < currentReplacements.size(); j++) { - AvailableUpdateElement replacementElement = (AvailableUpdateElement) currentReplacements.get(j); - String key; - if (Boolean.toString(true).equals(replacementElement.getIU().getProperty(IInstallableUnit.PROP_TYPE_PATCH))) { - foundPatch = true; - key = replacementElement.getIU().getId(); - } else { - foundUpdate = true; - key = replacementElement.getIUToBeUpdated().getId(); - } - AvailableUpdateElement latestElement = (AvailableUpdateElement) latestVersions.get(key); - IInstallableUnit latestIU = latestElement == null ? null : latestElement.getIU(); - if (latestIU == null || replacementElement.getIU().getVersion().compareTo(latestIU.getVersion()) > 0) - latestVersions.put(key, replacementElement); - } - // If there is a true update available, ignore any patches found - // Patches are keyed by their own id - if (foundPatch && foundUpdate) { - Set keys = new HashSet(); - keys.addAll(latestVersions.keySet()); - Iterator keyIter = keys.iterator(); - while (keyIter.hasNext()) { - String id = (String) keyIter.next(); - // Get rid of things keyed by a different id. We've already made sure - // that updates with a different id are keyed under the original id - if (!id.equals(iusToUpdate[i].getId())) { - latestVersions.remove(id); - } - } - } - elementsToPlan.addAll(latestVersions.values()); - } - sub.worked(100); - } - if (root != null) - root.setChildren(allReplacements.toArray()); - - if (toBeUpdated.size() <= 0 || elementsToPlan.isEmpty()) { - sub.done(); - return null; - } - - ProfileChangeRequest request = ProfileChangeRequest.createByProfileId(profileId); - Iterator iter = elementsToPlan.iterator(); - while (iter.hasNext()) { - AvailableUpdateElement element = (AvailableUpdateElement) iter.next(); - IInstallableUnit theUpdate = element.getIU(); - if (initialSelections != null) { - if (!initialSelections.contains(element)) - initialSelections.add(element); - } - request.addInstallableUnits(new IInstallableUnit[] {theUpdate}); - request.setInstallableUnitProfileProperty(theUpdate, IInstallableUnit.PROP_PROFILE_ROOT_IU, Boolean.toString(true)); - if (Boolean.toString(true).equals(theUpdate.getProperty(IInstallableUnit.PROP_TYPE_PATCH))) { - request.setInstallableUnitInclusionRules(theUpdate, PlannerHelper.createOptionalInclusionRule(theUpdate)); - } else { - request.removeInstallableUnits(new IInstallableUnit[] {element.getIUToBeUpdated()}); - } - - } - sub.done(); - return request; - } - - public UpdateWizard(Policy policy, String profileId, IUElementListRoot root, Object[] initialSelections, PlannerResolutionOperation initialResolution, QueryableMetadataRepositoryManager manager) { - super(policy, profileId, root, initialSelections, initialResolution); - setWindowTitle(ProvUIMessages.UpdateAction_UpdatesAvailableTitle); - setDefaultPageImageDescriptor(ProvUIImages.getImageDescriptor(ProvUIImages.WIZARD_BANNER_UPDATE)); - this.manager = manager; - } - - protected ISelectableIUsPage createMainPage(IUElementListRoot input, Object[] selections) { - mainPage = new SelectableIUsPage(policy, input, selections, profileId); - mainPage.setTitle(ProvUIMessages.UpdateAction_UpdatesAvailableTitle); - mainPage.setDescription(ProvUIMessages.UpdateAction_UpdatesAvailableMessage); - mainPage.updateStatus(input, resolutionOperation); - return mainPage; - } - - protected ResolutionResultsWizardPage createResolutionPage() { - return new UpdateWizardPage(policy, root, profileId, resolutionOperation); - } - - protected IUElementListRoot makeResolutionElementRoot(Object[] selectedElements) { - IUElementListRoot elementRoot = new IUElementListRoot(); - ArrayList list = new ArrayList(selectedElements.length); - for (int i = 0; i < selectedElements.length; i++) { - if (selectedElements[i] instanceof AvailableUpdateElement) { - AvailableUpdateElement element = (AvailableUpdateElement) selectedElements[i]; - AvailableUpdateElement newElement = new AvailableUpdateElement(elementRoot, element.getIU(), element.getIUToBeUpdated(), profileId, policy.getQueryContext().getShowProvisioningPlanChildren()); - list.add(newElement); - } - } - elementRoot.setChildren(list.toArray()); - return elementRoot; - } - - public void createPageControls(Composite pageContainer) { - super.createPageControls(pageContainer); - if (manager != null) - // async exec since we are in the middle of opening - pageContainer.getDisplay().asyncExec(new Runnable() { - public void run() { - manager.reportAccumulatedStatus(); - } - }); - } - - protected ProfileChangeRequest computeProfileChangeRequest(Object[] selectedElements, MultiStatus additionalStatus, IProgressMonitor monitor) { - ArrayList initialSelections = new ArrayList(); - initialSelections.addAll(Arrays.asList(selectedElements)); - return createProfileChangeRequest(getIUsToReplace(selectedElements), profileId, null, initialSelections, monitor); - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.ui.dialogs.ProvisioningOperationWizard#getErrorReportingPage() - */ - protected IResolutionErrorReportingPage getErrorReportingPage() { - return mainPage; - } - - public void setSkipSelectionsPage(boolean skipSelectionsPage) { - this.skipSelectionsPage = skipSelectionsPage; - } - - public IWizardPage getStartingPage() { - if (skipSelectionsPage) { - // TODO see https://bugs.eclipse.org/bugs/show_bug.cgi?id=276963 - IWizardPage page = getNextPage(mainPage); - if (page != null) - return page; - } - return mainPage; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/ArtifactRepositories.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/ArtifactRepositories.java deleted file mode 100644 index be7ebe875..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/ArtifactRepositories.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.model; - -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.model.RootElement; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.QueryProvider; - -/** - * Element class that represents the root of an artifact - * repository viewer. Its children are the artifact repositories - * obtained using the query installed in the content provider. - * - * @since 3.4 - * - */ -public class ArtifactRepositories extends RootElement { - - public ArtifactRepositories(Policy policy) { - super(policy); - } - - protected int getDefaultQueryType() { - return QueryProvider.ARTIFACT_REPOS; - } - - /* - * (non-Javadoc) - * @see org.eclipse.ui.model.IWorkbenchAdapter#getLabel(java.lang.Object) - */ - public String getLabel(Object o) { - return ProvUIMessages.Label_Repositories; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/IRepositoryElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/IRepositoryElement.java deleted file mode 100644 index fa02492bd..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/IRepositoryElement.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.model; - -import java.net.URI; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; - -/** - * Interface for elements that represent repositories. - * - * @since 3.4 - */ -public interface IRepositoryElement { - - public URI getLocation(); - - public String getName(); - - public String getDescription(); - - public boolean isEnabled(); - - public void setEnabled(boolean enabled); - - public IRepository getRepository(IProgressMonitor monitor); -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/IUElementListRoot.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/IUElementListRoot.java deleted file mode 100644 index 0c43cf157..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/IUElementListRoot.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.model; - -import org.eclipse.equinox.internal.p2.ui.model.ProvElement; - - -/** - * Element class representing a fixed set of IU's. This element should - * never appear in a list, but can be used as a parent in a list. - * - * @since 3.5 - */ -public class IUElementListRoot extends ProvElement { - - Object[] children; - - public IUElementListRoot(Object[] children) { - super(null); - this.children = children; - } - - public IUElementListRoot() { - this(new Object[0]); - } - - public void setChildren(Object[] children) { - this.children = children; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.equinox.internal.provisional.p2.ui.model.ProvElement#getImageID(java.lang.Object) - */ - protected String getImageId(Object obj) { - return null; - } - - public String getLabel(Object o) { - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.ui.model.IWorkbenchAdapter#getChildren(java.lang.Object) - */ - public Object[] getChildren(Object o) { - return children; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/InstalledIUElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/InstalledIUElement.java deleted file mode 100644 index 107be0eae..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/InstalledIUElement.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.model; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.p2.ui.model.IIUElement; -import org.eclipse.equinox.internal.p2.ui.model.QueriedElement; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.IRequiredCapability; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.QueryProvider; - -/** - * Element wrapper class for installed IU's. Used instead of the plain IU when - * there should be a parent profile available for operations. - * - * @since 3.4 - */ -public class InstalledIUElement extends QueriedElement implements IIUElement { - - String profileId; - IInstallableUnit iu; - - public InstalledIUElement(Object parent, String profileId, IInstallableUnit iu) { - super(parent); - this.profileId = profileId; - this.iu = iu; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.equinox.internal.provisional.p2.ui.model.ProvElement#getImageID(java.lang.Object) - */ - protected String getImageId(Object obj) { - return ProvUIImages.IMG_IU; - } - - public String getLabel(Object o) { - return iu.getId(); - } - - public Object getAdapter(Class adapter) { - if (adapter == IInstallableUnit.class) - return iu; - return super.getAdapter(adapter); - } - - public String getProfileId() { - return profileId; - } - - public IInstallableUnit getIU() { - return iu; - } - - // TODO Later we might consider showing this in the installed views, - // but it is less important than before install. - public long getSize() { - return SIZE_UNKNOWN; - } - - public boolean shouldShowSize() { - return false; - } - - public void computeSize(IProgressMonitor monitor) { - // Should never be called, as long as shouldShowSize() returns false - } - - public boolean shouldShowVersion() { - return true; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.ui.model.IUElement#getRequirements() - */ - public IRequiredCapability[] getRequirements() { - return iu.getRequiredCapabilities(); - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.ui.model.QueriedElement#getDefaultQueryType() - */ - protected int getDefaultQueryType() { - return QueryProvider.INSTALLED_IUS; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.ui.model.IIUElement#shouldShowChildren() - */ - public boolean shouldShowChildren() { - return true; - } - - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof InstalledIUElement)) - return false; - if (iu == null) - return false; - return iu.equals(((InstalledIUElement) obj).getIU()); - } - - public int hashCode() { - if (iu == null) - return 0; - return iu.hashCode(); - } - - public String toString() { - if (iu == null) - return "NULL"; //$NON-NLS-1$ - return iu.toString(); - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/MetadataRepositories.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/MetadataRepositories.java deleted file mode 100644 index 93441aa51..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/MetadataRepositories.java +++ /dev/null @@ -1,102 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.model; - -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.model.RootElement; -import org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; - -/** - * Element class that represents some collection of metadata repositories. - * It can be configured so that it retrieves its children in different ways. - * The default query type will return the metadata repositories specified in - * this element. Other query types can be used to query each repository and - * aggregate the children. - * - * @since 3.4 - * - */ -public class MetadataRepositories extends RootElement { - - private boolean includeDisabled = false; - - public MetadataRepositories(Policy policy) { - this(policy.getQueryContext(), policy, null); - } - - public MetadataRepositories(IUViewQueryContext queryContext, Policy policy, QueryableMetadataRepositoryManager queryable) { - super(queryContext, policy); - this.queryable = queryable; - } - - /** - * Get whether disabled repositories should be included in queries when no repositories - * have been specified. This boolean is used because the flags specified when getting - * repositories from a repository manager are treated as an AND, and we want to permit - * aggregating disabled repositories along with other flags. - * - * @return includeDisabled true if disabled repositories should be included and - * false if they should not be included. - */ - public boolean getIncludeDisabledRepositories() { - return includeDisabled; - } - - /** - * Set whether disabled repositories should be included in queries when no repositories - * have been specified. This boolean is used because the flags specified when getting - * repositories from a repository manager are treated as an AND, and we want to permit - * aggregating disabled repositories along with other flags. - * - * @param includeDisabled true if disabled repositories should be included and - * false if they should not be included. - */ - public void setIncludeDisabledRepositories(boolean includeDisabled) { - this.includeDisabled = includeDisabled; - } - - /* - * Overridden to check the query context. We might - * be showing repositories, or we might be flattening the - * view to some other element - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueriedElement#getQueryType() - */ - public int getQueryType() { - if (getQueryContext() == null) - return getDefaultQueryType(); - return getQueryContext().getQueryType(); - } - - protected int getDefaultQueryType() { - return QueryProvider.METADATA_REPOS; - } - - /* - * (non-Javadoc) - * @see org.eclipse.ui.model.IWorkbenchAdapter#getLabel(java.lang.Object) - */ - public String getLabel(Object o) { - return ProvUIMessages.Label_Repositories; - } - - /* - * Overridden because we might be iterating sites - * (type = METADATA_REPOSITORIES) rather than loading repos. If this - * is the case, we only care whether we have a queryable or not. - */ - public boolean hasQueryable() { - if (getQueryType() == QueryProvider.METADATA_REPOS) - return queryable != null; - return super.hasQueryable(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/ProfileElement.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/ProfileElement.java deleted file mode 100644 index 584697307..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/ProfileElement.java +++ /dev/null @@ -1,91 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.model; - -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.model.RemoteQueriedElement; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.IQueryable; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.QueryProvider; -import org.eclipse.osgi.util.NLS; - -/** - * Element wrapper class for a profile that uses the query - * mechanism to obtain its contents. - * - * @since 3.4 - */ -public class ProfileElement extends RemoteQueriedElement { - String profileId; - - public ProfileElement(Object parent, String profileId) { - super(parent); - this.profileId = profileId; - } - - public Object getAdapter(Class adapter) { - if (adapter == IProfile.class) - return getQueryable(); - return super.getAdapter(adapter); - } - - protected String getImageId(Object obj) { - return ProvUIImages.IMG_PROFILE; - } - - public String getLabel(Object o) { - return profileId; - } - - public String getProfileId() { - return profileId; - } - - protected int getDefaultQueryType() { - return QueryProvider.INSTALLED_IUS; - } - - public IQueryable getQueryable() { - try { - return ProvisioningUtil.getProfile(profileId); - } catch (ProvisionException e) { - handleException(e, NLS.bind(ProvUIMessages.ProfileElement_InvalidProfile, profileId)); - return null; - } - } - - /* - * Overridden to check whether we know the profile id rather - * than fetch the profile from the registry using getQueryable() - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueriedElement#knowsQueryable() - */ - public boolean knowsQueryable() { - return profileId != null; - } - - /* - * Overridden to check the children so that profiles - * showing in profile views accurately reflect if they - * are empty. We do not cache the children because often - * this element is the input of a view and when the view - * is refreshed we want to refetch the children. - * - * (non-Javadoc) - * @see org.eclipse.equinox.internal.p2.ui.model.RemoteQueriedElement#isContainer() - */ - public boolean isContainer() { - return super.getChildren(this).length > 0; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/Profiles.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/Profiles.java deleted file mode 100644 index dc93702e1..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/Profiles.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.model; - -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.model.RootElement; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.QueryProvider; - -/** - * Element class that represents the root of a profile - * viewer. Its children are the profiles that match the - * specified query for profiles. - * - * @since 3.4 - * - */ -public class Profiles extends RootElement { - - public Profiles(Policy policy) { - super(policy); - } - - /* - * (non-Javadoc) - * @see org.eclipse.ui.model.IWorkbenchAdapter#getLabel(java.lang.Object) - */ - public String getLabel(Object o) { - return ProvUIMessages.Label_Profiles; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueriedElement#getDefaultQueryType() - */ - protected int getDefaultQueryType() { - return QueryProvider.PROFILES; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/Updates.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/Updates.java deleted file mode 100644 index cbb93eb3c..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/model/Updates.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.model; - -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.model.QueriedElement; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.QueryProvider; - -/** - * Element class that represents available updates. - * - * @since 3.4 - * - */ -public class Updates extends QueriedElement { - - private String profileId; - private IInstallableUnit[] iusToBeUpdated; - - public Updates(String profileId) { - this(profileId, null); - } - - public Updates(String profileId, IInstallableUnit[] iusToBeUpdated) { - super(null); - this.profileId = profileId; - this.iusToBeUpdated = iusToBeUpdated; - } - - /* - * (non-Javadoc) - * @see org.eclipse.ui.model.IWorkbenchAdapter#getLabel(java.lang.Object) - */ - public String getLabel(Object o) { - return ProvUIMessages.Updates_Label; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueriedElement#getDefaultQueryType() - */ - protected int getDefaultQueryType() { - return QueryProvider.AVAILABLE_UPDATES; - } - - public String getProfileId() { - return profileId; - } - - public IInstallableUnit[] getIUs() { - return iusToBeUpdated; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/AddColocatedRepositoryOperation.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/AddColocatedRepositoryOperation.java deleted file mode 100644 index 1d8cadda7..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/AddColocatedRepositoryOperation.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.operations; - -import java.net.URI; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; - -/** - * Operation that adds colocated artifact and metadata repositories - * given a URL. - * - * @since 3.4 - */ -public class AddColocatedRepositoryOperation extends AddRepositoryOperation { - public AddColocatedRepositoryOperation(String label, URI url) { - super(label, new URI[] {url}); - } - - public AddColocatedRepositoryOperation(String label, URI[] urls) { - super(label, urls); - } - - protected IStatus doBatchedExecute(IProgressMonitor monitor) throws ProvisionException { - SubMonitor mon = SubMonitor.convert(monitor, locations.length * 2); - - for (int i = 0; i < locations.length; i++) { - ProvisioningUtil.addMetadataRepository(locations[i], notify); - mon.worked(1); - ProvisioningUtil.addArtifactRepository(locations[i], notify); - mon.worked(1); - } - return okStatus(); - } - - protected void setNickname(URI location, String nickname) throws ProvisionException { - for (int i = 0; i < locations.length; i++) { - ProvisioningUtil.setMetadataRepositoryProperty(location, IRepository.PROP_NICKNAME, nickname); - ProvisioningUtil.setArtifactRepositoryProperty(location, IRepository.PROP_NICKNAME, nickname); - } - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/AddProfileOperation.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/AddProfileOperation.java deleted file mode 100644 index f2bf7195b..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/AddProfileOperation.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.operations; - -import java.util.Map; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; - -/** - * Operation that adds the given profile to the profile registry. - * - * @since 3.4 - */ -public class AddProfileOperation extends ProvisioningOperation { - private String profileId; - private Map profileProperties; - - public AddProfileOperation(String label, String profileId, Map profileProperties) { - super(label); - this.profileId = profileId; - this.profileProperties = profileProperties; - } - - protected IStatus doExecute(IProgressMonitor monitor) throws ProvisionException { - ProvisioningUtil.addProfile(profileId, profileProperties, monitor); - return okStatus(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/AddRepositoryOperation.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/AddRepositoryOperation.java deleted file mode 100644 index ebcd683cc..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/AddRepositoryOperation.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.operations; - -import java.net.URI; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; - -/** - * Abstract class representing an operation that adds repositories, - * using an optional nickname. - * - * @since 3.5 - */ -public abstract class AddRepositoryOperation extends RepositoryOperation { - - protected String[] nicknames; - - public AddRepositoryOperation(String label, URI[] locations) { - super(label, locations); - } - - public void setNicknames(String[] nicknames) { - Assert.isLegal(nicknames != null && nicknames.length == locations.length); - this.nicknames = nicknames; - } - - public boolean runInBackground() { - return true; - } - - protected IStatus doExecute(IProgressMonitor monitor) throws ProvisionException { - boolean batched = false; - if (locations != null && locations.length > 1) { - ProvUI.startBatchOperation(); - batched = true; - } - IStatus status = doBatchedExecute(monitor); - if (nicknames != null) { - for (int i = 0; i < nicknames.length; i++) { - setNickname(locations[i], nicknames[i]); - } - } - if (batched) - ProvUI.endBatchOperation(notify); - return status; - } - - protected abstract void setNickname(URI location, String nickname) throws ProvisionException; - - protected abstract IStatus doBatchedExecute(IProgressMonitor monitor) throws ProvisionException; - - public void setNotify(boolean notify) { - this.notify = notify; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/DownloadPhaseSet.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/DownloadPhaseSet.java deleted file mode 100644 index 2132765eb..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/DownloadPhaseSet.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/** - * - */ -package org.eclipse.equinox.internal.provisional.p2.ui.operations; - -import org.eclipse.equinox.internal.provisional.p2.engine.Phase; -import org.eclipse.equinox.internal.provisional.p2.engine.PhaseSet; -import org.eclipse.equinox.internal.provisional.p2.engine.phases.Collect; - -public class DownloadPhaseSet extends PhaseSet { - public DownloadPhaseSet() { - super(new Phase[] {new Collect(10)}); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/PlannerResolutionOperation.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/PlannerResolutionOperation.java deleted file mode 100644 index 8674fa6c7..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/PlannerResolutionOperation.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.operations; - -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.ui.IStatusCodes; -import org.eclipse.equinox.internal.provisional.p2.ui.ResolutionResult; - -/** - * Class representing a provisioning profile plan - * - * @since 3.4 - */ -public class PlannerResolutionOperation extends ProvisioningOperation { - - ProfileChangeRequest request; - String profileId; - boolean isUser = true; - ProvisioningPlan plan; - MultiStatus additionalStatus; - ResolutionResult report; - ProvisioningContext provisioningContext; - - public PlannerResolutionOperation(String label, String profileId, ProfileChangeRequest request, ProvisioningContext provisioningContext, MultiStatus additionalStatus, boolean isUser) { - super(label); - this.request = request; - this.profileId = profileId; - this.isUser = isUser; - if (provisioningContext == null) - this.provisioningContext = new ProvisioningContext(); - else - this.provisioningContext = provisioningContext; - Assert.isNotNull(additionalStatus); - this.additionalStatus = additionalStatus; - } - - public ProvisioningPlan getProvisioningPlan() { - return plan; - } - - public ProfileChangeRequest getProfileChangeRequest() { - return request; - } - - public ProvisioningContext getProvisioningContext() { - return provisioningContext; - } - - protected IStatus doExecute(IProgressMonitor monitor) throws ProvisionException { - plan = ProvisioningUtil.getProvisioningPlan(request, provisioningContext, monitor); - if (plan == null) - return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, IStatusCodes.UNEXPECTED_NOTHING_TO_DO, ProvUIMessages.PlannerResolutionOperation_UnexpectedError, null); - // We are reporting on our ability to get a plan, not on the status of the plan itself. - // Callers will interpret and report the status as needed. - return Status.OK_STATUS; - } - - public ResolutionResult getResolutionResult() { - if (report == null) { - report = PlanAnalyzer.computeResolutionResult(request, plan, additionalStatus); - } - return report; - } - - public boolean runInBackground() { - return true; - } - - public boolean isUser() { - return isUser; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProfileModificationOperation.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProfileModificationOperation.java deleted file mode 100644 index 2b8afb291..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProfileModificationOperation.java +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.operations; - -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.*; - -/** - * Class representing a provisioning profile plan - * - * @since 3.4 - */ -public class ProfileModificationOperation extends ProvisioningOperation { - - ProvisioningPlan plan; - String profileId; - PhaseSet phaseSet; - boolean isUser = true; - ProvisioningContext provisioningContext; - private String taskName; - - public ProfileModificationOperation(String label, String profileId, ProvisioningPlan plan, ProvisioningContext context) { - this(label, profileId, plan, context, null, true); - } - - public ProfileModificationOperation(String label, String profileId, ProvisioningPlan plan, ProvisioningContext context, PhaseSet set, boolean isUser) { - super(label); - this.plan = plan; - this.profileId = profileId; - this.provisioningContext = context; - this.isUser = isUser; - if (set == null) - phaseSet = new DefaultPhaseSet(); - else - phaseSet = set; - } - - public String getProfileId() { - return profileId; - } - - protected IProfile getProfile() { - try { - return ProvisioningUtil.getProfile(profileId); - } catch (ProvisionException e) { - return null; - } - } - - protected IStatus doExecute(IProgressMonitor monitor) throws ProvisionException { - String task = taskName; - if (task == null) - task = ""; //$NON-NLS-1$ - monitor.beginTask(task, 1000); - try { - return ProvisioningUtil.performProvisioningPlan(plan, phaseSet, provisioningContext, new SubProgressMonitor(monitor, 1000)); - } finally { - monitor.done(); - } - } - - public boolean runInBackground() { - return true; - } - - /** - * Sets the top level task name for progress when running this operation. - * @param label - */ - public void setTaskName(String label) { - this.taskName = label; - } - - public boolean isUser() { - return isUser; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningOperation.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningOperation.java deleted file mode 100644 index c523df40d..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningOperation.java +++ /dev/null @@ -1,86 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.operations; - -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; - -/** - * Abstract class representing provisioning operations. ProvisioningOperations - * can be run in the foreground or in the background as a job. - * - * @since 3.4 - */ - -public abstract class ProvisioningOperation { - - private String label; - - public ProvisioningOperation(String label) { - this.label = label; - } - - /** - * - */ - public IStatus execute(IProgressMonitor monitor) throws ProvisionException { - IStatus status; - try { - status = doExecute(monitor); - } catch (OperationCanceledException e) { - return Status.CANCEL_STATUS; - } - return status; - } - - /** - * Perform the specific work involved in executing this operation. - * - * @param monitor - * the progress monitor to use for the operation - * @throws ProvisionException - * propagates any ProvisionException thrown - * - */ - protected abstract IStatus doExecute(IProgressMonitor monitor) throws ProvisionException; - - protected IStatus okStatus() { - return Status.OK_STATUS; - } - - public String getLabel() { - return label; - } - - /** - * Return a boolean indicating whether the operation can be run in the - * background. - * - * @return true if the operation can be run in the background, and - * false if it should be run in the UI. - */ - public boolean runInBackground() { - return false; - } - - /** - * Return a boolean indicating whether this operation was triggered by the - * user. This value is used to determine whether any job running this operation - * should be considered a user job. This can affect the way progress is shown to the user. - * - * @return true if the operation was initiated by the user, - * false if it was not. - */ - public boolean isUser() { - return true; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningUtil.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningUtil.java deleted file mode 100644 index a0f2a92e5..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningUtil.java +++ /dev/null @@ -1,450 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.operations; - -import java.io.IOException; -import java.net.URI; -import java.util.*; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.ui.*; -import org.eclipse.equinox.internal.p2.ui.model.IIUElement; -import org.eclipse.equinox.internal.provisional.configurator.Configurator; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.director.*; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner; -import org.eclipse.osgi.util.NLS; - -/** - * Utility methods for clients using the provisioning UI - * - * @since 3.4 - */ -public class ProvisioningUtil { - - public static void addMetadataRepository(URI location, boolean notify) throws ProvisionException { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName()); - if (manager == null) - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - manager.addRepository(location); - if (notify) { - IProvisioningEventBus bus = ProvUIActivator.getDefault().getProvisioningEventBus(); - if (bus != null) { - bus.publishEvent(new UIRepositoryEvent(location, IRepository.TYPE_METADATA, RepositoryEvent.ADDED)); - } - } - } - - public static String getMetadataRepositoryProperty(URI location, String key) throws ProvisionException { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName()); - if (manager == null) - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - return manager.getRepositoryProperty(location, key); - } - - public static void setMetadataRepositoryProperty(URI location, String key, String value) throws ProvisionException { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName()); - if (manager == null) - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - manager.setRepositoryProperty(location, key, value); - } - - public static boolean getMetadataRepositoryEnablement(URI location) { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName()); - if (manager == null) - return false; - return manager.isEnabled(location); - } - - public static boolean getArtifactRepositoryEnablement(URI location) { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName()); - if (manager == null) - return false; - return manager.isEnabled(location); - } - - public static IMetadataRepository loadMetadataRepository(URI location, IProgressMonitor monitor) throws ProvisionException { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName()); - if (manager == null) - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - IMetadataRepository repo = manager.loadRepository(location, monitor); - // If there is no user nickname assigned to this repo but there is a provider name, then set the nickname. - // This will keep the name in the manager even when the repo is not loaded - String name = getMetadataRepositoryProperty(location, IRepository.PROP_NICKNAME); - if (name == null || name.length() == 0) { - name = repo.getName(); - if (name != null && name.length() > 0) - setMetadataRepositoryProperty(location, IRepository.PROP_NICKNAME, name); - } - return repo; - } - - public static IStatus validateMetadataRepositoryLocation(URI location, IProgressMonitor monitor) { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName()); - if (manager == null) - return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - return manager.validateRepositoryLocation(location, monitor); - } - - public static void removeMetadataRepository(URI location) throws ProvisionException { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName()); - if (manager == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - } - manager.removeRepository(location); - IProvisioningEventBus bus = ProvUIActivator.getDefault().getProvisioningEventBus(); - if (bus != null) { - bus.publishEvent(new UIRepositoryEvent(location, IRepository.TYPE_METADATA, RepositoryEvent.REMOVED)); - } - } - - public static void addArtifactRepository(URI location, boolean notify) throws ProvisionException { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName()); - if (manager == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - } - manager.addRepository(location); - if (notify) { - IProvisioningEventBus bus = ProvUIActivator.getDefault().getProvisioningEventBus(); - if (bus != null) { - bus.publishEvent(new UIRepositoryEvent(location, IRepository.TYPE_ARTIFACT, RepositoryEvent.ADDED)); - } - } - } - - public static String getArtifactRepositoryProperty(URI location, String key) throws ProvisionException { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName()); - if (manager == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - } - return manager.getRepositoryProperty(location, key); - } - - public static void setArtifactRepositoryProperty(URI location, String key, String value) throws ProvisionException { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName()); - if (manager == null) - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - manager.setRepositoryProperty(location, key, value); - } - - public static IArtifactRepository loadArtifactRepository(URI location, IProgressMonitor monitor) throws ProvisionException { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName()); - if (manager == null) - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - IArtifactRepository repo = manager.loadRepository(location, monitor); - if (repo == null) { - throw new ProvisionException(NLS.bind(ProvUIMessages.ProvisioningUtil_LoadRepositoryFailure, location)); - } - // If there is no user nickname assigned to this repo but there is a provider name, then set the nickname. - // This will keep the name in the manager even when the repo is not loaded - String name = getArtifactRepositoryProperty(location, IRepository.PROP_NICKNAME); - if (name == null) { - name = getArtifactRepositoryProperty(location, IRepository.PROP_NAME); - if (name != null) - setArtifactRepositoryProperty(location, IRepository.PROP_NICKNAME, name); - } - return repo; - } - - public static void removeArtifactRepository(URI location) throws ProvisionException { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName()); - if (manager == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - } - manager.removeRepository(location); - IProvisioningEventBus bus = ProvUIActivator.getDefault().getProvisioningEventBus(); - if (bus != null) { - bus.publishEvent(new UIRepositoryEvent(location, IRepository.TYPE_ARTIFACT, RepositoryEvent.REMOVED)); - } - } - - public static IProfile addProfile(String profileId, Map properties, IProgressMonitor monitor) throws ProvisionException { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName()); - if (profileRegistry == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound); - } - return profileRegistry.addProfile(profileId, properties); - } - - public static void removeProfile(String profileId, IProgressMonitor monitor) throws ProvisionException { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName()); - if (profileRegistry == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound); - } - profileRegistry.removeProfile(profileId); - } - - public static IProfile[] getProfiles() throws ProvisionException { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName()); - if (profileRegistry == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound); - } - return profileRegistry.getProfiles(); - } - - public static long[] getProfileTimestamps(String id) throws ProvisionException { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName()); - if (profileRegistry == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound); - } - return profileRegistry.listProfileTimestamps(id); - - } - - public static IProfile getProfile(String id) throws ProvisionException { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName()); - if (profileRegistry == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound); - } - return profileRegistry.getProfile(id); - } - - public static IProfile getProfile(String id, long timestamp) throws ProvisionException { - IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName()); - if (profileRegistry == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound); - } - return profileRegistry.getProfile(id, timestamp); - } - - public static URI[] getMetadataRepositories(int flags) throws ProvisionException { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName()); - if (manager == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - } - return manager.getKnownRepositories(flags); - } - - public static void refreshMetadataRepositories(URI[] urls, IProgressMonitor monitor) throws ProvisionException { - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName()); - if (manager == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - } - SubMonitor mon = SubMonitor.convert(monitor, urls.length * 100); - for (int i = 0; i < urls.length; i++) { - try { - manager.refreshRepository(urls[i], mon.newChild(100)); - } catch (ProvisionException e) { - //ignore problematic repositories when refreshing - } - } - } - - public static URI[] getArtifactRepositories(int flags) throws ProvisionException { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName()); - if (manager == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - } - return manager.getKnownRepositories(flags); - } - - public static void refreshArtifactRepositories(URI[] urls, IProgressMonitor monitor) throws ProvisionException { - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName()); - if (manager == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager); - } - SubMonitor mon = SubMonitor.convert(monitor, urls.length * 100); - for (int i = 0; i < urls.length; i++) { - manager.refreshRepository(urls[i], mon.newChild(100)); - } - } - - /* - * Get the plan for the specified install operation - */ - public static ProvisioningPlan getProvisioningPlan(ProfileChangeRequest request, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException { - try { - return getPlanner().getProvisioningPlan(request, context, monitor); - } catch (OperationCanceledException e) { - return null; - } - } - - /* - * Get a plan for reverting to a specified profile snapshot - */ - public static ProvisioningPlan getRevertPlan(IProfile currentProfile, IProfile snapshot, IProgressMonitor monitor) throws ProvisionException { - Assert.isNotNull(currentProfile); - Assert.isNotNull(snapshot); - return getPlanner().getDiffPlan(currentProfile, snapshot, monitor); - } - - /* - * Get sizing info for the specified plan - */ - public static long getSize(ProvisioningPlan plan, String profileId, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException { - // If there is nothing to size, return 0 - if (plan == null) - return IIUElement.SIZE_NOTAPPLICABLE; - if (plan.getOperands().length == 0) - return 0; - long installPlanSize = 0; - SubMonitor mon = SubMonitor.convert(monitor, 300); - if (plan.getInstallerPlan() != null) { - SizingPhaseSet set = new SizingPhaseSet(); - IStatus status = getEngine().perform(getProfile(profileId), set, plan.getInstallerPlan().getOperands(), context, mon.newChild(100)); - if (status.isOK()) - installPlanSize = set.getSizing().getDiskSize(); - } else { - mon.worked(100); - } - SizingPhaseSet set = new SizingPhaseSet(); - IStatus status = getEngine().perform(getProfile(profileId), set, plan.getOperands(), context, mon.newChild(200)); - if (status.isOK()) - return installPlanSize + set.getSizing().getDiskSize(); - return IIUElement.SIZE_UNAVAILABLE; - } - - /** - * Perform the specified provisioning plan. - * - * @param plan the plan to perform - * @param phaseSet the phase set to use - * @param profile the profile to be changed. This parameter is now ignored. - * @param context the provisioning context to be used - * @param monitor the progress monitor - * @return a status indicating the success of the plan - * @throws ProvisionException - * - * @deprecated clients should use {@linkplain #performProvisioningPlan(ProvisioningPlan, PhaseSet, ProvisioningContext, IProgressMonitor)} - * because the profile argument is now ignored. - */ - public static IStatus performProvisioningPlan(ProvisioningPlan plan, PhaseSet phaseSet, IProfile profile, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException { - // ignore the profile, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=272355 - return performProvisioningPlan(plan, phaseSet, context, monitor); - } - - public static IStatus performProvisioningPlan(ProvisioningPlan plan, PhaseSet phaseSet, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException { - PhaseSet set; - if (phaseSet == null) - set = new DefaultPhaseSet(); - else - set = phaseSet; - - // 300 ticks for download, 100 to install handlers, 100 to install the rest - SubMonitor mon = SubMonitor.convert(monitor, 500); - int ticksUsed = 0; - - // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=272355 - // The exact profile instance used in the profile change request and passed to the engine must be used for all - // of these operations, otherwise we can get profile out of synch errors. - IProfile profile = plan.getProfileChangeRequest().getProfile(); - - if (plan.getInstallerPlan() != null) { - if (set instanceof DefaultPhaseSet) { - // If the phase set calls for download and install, then we want to download everything atomically before - // applying the install plan. This way, we can be sure to install the install handler only if we know - // we will be able to get everything else. - List allOperands = new ArrayList(); - allOperands.addAll(Arrays.asList(plan.getOperands())); - allOperands.addAll(Arrays.asList(plan.getInstallerPlan().getOperands())); - PhaseSet download = new DownloadPhaseSet(); - IStatus downloadStatus = getEngine().perform(profile, download, (Operand[]) allOperands.toArray(new Operand[allOperands.size()]), context, mon.newChild(300)); - if (!downloadStatus.isOK()) { - mon.done(); - return downloadStatus; - } - ticksUsed = 300; - } - // we pre-downloaded if necessary. Now perform the plan against the original phase set. - IStatus installerPlanStatus = getEngine().perform(profile, set, plan.getInstallerPlan().getOperands(), context, mon.newChild(100)); - if (!installerPlanStatus.isOK()) { - mon.done(); - return installerPlanStatus; - } - ticksUsed += 100; - // Apply the configuration - Configurator configChanger = (Configurator) ServiceHelper.getService(ProvUIActivator.getContext(), Configurator.class.getName()); - try { - // TODO see https://bugs.eclipse.org/bugs/show_bug.cgi?id=274876 - ProvisioningOperationRunner.suppressRestart(true); - configChanger.applyConfiguration(); - // We just applied the configuration so restart is no longer required. - ProvisioningOperationRunner.clearRestartRequests(); - } catch (IOException e) { - mon.done(); - return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningUtil_InstallPlanConfigurationError, e); - } finally { - ProvisioningOperationRunner.suppressRestart(false); - } - } - return getEngine().perform(profile, set, plan.getOperands(), context, mon.newChild(500 - ticksUsed)); - } - - private static IEngine getEngine() throws ProvisionException { - IEngine engine = (IEngine) ServiceHelper.getService(ProvUIActivator.getContext(), IEngine.SERVICE_NAME); - if (engine == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoEngineFound); - } - return engine; - } - - public static IPlanner getPlanner() throws ProvisionException { - IPlanner planner = (IPlanner) ServiceHelper.getService(ProvUIActivator.getContext(), IPlanner.class.getName()); - if (planner == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoPlannerFound); - } - return planner; - } - - public static IDirector getDirector() throws ProvisionException { - IDirector director = (IDirector) ServiceHelper.getService(ProvUIActivator.getContext(), IDirector.class.getName()); - if (director == null) { - throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoDirectorFound); - } - return director; - } - - public static void setColocatedRepositoryEnablement(URI location, boolean enabled) { - IMetadataRepositoryManager metaManager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName()); - if (metaManager != null) - metaManager.setEnabled(location, enabled); - IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName()); - if (artifactManager != null) - artifactManager.setEnabled(location, enabled); - } - - public static boolean isCategory(IInstallableUnit iu) { - String isCategory = iu.getProperty(IInstallableUnit.PROP_TYPE_CATEGORY); - return isCategory != null && Boolean.valueOf(isCategory).booleanValue(); - } - - /** - * Perform the provisioning plan using a default context that contacts all repositories. - * @param plan the plan to perform - * @param phaseSet the phase set to use - * @param profile the profile to be changed - * @param monitor the progress monitor - * @return a status indicating the success of the plan - * @throws ProvisionException - * - * @deprecated clients should use {@linkplain #performProvisioningPlan(ProvisioningPlan, PhaseSet, IProfile, ProvisioningContext, IProgressMonitor)} - * to explicitly establish a provisioning context. Otherwise all repositories will be contacted - */ - public static IStatus performProvisioningPlan(ProvisioningPlan plan, PhaseSet phaseSet, IProfile profile, IProgressMonitor monitor) throws ProvisionException { - PhaseSet set; - if (phaseSet == null) - set = new DefaultPhaseSet(); - else - set = phaseSet; - return getEngine().perform(profile, set, plan.getOperands(), new ProvisioningContext(), monitor); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RemoveColocatedRepositoryOperation.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RemoveColocatedRepositoryOperation.java deleted file mode 100644 index 6faf3b0db..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RemoveColocatedRepositoryOperation.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.operations; - -import java.net.URI; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; - -/** - * Operation that removes the colocated repositories with the given locations. * - * - * @since 3.4 - */ -public class RemoveColocatedRepositoryOperation extends RemoveRepositoryOperation { - - public RemoveColocatedRepositoryOperation(String label, URI[] repoLocations) { - super(label, repoLocations); - } - - protected IStatus doBatchedExecute(IProgressMonitor monitor) throws ProvisionException { - SubMonitor mon = SubMonitor.convert(monitor, locations.length * 2); - - for (int i = 0; i < locations.length; i++) { - ProvisioningUtil.removeMetadataRepository(locations[i]); - mon.worked(1); - ProvisioningUtil.removeArtifactRepository(locations[i]); - mon.worked(1); - } - return okStatus(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RemoveProfilesOperation.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RemoveProfilesOperation.java deleted file mode 100644 index db1fa29e7..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RemoveProfilesOperation.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.operations; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; - -/** - * Operation that removes a profile - * - * @since 3.4 - */ -public class RemoveProfilesOperation extends ProvisioningOperation { - String[] profileIds; - - public RemoveProfilesOperation(String label, String[] profileIds) { - super(label); - this.profileIds = profileIds; - } - - protected IStatus doExecute(IProgressMonitor monitor) throws ProvisionException { - for (int i = 0; i < profileIds.length; i++) { - ProvisioningUtil.removeProfile(profileIds[i], monitor); - } - // assume the best if no exception - return okStatus(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RemoveRepositoryOperation.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RemoveRepositoryOperation.java deleted file mode 100644 index b50015eab..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RemoveRepositoryOperation.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.operations; - -import java.net.URI; - -/** - * Abstract class representing an operation that removes repositories. - * - * @since 3.5 - */ -public abstract class RemoveRepositoryOperation extends RepositoryOperation { - - public RemoveRepositoryOperation(String label, URI[] locations) { - super(label, locations); - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RepositoryOperation.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RepositoryOperation.java deleted file mode 100644 index 8fa9cb003..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/RepositoryOperation.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.operations; - -import java.net.URI; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; - -/** - * Abstract class representing provisioning repository operations - * - * @since 3.4 - */ -public abstract class RepositoryOperation extends ProvisioningOperation { - - protected URI[] locations; - protected boolean notify = true; - - public RepositoryOperation(String label, URI[] urls) { - super(label); - this.locations = urls; - } - - public boolean runInBackground() { - return true; - } - - protected IStatus doExecute(IProgressMonitor monitor) throws ProvisionException { - boolean batched = false; - if (locations != null && locations.length > 1) { - ProvUI.startBatchOperation(); - batched = true; - } - IStatus status = doBatchedExecute(monitor); - if (batched && notify) - ProvUI.endBatchOperation(notify); - return status; - } - - protected abstract IStatus doBatchedExecute(IProgressMonitor monitor) throws ProvisionException; - - public void setNotify(boolean notify) { - this.notify = notify; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/SizingPhaseSet.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/SizingPhaseSet.java deleted file mode 100644 index be655bd61..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/SizingPhaseSet.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/** - * - */ -package org.eclipse.equinox.internal.provisional.p2.ui.operations; - -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.engine.Phase; -import org.eclipse.equinox.internal.provisional.p2.engine.PhaseSet; -import org.eclipse.equinox.internal.provisional.p2.engine.phases.Sizing; - -public class SizingPhaseSet extends PhaseSet { - private static Sizing sizing; - - SizingPhaseSet() { - super(new Phase[] {sizing = new Sizing(100, ProvUIMessages.SizingPhaseSet_PhaseSetName)}); - } - - Sizing getSizing() { - return sizing; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/ColocatedRepositoryManipulator.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/ColocatedRepositoryManipulator.java deleted file mode 100644 index b8d4d3eb3..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/ColocatedRepositoryManipulator.java +++ /dev/null @@ -1,166 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.policy; - -import java.net.URI; -import org.eclipse.equinox.internal.p2.ui.DefaultMetadataURLValidator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.RepositoryManipulationPage; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.*; -import org.eclipse.jface.dialogs.TitleAreaDialog; -import org.eclipse.jface.preference.PreferenceDialog; -import org.eclipse.swt.widgets.*; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.dialogs.PreferencesUtil; - -/** - * Provides a repository manipulator that interprets URLs as colocated - * artifact and metadata repositories. If a preference id has been - * set, the manipulator will open a pref page to manipulate sites. If it has - * not been set, then a dialog will be opened. - * - * @since 3.5 - */ - -public class ColocatedRepositoryManipulator extends RepositoryManipulator { - - Policy policy; - String prefPageId = null; - - public ColocatedRepositoryManipulator(Policy policy, String prefPageId) { - this.policy = policy; - this.prefPageId = prefPageId; - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getManipulatorButtonLabel() - */ - public String getManipulatorButtonLabel() { - return ProvUIMessages.ColocatedRepositoryManipulator_ManageSites; - - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#manipulateRepositories(org.eclipse.swt.widgets.Shell) - */ - public boolean manipulateRepositories(Shell shell) { - if (prefPageId != null) { - PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(shell, prefPageId, null, null); - dialog.open(); - } else { - TitleAreaDialog dialog = new TitleAreaDialog(shell) { - RepositoryManipulationPage page; - - protected Control createDialogArea(Composite parent) { - page = new RepositoryManipulationPage(); - page.setPolicy(policy); - page.init(PlatformUI.getWorkbench()); - page.createControl(parent); - this.setTitle(ProvUIMessages.RepositoryManipulationPage_Title); - this.setMessage(ProvUIMessages.RepositoryManipulationPage_Description); - return page.getControl(); - } - - protected void okPressed() { - if (page.performOk()) - super.okPressed(); - } - - protected void cancelPressed() { - if (page.performCancel()) - super.cancelPressed(); - } - }; - dialog.open(); - } - return true; - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getAddOperation(java.net.URI) - */ - public AddRepositoryOperation getAddOperation(URI repoLocation) { - return new AddColocatedRepositoryOperation(getAddOperationLabel(), repoLocation); - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getAddOperationLabel() - */ - public String getAddOperationLabel() { - return ProvUIMessages.ColocatedRepositoryManipulator_AddSiteOperationLabel; - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getKnownRepositories() - */ - public URI[] getKnownRepositories() { - try { - return ProvisioningUtil.getMetadataRepositories(policy.getQueryContext().getMetadataRepositoryFlags()); - } catch (ProvisionException e) { - return new URI[0]; - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getRemoveOperation(java.net.URI[]) - */ - public RemoveRepositoryOperation getRemoveOperation(URI[] reposToRemove) { - return new RemoveColocatedRepositoryOperation(getRemoveOperationLabel(), reposToRemove); - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getRemoveOperationLabel() - */ - public String getRemoveOperationLabel() { - return ProvUIMessages.ColocatedRepositoryManipulator_RemoveSiteOperationLabel; - } - - /* - * (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getURLValidator(org.eclipse.swt.widgets.Shell) - */ - public RepositoryLocationValidator getRepositoryLocationValidator(Shell shell) { - DefaultMetadataURLValidator validator = new DefaultMetadataURLValidator(); - validator.setKnownRepositoriesFlag(policy.getQueryContext().getMetadataRepositoryFlags()); - return validator; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getManipulatorLinkLabel() - */ - public String getManipulatorLinkLabel() { - return ProvUIMessages.ColocatedRepositoryManipulator_GotoPrefs; - - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getSiteNotFoundCorrectionString() - */ - public String getRepositoryNotFoundInstructionString() { - return ProvUIMessages.ColocatedRepositoryManipulator_SiteNotFoundDescription; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator#getManipulatorInstructionString() - */ - public String getManipulatorInstructionString() { - return ProvUIMessages.ColocatedRepositoryManipulator_NoContentExplanation; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/IProfileChooser.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/IProfileChooser.java deleted file mode 100644 index 9bf0036ef..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/IProfileChooser.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.policy; - -import org.eclipse.swt.widgets.Shell; - -/** - * Interface for a mechanism that chooses a profile from the profile registry. - * the mechanism may or may not involve the user. - * - * @since 3.4 - * - */ - -public interface IProfileChooser { - /** - * Return a chosen profile id, or null if there is no profile - * chosen. - */ - public String getProfileId(Shell shell); -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/IUViewQueryContext.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/IUViewQueryContext.java deleted file mode 100644 index 7f5c5a498..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/IUViewQueryContext.java +++ /dev/null @@ -1,210 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.policy; - -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; - -/** - * IUViewQueryContext defines the different ways - * IUs can be viewed. Clients can use this context to - * control how the various IU views are represented and traversed. - * - * @since 3.4 - */ -public class IUViewQueryContext { - public static final int AVAILABLE_VIEW_BY_CATEGORY = 1; - public static final int AVAILABLE_VIEW_BY_REPO = 2; - public static final int AVAILABLE_VIEW_FLAT = 3; - - // Available view settings - // Default available view to repo as this provides the fastest information - private int view = AVAILABLE_VIEW_BY_REPO; - // What property to use for choosing visible IUs - private String visibleAvailableIUProperty = IInstallableUnit.PROP_TYPE_GROUP; - // Whether to show latest versions only, defaults to - // true. Clients typically use a pref setting or dialog - // setting to initialize - private boolean showLatestVersionsOnly = true; - // Whether to hide things that are already installed - // Defaults to false since we wouldn't know what profile to use - private boolean hideAlreadyInstalled = false; - // Whether to group items in repos by category. Note this only makes sense when the - // view type is AVAILABLE_VIEW_BY_REPO - private boolean useCategories = true; - // Whether to drill down into installed items - private boolean showInstallChildren = true; - // Whether to drill down into available items - private boolean showAvailableChildren = false; - // Whether to drill down into items in a provisioning plan - private boolean showProvisioningPlanChildren = true; - - private String profileId = null; - // What repositories to show - private int artifactRepositoryFlags = IRepositoryManager.REPOSITORIES_NON_SYSTEM; - private int metadataRepositoryFlags = IRepositoryManager.REPOSITORIES_NON_SYSTEM; - - // Installed view settings - private String visibleInstalledIUProperty = IInstallableUnit.PROP_PROFILE_ROOT_IU; - - private String hidingInstalledDescription = ProvUIMessages.IUViewQueryContext_AllAreInstalledDescription; - private String groupingCategoriesDescription = ProvUIMessages.IUViewQueryContext_NoCategorizedItemsDescription; - - public IUViewQueryContext(int viewType) { - this.view = viewType; - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.ui.query.QueryContext#getQueryType() - */ - public int getQueryType() { - if (view == AVAILABLE_VIEW_BY_REPO) - return QueryProvider.METADATA_REPOS; - return QueryProvider.AVAILABLE_IUS; - } - - public int getViewType() { - return view; - } - - public void setViewType(int viewType) { - view = viewType; - } - - public boolean getShowLatestVersionsOnly() { - return showLatestVersionsOnly; - } - - public void setShowLatestVersionsOnly(boolean showLatest) { - showLatestVersionsOnly = showLatest; - } - - public void hideAlreadyInstalled(String installedProfileId) { - profileId = installedProfileId; - hideAlreadyInstalled = true; - } - - public void showAlreadyInstalled() { - hideAlreadyInstalled = false; - } - - public boolean getHideAlreadyInstalled() { - return hideAlreadyInstalled; - } - - public String getInstalledProfileId() { - return profileId; - } - - public void setInstalledProfileId(String profileId) { - this.profileId = profileId; - } - - public int getArtifactRepositoryFlags() { - return artifactRepositoryFlags; - } - - public void setArtifactRepositoryFlags(int flags) { - artifactRepositoryFlags = flags; - } - - public int getMetadataRepositoryFlags() { - return metadataRepositoryFlags; - } - - public void setMetadataRepositoryFlags(int flags) { - metadataRepositoryFlags = flags; - } - - public String getVisibleAvailableIUProperty() { - return visibleAvailableIUProperty; - } - - public void setVisibleAvailableIUProperty(String propertyName) { - visibleAvailableIUProperty = propertyName; - } - - public String getVisibleInstalledIUProperty() { - return visibleInstalledIUProperty; - } - - public void setVisibleInstalledIUProperty(String propertyName) { - visibleInstalledIUProperty = propertyName; - } - - /** - * Set a boolean that indicates whether categories should be used when - * viewing by repository. - * - * useCategories true if a site in a sites view should expand into categories, - * false if it should expand into IU's. - */ - - public void setUseCategories(boolean useCategories) { - this.useCategories = useCategories; - } - - /** - * Return a boolean that indicates whether categories should be used when - * viewing by repository. - * - * @return true if a site in a sites view should expand into categories, - * false if it should expand into IU's. - */ - public boolean getUseCategories() { - return useCategories; - } - - public boolean getShowInstallChildren() { - return showInstallChildren; - } - - public void setShowInstallChildren(boolean showChildren) { - showInstallChildren = showChildren; - } - - public boolean getShowAvailableChildren() { - return showAvailableChildren; - } - - public void setShowAvailableChildren(boolean showChildren) { - showAvailableChildren = showChildren; - } - - public boolean getShowProvisioningPlanChildren() { - return showProvisioningPlanChildren; - } - - public void setShowProvisioningPlanChildren(boolean showChildren) { - showProvisioningPlanChildren = showChildren; - } - - public String getHidingInstalledDescription() { - return hidingInstalledDescription; - } - - public void setHidingInstalledDescription(String description) { - hidingInstalledDescription = description; - } - - public String getUsingCategoriesDescription() { - return groupingCategoriesDescription; - } - - public void setUsingCategoriesDescription(String description) { - groupingCategoriesDescription = description; - } - - public boolean shouldGroupByCategories() { - return view == AVAILABLE_VIEW_BY_CATEGORY || (view == AVAILABLE_VIEW_BY_REPO && useCategories); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/LicenseManager.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/LicenseManager.java deleted file mode 100644 index a9838f122..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/LicenseManager.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.policy; - -import java.io.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; - -/** - * Abstract class for a manager which tracks which licenses have been accepted. - * - * @since 3.4 - */ -public abstract class LicenseManager { - - public abstract boolean accept(IInstallableUnit iu); - - public abstract boolean reject(IInstallableUnit iu); - - public abstract boolean isAccepted(IInstallableUnit iu); - - public abstract boolean hasAcceptedLicenses(); - - /** - * - * @param stream - * @throws IOException - * @since 3.5 - */ - public abstract void write(OutputStream stream) throws IOException; - - /** - * - * @param stream - * @throws IOException - * @since 3.5 - */ - public abstract void read(InputStream stream) throws IOException; - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/PlanValidator.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/PlanValidator.java deleted file mode 100644 index e324ddc4c..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/PlanValidator.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.policy; - -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.swt.widgets.Shell; - -/** - * Abstract class for a mechanism that checks a provisioning plan to see - * if a user should be allowed to perform a provisioning action on it. - * - * @since 3.4 - * - * @see org.eclipse.equinox.internal.provisional.p2.ui.actions.ProfileModificationAction - * - */ - -public abstract class PlanValidator { - /** - * Return a boolean indicating whether the caller should continue working - * with the provisioning plan. This method is used to give implementors a chance - * to validate or check a plan before continuing. The work that the caller intends - * to do depends on the context in which this validator is used. When the validator is used - * for an action, it may mean opening a wizard on the plan. When the validator is used - * inside a wizard, it may mean attempting to perform the plan. It is up to the implementor of - * this method to report any errors to user or otherwise inform the user if the - * outcome is false. - * - * @param plan a ProvisioningPlan that the caller wishes to work with. Never null. - * @param shell the Shell that may be used to report any errors or prompt the user. May be null. - * @return true if the caller should continue working with the plan, or - * false if the caller should stop. If false it is expected that - * any error reporting has already been completed. - */ - public abstract boolean continueWorkingWithPlan(ProvisioningPlan plan, Shell shell); - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/Policy.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/Policy.java deleted file mode 100644 index d39442c42..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/Policy.java +++ /dev/null @@ -1,289 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.policy; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.ui.*; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.ui.IStatusCodes; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.statushandlers.StatusManager; - -/** - * The Policy class is used to locate application specific policies that - * should be used in the standard p2 UI class libraries. The default policy - * is acquired using the OSGi service model. - * - * Policy allows clients to specify things such as how repositories - * are manipulated in the standard wizards and dialogs, and how the repositories - * or the installation itself should be traversed when displaying content. - * - * In some cases, the Policy is used only to define a default value that can - * be overridden by user choice and subsequently stored in dialog settings. - * - * Client applications should ensure that their Policy is registered before - * any of the p2 UI objects access the default Policy. - * - * @since 3.5 - */ - -public class Policy { - - private static Policy defaultInstance; - - private QueryProvider queryProvider; - private LicenseManager licenseManager; - private PlanValidator planValidator; - private IProfileChooser profileChooser; - private IUViewQueryContext queryContext; - private RepositoryManipulator repositoryManipulator; - - /** - * Get the default policy that should be used for determining the behavior of the UI. - * The default policy is acquired using OSGi services. The highest ranking implementation - * of the Policy service will be used, or a default policy if no policy was registered. - * - * @return the Policy that should be used - */ - public static Policy getDefault() { - if (defaultInstance == null) { - defaultInstance = (Policy) ServiceHelper.getService(ProvUIActivator.getContext(), Policy.class.getName()); - if (defaultInstance == null) - defaultInstance = new Policy(); - } - return defaultInstance; - } - - /** - * Returns the query provider used to query for the UI elements shown - * in the various UI components. - * - * @return the queryProvider - */ - public QueryProvider getQueryProvider() { - if (queryProvider == null) { - queryProvider = getDefaultQueryProvider(); - } - return queryProvider; - } - - /** - * Set the query provider used to query for the UI elements shown in - * the various UI components. - * - * @param provider - * the provider to use, or null to use the default - * provider - */ - public void setQueryProvider(QueryProvider provider) { - queryProvider = provider; - } - - /** - * Returns the license manager used to remember accepted licenses - * - * @return the licenseManager - */ - public LicenseManager getLicenseManager() { - if (licenseManager == null) { - licenseManager = getDefaultLicenseManager(); - } - return licenseManager; - } - - /** - * Set the license manager used to remember accepted licenses. - * - * @param manager the manager to use, or null to use - * the default manager - */ - public void setLicenseManager(LicenseManager manager) { - licenseManager = manager; - } - - /** - * Returns the plan validator used to validate a proposed provisioning - * plan - * - * @return the plan validator - */ - public PlanValidator getPlanValidator() { - if (planValidator == null) { - planValidator = getDefaultPlanValidator(); - } - return planValidator; - } - - /** - * Set the plan validator used to validate a proposed provisioning - * plan - * - * @param validator the validator to use, or null to use - * the default validator - */ - public void setPlanValidator(PlanValidator validator) { - planValidator = validator; - } - - /** - * Get the profile chooser used to provide a profile id when performing - * operations on a profile and the profile id is not otherwise specified. - * - * @return the profile chooser - */ - public IProfileChooser getProfileChooser() { - if (profileChooser == null) { - profileChooser = getDefaultProfileChooser(); - } - return profileChooser; - } - - /** - * Set the profile chooser used to provide a profile id when performing - * operations on a profile and the profile id is not otherwise specified. - * - * @param chooser the chooser to use, or null to use - * the default chooser - */ - public void setProfileChooser(IProfileChooser chooser) { - profileChooser = chooser; - } - - /** - * Get the query context that is used to drive the filtering and - * traversal of any IU views - * - * @return the queryContext - */ - public IUViewQueryContext getQueryContext() { - if (queryContext == null) { - queryContext = getDefaultQueryContext(); - } - return queryContext; - } - - /** - * Set the query context that is used to drive the filtering and - * traversal of any IU views - * - * @param context the context to use, or null to use - * the default context - */ - public void setQueryContext(IUViewQueryContext context) { - queryContext = context; - } - - /** - * Get the repository manipulator that is used to perform repository - * operations given a URL. - * - * @return the repository manipulator - */ - public RepositoryManipulator getRepositoryManipulator() { - return repositoryManipulator; - } - - /** - * Set the repository manipulator that is used to perform repository - * operations given a URL. - * - * @param manipulator the manipulator to use, or null to use - * the default manipulator - */ - public void setRepositoryManipulator(RepositoryManipulator manipulator) { - repositoryManipulator = manipulator; - } - - /** - * Reset all of the policies to their default values - */ - public void reset() { - licenseManager = null; - planValidator = null; - profileChooser = null; - queryContext = null; - queryProvider = null; - repositoryManipulator = null; - } - - /* - * Returns the plan validator to use if none has been set. This - * validator approves every plan. - */ - private PlanValidator getDefaultPlanValidator() { - return new PlanValidator() { - public boolean continueWorkingWithPlan(ProvisioningPlan plan, Shell shell) { - if (plan == null) - return false; - if (plan.getStatus().getSeverity() == IStatus.CANCEL) - return false; - - // Special case those statuses where we would never want to open a wizard - if (plan.getStatus().getCode() == IStatusCodes.NOTHING_TO_UPDATE) { - ProvUI.reportStatus(plan.getStatus(), StatusManager.BLOCK); - return false; - } - // Allow the wizard to open otherwise. - return true; - } - }; - } - - /* - * Returns the license manager to use if none has been set. - */ - private LicenseManager getDefaultLicenseManager() { - return new SimpleLicenseManager(); - } - - /* - * Returns the profile chooser to use if none has been set. - * This profile chooser uses the profile id of the running - * application. - */ - private IProfileChooser getDefaultProfileChooser() { - return new IProfileChooser() { - public String getProfileId(Shell shell) { - return IProfileRegistry.SELF; - } - }; - } - - /* - * Returns the query provider used to provide a descriptor for - * the various queries that are used to show the UI elements of a - * particular installation. The default returns - * a null query descriptor. - */ - private QueryProvider getDefaultQueryProvider() { - return new DefaultQueryProvider(this); - } - - /* - * Returns an IUViewQueryContext with default values - */ - private IUViewQueryContext getDefaultQueryContext() { - return new IUViewQueryContext(IUViewQueryContext.AVAILABLE_VIEW_BY_REPO); - } - - /** - * Return a status that can be used to describe the failure to - * retrieve a profile. - * @return a status describing a failure to retrieve a profile, - * or null if there is no such status. - */ - public IStatus getNoProfileChosenStatus() { - return null; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/QueryProvider.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/QueryProvider.java deleted file mode 100644 index af01181f4..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/QueryProvider.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.policy; - -import org.eclipse.equinox.internal.p2.ui.model.QueriedElement; -import org.eclipse.equinox.internal.provisional.p2.ui.ElementQueryDescriptor; - -/** - * An abstract class for an object that provides element queries - * - * @since 3.5 - */ -public abstract class QueryProvider { - - public static final int METADATA_REPOS = 1; - public static final int ARTIFACT_REPOS = 2; - public static final int PROFILES = 3; - public static final int AVAILABLE_IUS = 4; - public static final int AVAILABLE_UPDATES = 5; - public static final int INSTALLED_IUS = 6; - - public abstract ElementQueryDescriptor getQueryDescriptor(QueriedElement element); -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/RepositoryLocationValidator.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/RepositoryLocationValidator.java deleted file mode 100644 index 4f8e34b79..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/RepositoryLocationValidator.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.policy; - -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.repository.helpers.RepositoryHelper; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.osgi.util.NLS; - -/** - * - * RepositoryLocationValidator can be used to validate a repository URL. Validation may - * involve rules known by the validator itself or contact with a repository - * manager. - * - * @since 3.4 - * - */ -public abstract class RepositoryLocationValidator { - - public static final int LOCAL_VALIDATION_ERROR = 3000; - public static final int ALTERNATE_ACTION_TAKEN = 3001; - - public static IStatus getInvalidLocationStatus(String urlText) { - return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, LOCAL_VALIDATION_ERROR, NLS.bind(ProvUIMessages.URLValidator_UnrecognizedURL, urlText), null); - } - - public static URI locationFromString(String locationString) { - URI userLocation; - try { - userLocation = URIUtil.fromString(locationString); - } catch (URISyntaxException e) { - return null; - } - // If a path separator char was used, interpret as a local file URI - String uriString = URIUtil.toUnencodedString(userLocation); - if (uriString.length() > 0 && (uriString.charAt(0) == '/' || uriString.charAt(0) == File.separatorChar)) - return RepositoryHelper.localRepoURIHelper(userLocation); - return userLocation; - } - - public abstract IStatus validateRepositoryLocation(URI url, boolean contactRepositories, IProgressMonitor monitor); -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/RepositoryManipulator.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/RepositoryManipulator.java deleted file mode 100644 index 6f7d9f74c..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/policy/RepositoryManipulator.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.policy; - -import java.net.URI; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.AddRepositoryOperation; -import org.eclipse.equinox.internal.provisional.p2.ui.operations.RemoveRepositoryOperation; -import org.eclipse.swt.widgets.Shell; - -/** - * Abstract class for a mechanism that allows the user to manipulate which repositories - * are in the system. - * - * @since 3.4 - * - */ - -public abstract class RepositoryManipulator { - /** - * Invoke whatever mechanism is used to manipulate repositories. - * Return a boolean indicating whether the repositories were - * actually manipulated in any way. - */ - public abstract boolean manipulateRepositories(Shell shell); - - /** - * Return a short String that could be used to label this manager in a button. - * This string should include any necessary ellipsis or mnemonics. - */ - public abstract String getManipulatorButtonLabel(); - - /** - * Return a long String that could be used to label this manager in a link. - * This string does not need mnemonics. - */ - public abstract String getManipulatorLinkLabel(); - - /** - * Return an array of URLs containing the repositories already known. - */ - public abstract URI[] getKnownRepositories(); - - /** - * Return an operation that could be used to add the specified URL as - * a repository. - */ - public abstract AddRepositoryOperation getAddOperation(URI repoLocation); - - /** - * Return a String describing a possible add operation. This is used - * when prompting or reporting errors involving a possible add operation. - */ - public abstract String getAddOperationLabel(); - - /** - * Return an operation that could be used to remove the specified URL as - * a repositories. - */ - public abstract RemoveRepositoryOperation getRemoveOperation(URI[] repoLocations); - - /** - * Return a String describing a possible remove operation. This is used - * when prompting or reporting errors involving a possible remove operation. - */ - public abstract String getRemoveOperationLabel(); - - /** - * Get a URL validator that could be used to validate URLs supplied - * by the user. - * - * @param shell the shell used by the validator to report any problems. - * @return the validator to be used. - */ - - public abstract RepositoryLocationValidator getRepositoryLocationValidator(Shell shell); - - /** - * Return a string giving the user further instruction when a site was found. This - * is a textual description that can tell the user why a site might be empty, or - * telling the user to use the manipulator (ie, go to the preferences page). - */ - public abstract String getRepositoryNotFoundInstructionString(); - - /** - * Return a string giving the user further instruction about how to manipulate - * repositories. The {@link #getManipulatorLinkLabel()} and {@link #getManipulatorButtonLabel()} - * are used to label the link and/or button used to launch the UI for adding and removing - * repositories. This string is a textual description (without a link) suggesting ways - * that a user might manipulate repositories. - */ - public abstract String getManipulatorInstructionString(); -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/IUColumnConfig.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/IUColumnConfig.java deleted file mode 100644 index 9629b5a1f..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/IUColumnConfig.java +++ /dev/null @@ -1,172 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.viewers; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.swt.graphics.FontMetrics; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.widgets.Control; - -/** - * An IUColumnConfig describes a column in a viewer that is showing - * information about an IIInstallableUnit. - * - * @since 3.4 - */ -public class IUColumnConfig { - /** - * Constant indicating that the column represents an IInstallableUnit's id - */ - public final static int COLUMN_ID = 0; - - /** - * Constant indicating that the column represents an IInstallableUnit's name - */ - public final static int COLUMN_NAME = 1; - - /** - * Constant indicating that the column represents an IInstallableUnit's version - */ - public final static int COLUMN_VERSION = 2; - - /** - * Constant indicating that the column represents an IInstallableUnit's size - */ - public final static int COLUMN_SIZE = 3; - - private String columnTitle; - private int columnType; - private int columnWidth; - private int columnWidthInPixels; - - /** - * Create an IUColumnConfig describing a column with the specified title, type, and - * default width. - * - * @param title the title that should appear for the column - * @param columnType the type of column represented. The type may be used to determine - * appropriate size or formatting of the column's content. - * @param columnWidthInChars the width (in characters) that should be used for the column if no - * other width is specified by the client. - */ - - public IUColumnConfig(String title, int columnType, int columnWidthInChars) { - this.columnTitle = title; - this.columnType = columnType; - this.columnWidth = columnWidthInChars; - this.columnWidthInPixels = -1; - } - - /** - * Return the title of the column. - * @return the title that should be used for the column. - * - * @since 3.6 - */ - public String getColumnTitle() { - return columnTitle; - } - - /** - * Set the title of the column - * @param title the String that should be used when the column's title is shown - * - * @since 3.6 - */ - public void setColumnTitle(String title) { - this.columnTitle = title; - } - - /** - * Return the width of the column in character width units - * @return the width (in characters) of the column - * - * @since 3.6 - */ - public int getWidthInChars() { - return columnWidth; - } - - /** - * Set the width of the column in character width units - * @param columnWidth the width (in characters) of the column - * - * @since 3.6 - */ - public void setWidthInChars(int columnWidth) { - this.columnWidth = columnWidth; - } - - /** - * Get the width in pixels of this column when displayed in the specified - * control. If a specific width in pixels has already been specified by a client, - * that width is used. Otherwise, the value is computed based on the character - * width specified for the column. - * @param control - * @return the width in pixels that should be used for the column - * - * @since 3.6 - * - * @see #setWidthInPixels(int) - */ - public int getWidthInPixels(Control control) { - if (columnWidthInPixels >= 0) - return columnWidthInPixels; - - GC gc = new GC(control); - FontMetrics fm = gc.getFontMetrics(); - columnWidthInPixels = Dialog.convertWidthInCharsToPixels(fm, columnWidth); - return columnWidthInPixels; - } - - /** - * Set the width in pixels that should be used for this column. This width overrides - * any character width that has been specified. This method is useful when the column width - * is determined by user action. - * - * @param width - * - * @since 3.6 - */ - public void setWidthInPixels(int width) { - this.columnWidthInPixels = width; - } - - /** - * Return the type of column. - * @return an Integer constant specifying the type of data being shown in the column. - * - * @since 3.6 - * @see #COLUMN_ID - * @see #COLUMN_NAME - * @see #COLUMN_SIZE - * @see #COLUMN_VERSION - */ - public int getColumnType() { - return columnType; - } - - /** - * Set the type of column. - * @param type an Integer constant specifying the type of data being shown in the column. - * - * @since 3.6 - * - * @see #COLUMN_ID - * @see #COLUMN_NAME - * @see #COLUMN_SIZE - * @see #COLUMN_VERSION - */ - public void setColumnType(int type) { - this.columnType = type; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/IUComparator.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/IUComparator.java deleted file mode 100644 index ca04786c5..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/IUComparator.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.viewers; - -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.IUPropertyUtils; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerComparator; - -public class IUComparator extends ViewerComparator { - public static final int IU_NAME = 0; - public static final int IU_ID = 1; - private int key; - private boolean showingId = false; - - public IUComparator(int sortKey) { - this.key = sortKey; - showingId = sortKey == IU_ID; - } - - /** - * Use the specified column config to determine - * whether the id should be used in lieu of an empty name - * when sorting. - * - * @param columnConfig - */ - public void useColumnConfig(IUColumnConfig[] columnConfig) { - for (int i = 0; i < columnConfig.length; i++) - if (columnConfig[i].getColumnType() == IUColumnConfig.COLUMN_ID) { - showingId = true; - break; - } - } - - public int compare(Viewer viewer, Object obj1, Object obj2) { - IInstallableUnit iu1 = (IInstallableUnit) ProvUI.getAdapter(obj1, IInstallableUnit.class); - IInstallableUnit iu2 = (IInstallableUnit) ProvUI.getAdapter(obj2, IInstallableUnit.class); - if (iu1 == null || iu2 == null) - // If these are not iu's use the super class comparator. - return super.compare(viewer, obj1, obj2); - - String key1, key2; - if (key == IU_NAME) { - // Compare the iu names in the default locale. - // If a name is not defined, we use blank if we know the id is shown in another - // column. If the id is not shown elsewhere, then we are displaying it, so use - // the id instead. - key1 = IUPropertyUtils.getIUProperty(iu1, IInstallableUnit.PROP_NAME); - if (key1 == null) - if (showingId) - key1 = ""; //$NON-NLS-1$ - else - key1 = iu1.getId(); - key2 = IUPropertyUtils.getIUProperty(iu2, IInstallableUnit.PROP_NAME); - if (key2 == null) - if (showingId) - key2 = ""; //$NON-NLS-1$ - else - key2 = iu2.getId(); - } else { - key1 = iu1.getId(); - key2 = iu2.getId(); - } - - int result = 0; - result = key1.compareToIgnoreCase(key2); - if (result == 0) { - // We want to show later versions first so compare backwards. - result = iu2.getVersion().compareTo(iu1.getVersion()); - } - return result; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/IUDragAdapter.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/IUDragAdapter.java deleted file mode 100644 index e6fddb88e..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/IUDragAdapter.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.viewers; - -import java.util.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.jface.util.LocalSelectionTransfer; -import org.eclipse.jface.viewers.*; -import org.eclipse.swt.dnd.*; -import org.eclipse.swt.widgets.Control; - -/** - * Implements drag behaviour when IU items are dragged from a repository view. - * - * @since 3.4 - */ -public class IUDragAdapter extends DragSourceAdapter { - - ISelectionProvider selectionProvider; - - /** - * Constructs a new drag adapter. - * - * @param provider - * The selection provider - */ - public IUDragAdapter(ISelectionProvider provider) { - selectionProvider = provider; - } - - /** - * Set the drag data to represent the local selection of IU's if possible. - * Fallback to using a text description of each IU. - */ - public void dragSetData(DragSourceEvent event) { - IInstallableUnit[] ius = getSelectedIUs(); - - if (ius == null || ius.length == 0) { - return; - } - - // use local selection transfer if possible - if (LocalSelectionTransfer.getTransfer().isSupportedType(event.dataType)) { - event.data = LocalSelectionTransfer.getTransfer().getSelection(); - return; - } - // resort to a text transfer - if (!TextTransfer.getInstance().isSupportedType(event.dataType)) { - return; - } - - // Get a text description of each IU and set as the drag data - final StringBuffer buffer = new StringBuffer(); - - for (int i = 0; i < ius.length; i++) { - buffer.append(ius[i].toString()); - buffer.append('\n'); - } - event.data = buffer.toString(); - } - - /** - * Start the drag only if the selection contains IUs. - */ - public void dragStart(DragSourceEvent event) { - - // Focus workaround copied from navigator drag adapter - DragSource dragSource = (DragSource) event.widget; - Control control = dragSource.getControl(); - if (control != control.getDisplay().getFocusControl()) { - event.doit = false; - return; - } - - // Check the selection - IStructuredSelection selection = (IStructuredSelection) selectionProvider.getSelection(); - // No drag if nothing is selected - if (selection.isEmpty()) { - event.doit = false; - return; - } - if (!areOnlyIUsSelected(selection)) { - event.doit = false; - return; - } - LocalSelectionTransfer.getTransfer().setSelection(selection); - event.doit = true; - } - - private IInstallableUnit[] getSelectedIUs() { - List ius = new ArrayList(); - - ISelection selection = selectionProvider.getSelection(); - if (!(selection instanceof IStructuredSelection) || selection.isEmpty()) { - return null; - } - IStructuredSelection structuredSelection = (IStructuredSelection) selection; - - Iterator iter = structuredSelection.iterator(); - while (iter.hasNext()) { - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(iter.next(), IInstallableUnit.class); - if (iu != null) { - ius.add(iu); - } - } - return (IInstallableUnit[]) ius.toArray(new IInstallableUnit[ius.size()]); - } - - private boolean areOnlyIUsSelected(IStructuredSelection selection) { - Iterator iter = selection.iterator(); - while (iter.hasNext()) { - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(iter.next(), IInstallableUnit.class); - if (iu == null) { - return false; - } - } - return true; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/InstallIUDropAdapter.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/InstallIUDropAdapter.java deleted file mode 100644 index 74f503004..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/InstallIUDropAdapter.java +++ /dev/null @@ -1,218 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.viewers; - -import java.util.*; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.InstallAction; -import org.eclipse.equinox.internal.provisional.p2.ui.model.InstalledIUElement; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.util.LocalSelectionTransfer; -import org.eclipse.jface.viewers.*; -import org.eclipse.swt.dnd.*; - -/** - * Defines drop behavior for selected IUs to mean install the IU on the target - * profile. - * - * @since 3.4 - * - */ -public class InstallIUDropAdapter extends ViewerDropAdapter { - - static boolean DEBUG = false; - Policy policy; - - /** - * Constructs a new drop adapter. - * - * @param viewer - * the navigator's viewer - */ - public InstallIUDropAdapter(Policy policy, StructuredViewer viewer) { - super(viewer); - this.policy = policy; - } - - /** - * Returns an error status with the given info. - */ - IStatus error(String message) { - return error(message, null); - } - - /** - * Returns an error status with the given info. - */ - IStatus error(String message, Throwable exception) { - return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, 0, message, exception); - } - - /** - * Returns the target profile id for the drop. If the drop is positioned on an - * IU, return its parent profile id. - */ - private String getProfileTarget(Object mouseTarget) { - IProfile profile = (IProfile) ProvUI.getAdapter(mouseTarget, IProfile.class); - if (profile != null) { - return profile.getProfileId(); - } - - if (mouseTarget instanceof InstalledIUElement) { - return ((InstalledIUElement) mouseTarget).getProfileId(); - } - return null; - } - - /** - * Returns an status indicating success. - */ - private IStatus ok() { - return new Status(IStatus.OK, ProvUIActivator.PLUGIN_ID, 0, null, null); - } - - /** - * Perform the drop. - * - * @see org.eclipse.swt.dnd.DropTargetListener#drop(org.eclipse.swt.dnd.DropTargetEvent) - */ - public boolean performDrop(final Object data) { - if (DEBUG) { - System.out.println("Perform drop on target: " + getCurrentTarget() + " with data: " + data); //$NON-NLS-1$//$NON-NLS-2$ - } - if (getCurrentTarget() == null || data == null) - return false; - - ISelection selection = LocalSelectionTransfer.getTransfer().getSelection(); - if (!(selection instanceof IStructuredSelection) || selection.isEmpty()) - return false; - - String profileId = getProfileTarget(getCurrentTarget()); - if (getCurrentOperation() == DND.DROP_COPY && profileId != null) { - final IStructuredSelection structuredSelection = (IStructuredSelection) selection; - ISelectionProvider selectionProvider = new ISelectionProvider() { - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ISelectionProvider#addSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) - */ - public void addSelectionChangedListener(ISelectionChangedListener listener) { - // Ignore because the selection won't change - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ISelectionProvider#getSelection() - */ - public ISelection getSelection() { - if (DEBUG) { - System.out.println("Selection was queried by action"); //$NON-NLS-1$ - System.out.println(structuredSelection.toString()); - } - return structuredSelection; - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ISelectionProvider#removeSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) - */ - public void removeSelectionChangedListener(ISelectionChangedListener listener) { - // ignore because the selection is static - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ISelectionProvider#setSelection(org.eclipse.jface.viewers.ISelection) - */ - public void setSelection(ISelection sel) { - throw new UnsupportedOperationException("This ISelectionProvider is static, and cannot be modified."); //$NON-NLS-1$ - } - }; - InstallAction action = new InstallAction(policy, selectionProvider, profileId); - if (DEBUG) - System.out.println("Running install action"); //$NON-NLS-1$ - action.run(); - return true; - } - return false; - } - - /** - * Validate whether the drop is valid for the target - */ - public boolean validateDrop(Object target, int dragOperation, TransferData transferType) { - - if (LocalSelectionTransfer.getTransfer().isSupportedType(transferType)) { - IStatus status = validateTarget(target, transferType); - if (DEBUG) { - System.out.println("Validate target: " + status); //$NON-NLS-1$ - } - return status.isOK(); - } - return false; - } - - /* - * Overridden to force a copy when the drag is valid. - * - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.ViewerDropAdapter#dragEnter(org.eclipse.swt.dnd.DropTargetEvent) - */ - public void dragEnter(DropTargetEvent event) { - event.detail = DND.DROP_COPY; - super.dragEnter(event); - } - - /** - * Ensures that the drop target meets certain criteria - */ - private IStatus validateTarget(Object target, TransferData transferType) { - if (LocalSelectionTransfer.getTransfer().isSupportedType(transferType)) { - IInstallableUnit[] ius = getSelectedIUs(); - - if (ius.length == 0) { - return error(ProvUIMessages.ProvDropAdapter_NoIUsToDrop); - } - if (getProfileTarget(target) != null) { - return ok(); - } - return error(ProvUIMessages.ProvDropAdapter_InvalidDropTarget); - } - return error(ProvUIMessages.ProvDropAdapter_UnsupportedDropOperation); - } - - /** - * Returns the resource selection from the LocalSelectionTransfer. - * - * @return the resource selection from the LocalSelectionTransfer - */ - private IInstallableUnit[] getSelectedIUs() { - ISelection selection = LocalSelectionTransfer.getTransfer().getSelection(); - List ius = new ArrayList(); - - if (!(selection instanceof IStructuredSelection) || selection.isEmpty()) { - return null; - } - IStructuredSelection structuredSelection = (IStructuredSelection) selection; - - Iterator iter = structuredSelection.iterator(); - while (iter.hasNext()) { - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(iter.next(), IInstallableUnit.class); - if (iu != null) { - ius.add(iu); - } - } - return (IInstallableUnit[]) ius.toArray(new IInstallableUnit[ius.size()]); - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/ProvElementComparer.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/ProvElementComparer.java deleted file mode 100644 index 3f4c11c96..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/ProvElementComparer.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.ui.viewers; - -import java.net.URI; -import org.eclipse.equinox.internal.p2.ui.model.CategoryElement; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IRepositoryElement; -import org.eclipse.equinox.internal.provisional.p2.ui.model.ProfileElement; -import org.eclipse.jface.viewers.IElementComparer; - -public class ProvElementComparer implements IElementComparer { - - public boolean equals(Object a, Object b) { - // We treat category elements specially because this - // is one case where resolving down to an IU will lose identity - // differences. (category IU's with the same name and version number cannot be treated the same). - if (a instanceof CategoryElement || b instanceof CategoryElement) - return a.equals(b); - IInstallableUnit iu1 = getIU(a); - IInstallableUnit iu2 = getIU(b); - if (iu1 != null && iu2 != null) - return iu1.equals(iu2); - String p1 = getProfileId(a); - String p2 = getProfileId(b); - if (p1 != null && p2 != null) - return p1.equals(p2); - URI r1 = getRepositoryLocation(a); - URI r2 = getRepositoryLocation(b); - if (r1 != null && r2 != null) - return r1.equals(r2); - return a.equals(b); - } - - public int hashCode(Object element) { - if (element instanceof CategoryElement) - return element.hashCode(); - IInstallableUnit iu = getIU(element); - if (iu != null) - return iu.hashCode(); - String profileId = getProfileId(element); - if (profileId != null) - return profileId.hashCode(); - URI location = getRepositoryLocation(element); - if (location != null) - return location.hashCode(); - return element.hashCode(); - } - - private IInstallableUnit getIU(Object obj) { - return (IInstallableUnit) ProvUI.getAdapter(obj, IInstallableUnit.class); - } - - private String getProfileId(Object obj) { - if (obj instanceof ProfileElement) - return ((ProfileElement) obj).getLabel(obj); - IProfile profile = (IProfile) ProvUI.getAdapter(obj, IProfile.class); - if (profile == null) - return null; - return profile.getProfileId(); - } - - private URI getRepositoryLocation(Object obj) { - if (obj instanceof IRepositoryElement) - return ((IRepositoryElement) obj).getLocation(); - return null; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/ProvElementContentProvider.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/ProvElementContentProvider.java deleted file mode 100644 index 9fe429748..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/ProvElementContentProvider.java +++ /dev/null @@ -1,160 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.viewers; - -import java.util.ArrayList; -import java.util.Arrays; -import org.eclipse.core.runtime.*; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; -import org.eclipse.equinox.internal.p2.ui.model.ProvElement; -import org.eclipse.jface.viewers.*; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.progress.*; - -/** - * Content provider that retrieves children of a ProvElement. - * - * @since 3.5 - * - */ -public class ProvElementContentProvider implements ITreeContentProvider { - - private Viewer viewer; - private Job fetchJob; - // family is used by test cases - Object fetchFamily = new Object(); - - /** - * - */ - public ProvElementContentProvider() { - // Default constructor - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) - */ - public Object[] getElements(final Object input) { - // Simple deferred fetch handling for table viewers - if (input instanceof IDeferredWorkbenchAdapter && viewer instanceof AbstractTableViewer) { - final Display display = viewer.getControl().getDisplay(); - final Object pending = new PendingUpdateAdapter(); - if (fetchJob != null) - fetchJob.cancel(); - fetchJob = new Job(ProvUIMessages.ProvElementContentProvider_FetchJobTitle) { - protected IStatus run(IProgressMonitor monitor) { - IDeferredWorkbenchAdapter parent = (IDeferredWorkbenchAdapter) input; - final ArrayList children = new ArrayList(); - parent.fetchDeferredChildren(parent, new IElementCollector() { - public void add(Object element, IProgressMonitor mon) { - if (mon.isCanceled()) - return; - children.add(element); - } - - public void add(Object[] elements, IProgressMonitor mon) { - if (mon.isCanceled()) - return; - children.addAll(Arrays.asList(elements)); - } - - public void done() { - // nothing special to do - } - - }, monitor); - display.asyncExec(new Runnable() { - public void run() { - AbstractTableViewer tableViewer = (AbstractTableViewer) viewer; - tableViewer.getControl().setRedraw(false); - tableViewer.remove(pending); - tableViewer.add(children.toArray()); - finishedFetchingElements(input); - tableViewer.getControl().setRedraw(true); - } - }); - return Status.OK_STATUS; - } - - public boolean belongsTo(Object family) { - return family == fetchFamily; - } - - }; - fetchJob.schedule(); - return new Object[] {pending}; - } - Object[] elements = getChildren(input); - finishedFetchingElements(input); - return elements; - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object) - */ - public Object getParent(Object child) { - if (child instanceof ProvElement) { - return ((ProvElement) child).getParent(child); - } - return null; - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object) - */ - public boolean hasChildren(Object element) { - if (element instanceof ProvElement) - return ((ProvElement) element).hasChildren(element); - return false; - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object) - */ - public Object[] getChildren(final Object parent) { - if (parent instanceof ProvElement) { - return ((ProvElement) parent).getChildren(parent); - } - return new Object[0]; - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.IContentProvider#dispose() - */ - public void dispose() { - viewer = null; - if (fetchJob != null) { - fetchJob.cancel(); - fetchJob = null; - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object) - */ - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - this.viewer = viewer; - if (fetchJob != null) { - fetchJob.cancel(); - fetchJob = null; - } - } - - protected void finishedFetchingElements(Object parent) { - // do nothing - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/ProvElementLabelProvider.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/ProvElementLabelProvider.java deleted file mode 100644 index ed4e09179..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/ProvElementLabelProvider.java +++ /dev/null @@ -1,147 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.viewers; - -import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.internal.p2.ui.model.IIUElement; -import org.eclipse.equinox.internal.p2.ui.model.ProvElement; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIImages; -import org.eclipse.equinox.internal.provisional.p2.ui.model.IRepositoryElement; -import org.eclipse.jface.viewers.ITableLabelProvider; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.swt.graphics.Image; -import org.eclipse.ui.ISharedImages; -import org.eclipse.ui.PlatformUI; - -/** - * Label provider for provisioning elements. Some provisioning objects are - * wrapped by ProvElements and some are not. This is the most generic of the - * provisioning label providers. A two-column format for elements is - * supported, with the content of the columns dependent on the type of object. - * - * @since 3.4 - */ -public class ProvElementLabelProvider extends LabelProvider implements ITableLabelProvider { - - public String getText(Object obj) { - if (obj instanceof ProvElement) { - return ((ProvElement) obj).getLabel(obj); - } - if (obj instanceof IProfile) { - return ((IProfile) obj).getProfileId(); - } - if (obj instanceof IInstallableUnit) { - IInstallableUnit iu = (IInstallableUnit) obj; - return iu.getId(); - } - if (obj instanceof IRepository) { - String name = ((IRepository) obj).getName(); - if (name != null && name.length() > 0) { - return name; - } - return URIUtil.toUnencodedString(((IRepository) obj).getLocation()); - } - if (obj instanceof IRepositoryElement) { - String name = ((IRepositoryElement) obj).getName(); - if (name != null && name.length() > 0) { - return name; - } - return URIUtil.toUnencodedString(((IRepositoryElement) obj).getLocation()); - } - if (obj instanceof IArtifactKey) { - IArtifactKey key = (IArtifactKey) obj; - return key.getId() + " [" + key.getClassifier() + "]"; //$NON-NLS-1$//$NON-NLS-2$ - } - if (obj instanceof ProcessingStepDescriptor) { - ProcessingStepDescriptor descriptor = (ProcessingStepDescriptor) obj; - return descriptor.getProcessorId(); - } - if (obj instanceof IRequiredCapability) { - return ((IRequiredCapability) obj).getName(); - } - return obj.toString(); - } - - public Image getImage(Object obj) { - if (obj instanceof ProvElement) { - return ((ProvElement) obj).getImage(obj); - } - if (obj instanceof IProfile) { - return ProvUIImages.getImage(ProvUIImages.IMG_PROFILE); - } - if (obj instanceof IInstallableUnit) { - return ProvUIImages.getImage(ProvUIImages.IMG_IU); - } - if (obj instanceof IArtifactRepository) { - return ProvUIImages.getImage(ProvUIImages.IMG_ARTIFACT_REPOSITORY); - } - if (obj instanceof IMetadataRepository) { - return ProvUIImages.getImage(ProvUIImages.IMG_METADATA_REPOSITORY); - } - if (obj instanceof IArtifactKey) { - return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE); - } - if (obj instanceof IRequiredCapability) { - return ProvUIImages.getImage(ProvUIImages.IMG_IU); - } - return null; - } - - public Image getColumnImage(Object element, int index) { - if (index == 0) { - return getImage(element); - } - return null; - } - - public String getColumnText(Object element, int columnIndex) { - - switch (columnIndex) { - case 0 : - return getText(element); - case 1 : - if (element instanceof IProfile) { - return ((IProfile) element).getProperty(IProfile.PROP_NAME); - } - if (element instanceof IIUElement) { - if (((IIUElement) element).shouldShowVersion()) - return ((IIUElement) element).getIU().getVersion().toString(); - } - IInstallableUnit iu = (IInstallableUnit) ProvUI.getAdapter(element, IInstallableUnit.class); - if (iu != null) { - return iu.getVersion().toString(); - } - if (element instanceof IRepository) { - return URIUtil.toUnencodedString(((IRepository) element).getLocation()); - } - if (element instanceof IRepositoryElement) { - return URIUtil.toUnencodedString(((IRepositoryElement) element).getLocation()); - } - if (element instanceof IArtifactKey) { - IArtifactKey key = (IArtifactKey) element; - return key.getVersion().toString(); - } - if (element instanceof IRequiredCapability) { - return ((IRequiredCapability) element).getRange().getMaximum().toString(); - } - - } - return null; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/RepositoryContentProvider.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/RepositoryContentProvider.java deleted file mode 100644 index 06d1f9c66..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/RepositoryContentProvider.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.viewers; - -import org.eclipse.equinox.internal.p2.ui.viewers.DeferredQueryContentProvider; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor; - -/** - * Content provider for provisioning repositories. The repositories are the - * elements and the repository children are retrieved asynchronously - * using the IDeferredWorkbenchAdapter mechanism. - * - * @since 3.4 - * - */ -public class RepositoryContentProvider extends DeferredQueryContentProvider { - - public Object[] getChildren(final Object parent) { - Object[] children = super.getChildren(parent); - if (children != null) - return children; - if (parent instanceof IArtifactDescriptor) { - return ((IArtifactDescriptor) parent).getProcessingSteps(); - } - return null; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/StructuredViewerProvisioningListener.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/StructuredViewerProvisioningListener.java deleted file mode 100644 index 056660a47..000000000 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/viewers/StructuredViewerProvisioningListener.java +++ /dev/null @@ -1,168 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.ui.viewers; - -import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUIProvisioningListener; -import org.eclipse.equinox.internal.provisional.p2.ui.model.ProfileElement; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.PlatformUI; - -/** - * ProvisioningListener which updates a structured viewer based on - * provisioning changes. Provides default behavior which refreshes particular - * model elements or the entire viewer based on the nature of the change and the - * changes that the client is interested in. Subclasses typically only need - * override when there is additional, specialized behavior required. - * - * @since 3.4 - */ -public class StructuredViewerProvisioningListener extends ProvUIProvisioningListener { - - StructuredViewer viewer; - Display display; - - public StructuredViewerProvisioningListener(StructuredViewer viewer, int eventTypes) { - super(eventTypes); - this.viewer = viewer; - this.display = viewer.getControl().getDisplay(); - } - - /** - * A repository has been added. The default behavior is to - * refresh the viewer. Subclasses may override. May be called - * from a non-UI thread. - * - * @param event the RepositoryEvent describing the details - */ - protected void repositoryAdded(RepositoryEvent event) { - asyncRefresh(); - } - - /** - * A repository has been removed. The default behavior is to - * refresh the viewer. Subclasses may override. May be called - * from a non-UI thread. - * - * @param event the RepositoryEvent describing the details - */ - protected void repositoryRemoved(RepositoryEvent event) { - asyncRefresh(); - } - - /** - * A repository has been discovered. Subclasses may override. May be called - * from a non-UI thread. - * - * @param event the RepositoryEvent describing the details - */ - protected void repositoryDiscovered(RepositoryEvent event) { - // Do nothing for now - } - - /** - * A repository has changed. Subclasses may override. May be called - * from a non-UI thread. - * - * @param event the RepositoryEvent describing the details - */ - protected void repositoryChanged(RepositoryEvent event) { - // Do nothing for now. When this event is actually used in - // the core, we may want to refresh particular elements the way - // we currently refresh a profile element. - } - - /** - * The specified profile has changed. The default behavior is to refresh the viewer - * with a profile element of the matching id. Subclasses may override. May be called - * from a non-UI thread. - * - * @param profileId the id of the profile that changed. - */ - protected void profileChanged(final String profileId) { - display.asyncExec(new Runnable() { - public void run() { - if (isClosing()) - return; - // We want to refresh the affected profile, so we - // construct a profile element on this profile. - ProfileElement element = new ProfileElement(null, profileId); - viewer.refresh(element); - } - }); - } - - /** - * The specified profile has been added. The default behavior is to fully - * refresh the associated viewer. Subclasses may override. May be called - * from a non-UI thread. - * - * @param profileId the id of the profile that has been added. - */ - protected void profileAdded(final String profileId) { - asyncRefresh(); - } - - /** - * The specified profile has been removed. The default behavior is to fully - * refresh the associated viewer. Subclasses may override. May be called - * from a non-UI thread. - * - * @param profileId the id of the profile that has been removed. - */ - protected void profileRemoved(final String profileId) { - asyncRefresh(); - } - - protected void asyncRefresh() { - display.asyncExec(new Runnable() { - public void run() { - if (isClosing()) - return; - refreshViewer(); - } - }); - } - - protected void refreshAll() { - asyncRefresh(); - } - - /** - * Refresh the entire structure of the viewer. Subclasses may - * override to ensure that any caching done in content providers or - * model elements is refreshed before the viewer is refreshed. This will - * always be called from the UI thread. - */ - protected void refreshViewer() { - viewer.refresh(); - } - - /** - * Return whether the viewer is closing or shutting down. - * This method should be used in async execs to ensure that - * the viewer is still alive. - * @return a boolean indicating whether the viewer is closing - */ - protected boolean isClosing() { - IWorkbench workbench = PlatformUI.getWorkbench(); - if (workbench.isClosing()) - return true; - - if (viewer.getControl().isDisposed()) - return true; - - return false; - } -} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/AcceptLicensesWizardPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/AcceptLicensesWizardPage.java new file mode 100644 index 000000000..9ec5fe391 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/AcceptLicensesWizardPage.java @@ -0,0 +1,484 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.ui; + +import org.eclipse.equinox.p2.metadata.ILicense; + +import java.util.*; +import java.util.List; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.metadata.License; +import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.internal.p2.ui.dialogs.ILayoutConstants; +import org.eclipse.equinox.internal.p2.ui.viewers.IUColumnConfig; +import org.eclipse.equinox.p2.engine.IProvisioningPlan; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogSettings; +import org.eclipse.jface.viewers.*; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.osgi.util.NLS; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.SashForm; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.*; + +/** + * AcceptLicensesWizardPage shows a list of the IU's that have + * licenses that have not been approved by the user, and allows the + * user to approve them. + * + * @since 2.0 + * @noextend This class is not intended to be subclassed by clients. + */ +public class AcceptLicensesWizardPage extends WizardPage { + private static final String DIALOG_SETTINGS_SECTION = "LicensessPage"; //$NON-NLS-1$ + private static final String LIST_WEIGHT = "ListSashWeight"; //$NON-NLS-1$ + private static final String LICENSE_WEIGHT = "LicenseSashWeight"; //$NON-NLS-1$ + private static final String NAME_COLUMN_WIDTH = "NameColumnWidth"; //$NON-NLS-1$ + private static final String VERSION_COLUMN_WIDTH = "VersionColumnWidth"; //$NON-NLS-1$ + + class IUWithLicenseParent { + IInstallableUnit iu; + ILicense license; + + IUWithLicenseParent(ILicense license, IInstallableUnit iu) { + this.license = license; + this.iu = iu; + } + } + + class LicenseContentProvider implements ITreeContentProvider { + public Object[] getChildren(Object parentElement) { + if (!(parentElement instanceof ILicense)) + return new Object[0]; + + if (licensesToIUs.containsKey(parentElement)) { + List iusWithLicense = licensesToIUs.get(parentElement); + IInstallableUnit[] ius = iusWithLicense.toArray(new IInstallableUnit[iusWithLicense.size()]); + IUWithLicenseParent[] children = new IUWithLicenseParent[ius.length]; + for (int i = 0; i < ius.length; i++) { + children[i] = new IUWithLicenseParent((ILicense) parentElement, ius[i]); + } + return children; + } + return null; + } + + public Object getParent(Object element) { + if (element instanceof IUWithLicenseParent) { + return ((IUWithLicenseParent) element).license; + } + return null; + } + + public boolean hasChildren(Object element) { + return licensesToIUs.containsKey(element); + } + + public Object[] getElements(Object inputElement) { + return licensesToIUs.keySet().toArray(); + } + + public void dispose() { + // Nothing to do + } + + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + // Nothing to do + } + } + + class LicenseLabelProvider extends LabelProvider { + public Image getImage(Object element) { + return null; + } + + public String getText(Object element) { + if (element instanceof License) { + return getFirstLine(((License) element).getBody()); + } else if (element instanceof IUWithLicenseParent) { + return getIUName(((IUWithLicenseParent) element).iu); + } else if (element instanceof IInstallableUnit) { + return getIUName((IInstallableUnit) element); + } + return ""; //$NON-NLS-1$ + } + + private String getFirstLine(String body) { + int i = body.indexOf('\n'); + int j = body.indexOf('\r'); + if (i > 0) { + if (j > 0) + return body.substring(0, i < j ? i : j); + return body.substring(0, i); + } else if (j > 0) { + return body.substring(0, j); + } + return body; + } + } + + TreeViewer iuViewer; + Text licenseTextBox; + Button acceptButton; + Button declineButton; + SashForm sashForm; + private IInstallableUnit[] originalIUs; + HashMap> licensesToIUs; // License -> IU Name + private LicenseManager manager; + IUColumnConfig nameColumn; + IUColumnConfig versionColumn; + + static String getIUName(IInstallableUnit iu) { + StringBuffer buf = new StringBuffer(); + String name = iu.getProperty(IInstallableUnit.PROP_NAME, null); + if (name != null) + buf.append(name); + else + buf.append(iu.getId()); + buf.append(" "); //$NON-NLS-1$ + buf.append(iu.getVersion().toString()); + return buf.toString(); + } + + /** + * Create a license acceptance page for showing licenses to the user. + * + * @param manager the license manager that should be used to check for already accepted licenses. May be null. + * @param ius the IInstallableUnits for which licenses should be checked + * @param operation the provisioning operation describing what changes are to take place on the profile + */ + public AcceptLicensesWizardPage(LicenseManager manager, IInstallableUnit[] ius, ProfileChangeOperation operation) { + super("AcceptLicenses"); //$NON-NLS-1$ + setTitle(ProvUIMessages.AcceptLicensesWizardPage_Title); + this.manager = manager; + update(ius, operation); + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) + */ + public void createControl(Composite parent) { + initializeDialogUnits(parent); + List ius; + if (licensesToIUs == null || licensesToIUs.size() == 0) { + Label label = new Label(parent, SWT.NONE); + setControl(label); + } else if (licensesToIUs.size() == 1 && (ius = licensesToIUs.values().iterator().next()).size() == 1) { + createLicenseContentSection(parent, ius.get(0)); + } else { + sashForm = new SashForm(parent, SWT.HORIZONTAL); + sashForm.setLayout(new GridLayout()); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + sashForm.setLayoutData(gd); + + createLicenseListSection(sashForm); + createLicenseContentSection(sashForm, null); + sashForm.setWeights(getSashWeights()); + setControl(sashForm); + } + Dialog.applyDialogFont(getControl()); + } + + private void createLicenseListSection(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + GridData gd = new GridData(GridData.FILL_BOTH); + composite.setLayoutData(gd); + + Label label = new Label(composite, SWT.NONE); + label.setText(ProvUIMessages.AcceptLicensesWizardPage_ItemsLabel); + iuViewer = new TreeViewer(composite, SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); + iuViewer.setContentProvider(new LicenseContentProvider()); + iuViewer.setLabelProvider(new LicenseLabelProvider()); + iuViewer.setComparator(new ViewerComparator()); + iuViewer.setInput(licensesToIUs); + + iuViewer.addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + handleSelectionChanged((IStructuredSelection) event.getSelection()); + } + + }); + gd = new GridData(GridData.FILL_BOTH); + gd.widthHint = convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_PRIMARY_COLUMN_WIDTH); + gd.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_HEIGHT); + iuViewer.getControl().setLayoutData(gd); + } + + private void createLicenseAcceptSection(Composite parent, boolean multiple) { + // Buttons for accepting licenses + Composite buttonContainer = new Composite(parent, SWT.NULL); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + buttonContainer.setLayout(new GridLayout()); + buttonContainer.setLayoutData(gd); + + acceptButton = new Button(buttonContainer, SWT.RADIO); + if (multiple) + acceptButton.setText(ProvUIMessages.AcceptLicensesWizardPage_AcceptMultiple); + else + acceptButton.setText(ProvUIMessages.AcceptLicensesWizardPage_AcceptSingle); + + acceptButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + setPageComplete(acceptButton.getSelection()); + } + }); + declineButton = new Button(buttonContainer, SWT.RADIO); + if (multiple) + declineButton.setText(ProvUIMessages.AcceptLicensesWizardPage_RejectMultiple); + else + declineButton.setText(ProvUIMessages.AcceptLicensesWizardPage_RejectSingle); + declineButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + setPageComplete(!declineButton.getSelection()); + } + }); + + acceptButton.setSelection(false); + declineButton.setSelection(true); + } + + private void createLicenseContentSection(Composite parent, IInstallableUnit singleIU) { + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + GridData gd = new GridData(GridData.FILL_BOTH); + composite.setLayoutData(gd); + + Label label = new Label(composite, SWT.NONE); + if (singleIU == null) + label.setText(ProvUIMessages.AcceptLicensesWizardPage_LicenseTextLabel); + else + label.setText(NLS.bind(ProvUIMessages.AcceptLicensesWizardPage_SingleLicenseTextLabel, getIUName(singleIU))); + licenseTextBox = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.WRAP | SWT.READ_ONLY); + licenseTextBox.setBackground(licenseTextBox.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); + initializeDialogUnits(licenseTextBox); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + gd.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_HEIGHT); + gd.widthHint = convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_COLUMN_WIDTH); + licenseTextBox.setLayoutData(gd); + + createLicenseAcceptSection(composite, licensesToIUs.size() > 1); + + if (singleIU != null) { + String licenseBody = ""; //$NON-NLS-1$ + // We've already established before calling this method that it's a single IU with a single license + ILicense[] licenses = singleIU.getLicenses(null); + if (licenses.length > 0 && licenses[0].getBody() != null) { + licenseBody = licenses[0].getBody(); + } + licenseTextBox.setText(licenseBody); + } + setControl(composite); + } + + void handleSelectionChanged(IStructuredSelection selection) { + if (!selection.isEmpty()) { + Object selected = selection.getFirstElement(); + if (selected instanceof License) + licenseTextBox.setText(((License) selected).getBody()); + else if (selected instanceof IUWithLicenseParent) + licenseTextBox.setText(((IUWithLicenseParent) selected).license.getBody()); + } + } + + /** + * The wizard is finishing. Perform any necessary processing. + * + * @return true if the finish can proceed, + * false if it should not. + */ + public boolean performFinish() { + rememberAcceptedLicenses(); + return true; + } + + /** + * Return a boolean indicating whether there are licenses that must be accepted + * by the user. + * + * @return true if there are licenses that must be accepted, and + * false if there are no licenses that must be accepted. + */ + public boolean hasLicensesToAccept() { + return licensesToIUs != null && licensesToIUs.size() > 0; + } + + /** + * Update the current page to show the licenses that must be approved for the + * selected IUs and the provisioning plan + * + * @param theIUs the installable units to be installed for which licenses must be checked + * @param plan the provisioning plan for the install operation + * @deprecated use {@link #update(IInstallableUnit[], ProfileChangeOperation)} + */ + + public void updateForPlan(IInstallableUnit[] theIUs, IProvisioningPlan plan) { + updateLicenses(theIUs, plan); + } + + private void updateLicenses(IInstallableUnit[] theIUs, IProvisioningPlan plan) { + this.originalIUs = theIUs; + if (theIUs == null) + licensesToIUs = new HashMap>(); + else + findUnacceptedLicenses(theIUs, plan); + setDescription(); + setPageComplete(licensesToIUs.size() == 0); + if (getControl() != null) { + Composite parent = getControl().getParent(); + getControl().dispose(); + createControl(parent); + parent.layout(true); + } + } + + /** + * Update the page for the specified IInstallableUnits and operation. + * + * @param theIUs the IInstallableUnits for which licenses should be checked + * @param operation the operation describing the pending profile change + */ + public void update(IInstallableUnit[] theIUs, ProfileChangeOperation operation) { + if (operation != null && operation.hasResolved()) { + int sev = operation.getResolutionResult().getSeverity(); + if (sev != IStatus.ERROR && sev != IStatus.CANCEL) { + updateLicenses(theIUs, operation.getProvisioningPlan()); + } else { + updateLicenses(new IInstallableUnit[0], null); + } + } + } + + private void findUnacceptedLicenses(IInstallableUnit[] selectedIUs, IProvisioningPlan plan) { + IInstallableUnit[] iusToCheck = selectedIUs; + if (plan != null) { + iusToCheck = plan.getAdditions().query(InstallableUnitQuery.ANY, null).toArray(IInstallableUnit.class); + } + + // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=218532 + // Current metadata generation can result with a feature group IU and the feature jar IU + // having the same name and license. We will weed out duplicates if the license and name are both + // the same. + licensesToIUs = new HashMap>();//map of License->ArrayList of IUs with that license + HashMap> namesSeen = new HashMap>(); // map of License->HashSet of names with that license + for (int i = 0; i < iusToCheck.length; i++) { + IInstallableUnit iu = iusToCheck[i]; + ILicense[] licenses = iu.getLicenses(null); + for (int k = 0; k < licenses.length; k++) { + ILicense license = licenses[k]; + if (manager != null && !manager.isAccepted(license)) { + String name = iu.getProperty(IInstallableUnit.PROP_NAME, null); + if (name == null) + name = iu.getId(); + // Have we already found this license? + if (licensesToIUs.containsKey(license)) { + HashSet names = namesSeen.get(license); + if (!names.contains(name)) { + names.add(name); + ((ArrayList) licensesToIUs.get(license)).add(iu); + } + } else { + ArrayList list = new ArrayList(1); + list.add(iu); + licensesToIUs.put(license, list); + HashSet names = new HashSet(1); + names.add(name); + namesSeen.put(license, names); + } + } + } + } + } + + private void rememberAcceptedLicenses() { + if (licensesToIUs == null || manager == null) + return; + for (ILicense license : licensesToIUs.keySet()) + manager.accept(license); + } + + private void setDescription() { + // No licenses but the page is open. Shouldn't happen, but just in case... + if (licensesToIUs == null || licensesToIUs.size() == 0) + setDescription(ProvUIMessages.AcceptLicensesWizardPage_NoLicensesDescription); + // We have licenses. Use a generic message if we think we aren't showing extra + // licenses from required IU's. This check is not entirely accurate, for example + // one root IU could have no license and the next one has two different + // IU's with different licenses. But this cheaply catches the common cases. + else if (licensesToIUs.size() <= originalIUs.length) + setDescription(ProvUIMessages.AcceptLicensesWizardPage_ReviewLicensesDescription); + else { + // Without a doubt we know we are showing extra licenses. + setDescription(ProvUIMessages.AcceptLicensesWizardPage_ReviewExtraLicensesDescription); + } + } + + private String getDialogSettingsName() { + return getWizard().getClass().getName() + "." + DIALOG_SETTINGS_SECTION; //$NON-NLS-1$ + } + + /** + * Save any settings related to the current size and location of the wizard page. + */ + public void saveBoundsRelatedSettings() { + if (iuViewer == null || iuViewer.getTree().isDisposed()) + return; + IDialogSettings settings = ProvUIActivator.getDefault().getDialogSettings(); + IDialogSettings section = settings.getSection(getDialogSettingsName()); + if (section == null) { + section = settings.addNewSection(getDialogSettingsName()); + } + section.put(NAME_COLUMN_WIDTH, iuViewer.getTree().getColumn(0).getWidth()); + section.put(VERSION_COLUMN_WIDTH, iuViewer.getTree().getColumn(1).getWidth()); + + if (sashForm == null || sashForm.isDisposed()) + return; + int[] weights = sashForm.getWeights(); + section.put(LIST_WEIGHT, weights[0]); + section.put(LICENSE_WEIGHT, weights[1]); + } + + private int[] getSashWeights() { + IDialogSettings settings = ProvUIActivator.getDefault().getDialogSettings(); + IDialogSettings section = settings.getSection(getDialogSettingsName()); + if (section != null) { + try { + int[] weights = new int[2]; + if (section.get(LIST_WEIGHT) != null) { + weights[0] = section.getInt(LIST_WEIGHT); + if (section.get(LICENSE_WEIGHT) != null) { + weights[1] = section.getInt(LICENSE_WEIGHT); + return weights; + } + } + } catch (NumberFormatException e) { + // Ignore if there actually was a value that didn't parse. + } + } + return new int[] {55, 45}; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/ICopyable.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/ICopyable.java new file mode 100644 index 000000000..70f2d1080 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/ICopyable.java @@ -0,0 +1,30 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.ui; + +import org.eclipse.swt.widgets.Control; + +/** + * ICopyable defines an interface for elements that provide + * copy support in a UI. The active control in the UI determines + * what should be copied. + * + * @since 2.0 + * @noimplement This interface is not intended to be implemented by clients. + */ +public interface ICopyable { + /** + * Copy text related to the active control to the clipboard. + * + * @param activeControl the active control + */ + public void copyToClipboard(Control activeControl); +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/InstalledSoftwarePage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/InstalledSoftwarePage.java new file mode 100644 index 000000000..d7c68f9e3 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/InstalledSoftwarePage.java @@ -0,0 +1,255 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.equinox.p2.ui; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.actions.*; +import org.eclipse.equinox.internal.p2.ui.dialogs.*; +import org.eclipse.equinox.internal.p2.ui.viewers.IUColumnConfig; +import org.eclipse.equinox.internal.p2.ui.viewers.IUDetailsLabelProvider; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.jface.viewers.*; +import org.eclipse.jface.window.SameShellProvider; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.SWT; +import org.eclipse.swt.dnd.*; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.*; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.about.InstallationPage; +import org.eclipse.ui.menus.AbstractContributionFactory; +import org.eclipse.ui.statushandlers.StatusManager; + +/** + * InstalledSoftwarePage displays a profile's IInstallableUnits in + * an Installation Page. Clients can use this class as the implementation + * class for an installationPages extension. + * + * @see InstallationPage + * + * @noextend This class is not intended to be subclassed by clients. + * @noinstantiate This class is not intended to be instantiated by clients. + * @since 2.0 + * + */ +public class InstalledSoftwarePage extends InstallationPage implements ICopyable { + + private static final int UPDATE_ID = IDialogConstants.CLIENT_ID; + private static final int UNINSTALL_ID = IDialogConstants.CLIENT_ID + 1; + private static final int PROPERTIES_ID = IDialogConstants.CLIENT_ID + 2; + private static final String BUTTON_ACTION = "org.eclipse.equinox.p2.ui.buttonAction"; //$NON-NLS-1$ + + AbstractContributionFactory factory; + Text detailsArea; + InstalledIUGroup installedIUGroup; + String profileId; + Button updateButton, uninstallButton, propertiesButton; + ProvisioningUI ui; + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) + */ + public void createControl(Composite parent) { + initializeDialogUnits(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IProvHelpContextIds.INSTALLED_SOFTWARE); + + ui = ProvisioningUI.getDefaultUI(); + profileId = ui.getProfileId(); + if (profileId == null) { + IStatus status = ui.getPolicy().getNoProfileChosenStatus(); + if (status != null) + ProvUI.reportStatus(status, StatusManager.LOG); + Text text = new Text(parent, SWT.WRAP | SWT.READ_ONLY); + text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + text.setText(ProvUIMessages.InstalledSoftwarePage_NoProfile); + setControl(text); + return; + } + + Composite composite = new Composite(parent, SWT.NONE); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + int width = getDefaultWidth(composite); + gd.widthHint = width; + composite.setLayoutData(gd); + GridLayout layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + + // Table of installed IU's + installedIUGroup = new InstalledIUGroup(ui, composite, JFaceResources.getDialogFont(), profileId, getColumnConfig()); + // we hook selection listeners on the viewer in createPageButtons because we + // rely on the actions we create there getting selection events before we use + // them to update button enablement. + + CopyUtils.activateCopy(this, installedIUGroup.getStructuredViewer().getControl()); + + gd = new GridData(SWT.FILL, SWT.FILL, true, false); + gd.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_DESCRIPTION_HEIGHT); + gd.widthHint = width; + + detailsArea = new Text(composite, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.READ_ONLY | SWT.WRAP); + detailsArea.setBackground(detailsArea.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); + detailsArea.setLayoutData(gd); + + setControl(composite); + } + + /* + * (non-Javadoc) + * @see org.eclipse.ui.about.InstallationPage#createPageButtons(org.eclipse.swt.widgets.Composite) + */ + public void createPageButtons(Composite parent) { + if (profileId == null) + return; + // For the update action, we create a custom selection provider that will interpret no + // selection as checking for updates to everything. + // We also override the run method to close the containing dialog + // if we successfully try to resolve. This is done to ensure that progress + // is shown properly. + // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=236495 + UpdateAction updateAction = new UpdateAction(ui, new ISelectionProvider() { + public void addSelectionChangedListener(ISelectionChangedListener listener) { + installedIUGroup.getStructuredViewer().addSelectionChangedListener(listener); + } + + public ISelection getSelection() { + StructuredViewer viewer = installedIUGroup.getStructuredViewer(); + ISelection selection = viewer.getSelection(); + if (selection.isEmpty()) { + final Object[] all = ((IStructuredContentProvider) viewer.getContentProvider()).getElements(viewer.getInput()); + return new StructuredSelection(all); + } + return selection; + } + + public void removeSelectionChangedListener(ISelectionChangedListener listener) { + installedIUGroup.getStructuredViewer().removeSelectionChangedListener(listener); + } + + public void setSelection(ISelection selection) { + installedIUGroup.getStructuredViewer().setSelection(selection); + } + }, profileId, true) { + public void run() { + super.run(); + if (getReturnCode() == Window.OK) + getPageContainer().closeModalContainers(); + } + }; + updateAction.setSkipSelectionPage(true); + updateButton = createButton(parent, UPDATE_ID, updateAction.getText()); + updateButton.setData(BUTTON_ACTION, updateAction); + // Uninstall action + Action uninstallAction = new UninstallAction(ui, installedIUGroup.getStructuredViewer(), profileId) { + public void run() { + super.run(); + if (getReturnCode() == Window.OK) + getPageContainer().closeModalContainers(); + } + }; + uninstallButton = createButton(parent, UNINSTALL_ID, uninstallAction.getText()); + uninstallButton.setData(BUTTON_ACTION, uninstallAction); + + // Properties action + PropertyDialogAction action = new PropertyDialogAction(new SameShellProvider(getShell()), installedIUGroup.getStructuredViewer()); + propertiesButton = createButton(parent, PROPERTIES_ID, action.getText()); + propertiesButton.setData(BUTTON_ACTION, action); + + // We rely on the actions getting selection events before we do, because + // we rely on the enablement state of the action. So we don't hook + // the selection listener on our table until after actions are created. + installedIUGroup.getStructuredViewer().addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + updateDetailsArea(); + updateEnablement(); + } + + }); + + updateEnablement(); + } + + void updateDetailsArea() { + IInstallableUnit[] selected = installedIUGroup.getSelectedIUs(); + if (selected.length == 1) { + String description = selected[0].getProperty(IInstallableUnit.PROP_DESCRIPTION, null); + if (description != null) { + detailsArea.setText(description); + return; + } + } + detailsArea.setText(""); //$NON-NLS-1$ + } + + void updateEnablement() { + if (updateButton == null || updateButton.isDisposed()) + return; + Button[] buttons = {updateButton, uninstallButton, propertiesButton}; + for (int i = 0; i < buttons.length; i++) { + Action action = (Action) buttons[i].getData(BUTTON_ACTION); + if (action == null || !action.isEnabled()) + buttons[i].setEnabled(false); + else + buttons[i].setEnabled(true); + } + } + + private IUColumnConfig[] getColumnConfig() { + return new IUColumnConfig[] {new IUColumnConfig(ProvUIMessages.ProvUI_NameColumnTitle, IUColumnConfig.COLUMN_NAME, ILayoutConstants.DEFAULT_PRIMARY_COLUMN_WIDTH), new IUColumnConfig(ProvUIMessages.ProvUI_VersionColumnTitle, IUColumnConfig.COLUMN_VERSION, ILayoutConstants.DEFAULT_SMALL_COLUMN_WIDTH), new IUColumnConfig(ProvUIMessages.ProvUI_IdColumnTitle, IUColumnConfig.COLUMN_ID, ILayoutConstants.DEFAULT_COLUMN_WIDTH)}; + } + + private int getDefaultWidth(Control control) { + IUColumnConfig[] columns = getColumnConfig(); + int totalWidth = 0; + for (int i = 0; i < columns.length; i++) { + totalWidth += columns[i].getWidthInPixels(control); + } + return totalWidth + 20; // buffer for surrounding composites + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.p2.ui.ICopyable#copyToClipboard(org.eclipse.swt.widgets.Control) + */ + public void copyToClipboard(Control activeControl) { + Object[] elements = installedIUGroup.getSelectedIUElements(); + if (elements.length == 0) + return; + String text = CopyUtils.getIndentedClipboardText(elements, new IUDetailsLabelProvider(null, getColumnConfig(), null)); + Clipboard clipboard = new Clipboard(PlatformUI.getWorkbench().getDisplay()); + clipboard.setContents(new Object[] {text}, new Transfer[] {TextTransfer.getInstance()}); + clipboard.dispose(); + } + + protected void buttonPressed(int buttonId) { + switch (buttonId) { + case UPDATE_ID : + ((Action) updateButton.getData(BUTTON_ACTION)).run(); + break; + case UNINSTALL_ID : + ((Action) uninstallButton.getData(BUTTON_ACTION)).run(); + break; + case PROPERTIES_ID : + ((Action) propertiesButton.getData(BUTTON_ACTION)).run(); + break; + default : + super.buttonPressed(buttonId); + break; + } + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/LicenseManager.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/LicenseManager.java new file mode 100644 index 000000000..61caae491 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/LicenseManager.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.ui; + +import org.eclipse.equinox.p2.metadata.ILicense; + +import java.io.*; + +/** + * LicenseManager defines a service which records the licenses that have been + * accepted in the course of installing or updating software. It can be used to determine + * whether a particular license should be presented to a user for acceptance, and + * to record the user's decision. + * + * @since 2.0 + */ +public abstract class LicenseManager { + + /** + * Record the acceptance of the specified license. + * + * @param license the license to be accepted + * + * @return true if the license was recorded as accepted, false if + * it was not. + * + */ + public abstract boolean accept(ILicense license); + + /** + * Record the rejection of the specified license. + * + * @param license the license to be rejected + * + * @return true if the license was recorded as rejected, false if + * it was not. + * + */ + public abstract boolean reject(ILicense license); + + /** + * Return a boolean indicating whether a particular license has previously + * been accepted. + * + * @param license the license in question + * + * @return true if the license has previously been accepted, + * false if it has not been accepted before. + * + */ + public abstract boolean isAccepted(ILicense license); + + /** + * Return a boolean indicating whether any licenses have been + * accepted. + * + * @return true if accepted licenses have been recorded, + * false if there have been no licenses accepted. + + */ + public abstract boolean hasAcceptedLicenses(); + + /** + * Write the accepted licenses list to the specified stream. + * @param stream the stream to which licenses should be written + * @throws IOException + */ + public abstract void write(OutputStream stream) throws IOException; + + /** + * Read the accepted licenses list from the specified stream. + * @param stream the stream from which to read the licenses + * @throws IOException + */ + public abstract void read(InputStream stream) throws IOException; + +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/LoadMetadataRepositoryJob.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/LoadMetadataRepositoryJob.java new file mode 100644 index 000000000..7702f5992 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/LoadMetadataRepositoryJob.java @@ -0,0 +1,177 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.p2.ui; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; +import org.eclipse.equinox.internal.p2.ui.ProvUIActivator; +import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.operations.ProvisioningJob; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.ui.statushandlers.StatusManager; + +/** + * A job that loads a set of metadata repositories and caches the loaded repositories. + * This job can be used when repositories are loaded by a client who wishes to + * maintain (and pass along) the in-memory references to the repositories. For example, + * repositories can be loaded in the background and then passed to another + * component, thus ensuring that the repositories remain loaded in memory. + * + * @since 2.0 + * @noextend This class is not intended to be subclassed by clients. + */ +public class LoadMetadataRepositoryJob extends ProvisioningJob { + + /** + * An object representing the family of jobs that load repositories. + */ + public static final Object LOAD_FAMILY = new Object(); + + /** + * The key that should be used to set a property on a repository load job to indicate + * that authentication should be suppressed when loading the repositories. + */ + public static final QualifiedName SUPPRESS_AUTHENTICATION_JOB_MARKER = new QualifiedName(ProvUIActivator.PLUGIN_ID, "SUPPRESS_AUTHENTICATION_REQUESTS"); //$NON-NLS-1$ + + /** + * The key that should be used to set a property on a repository load job to indicate + * that repository events triggered by this job should be suppressed so that clients + * will ignore all events related to the load. + */ + public static final QualifiedName SUPPRESS_REPOSITORY_EVENTS = new QualifiedName(ProvUIActivator.PLUGIN_ID, "SUPRESS_REPOSITORY_EVENTS"); //$NON-NLS-1$ + + /** + * The key that should be used to set a property on a repository load job to indicate + * that load errors should be accumulated into a single status rather than reported + * as they occur. + */ + public static final QualifiedName ACCUMULATE_LOAD_ERRORS = new QualifiedName(ProvUIActivator.PLUGIN_ID, "ACCUMULATE_LOAD_ERRORS"); //$NON-NLS-1$ + + private List repoCache = new ArrayList(); + private RepositoryTracker tracker; + private MultiStatus accumulatedStatus; + private URI[] locations; + private ProvisioningUI ui; + + /** + * Create a job that loads the metadata repositories known by the specified RepositoryTracker. + * @param ui the ProvisioningUI providing the necessary services + */ + public LoadMetadataRepositoryJob(ProvisioningUI ui) { + super(ProvUIMessages.LoadMetadataRepositoryJob_ContactSitesProgress, ui.getSession()); + this.ui = ui; + this.tracker = ui.getRepositoryTracker(); + this.locations = tracker.getKnownRepositories(ui.getSession()); + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.p2.operations.ProvisioningJob#runModal(org.eclipse.core.runtime.IProgressMonitor) + */ + public IStatus runModal(IProgressMonitor monitor) { + if (locations == null || locations.length == 0) + return Status.OK_STATUS; + + // We batch all the time as a way of distinguishing client-initiated repository + // jobs from low level repository manipulation. + ui.signalRepositoryOperationStart(); + try { + doLoad(monitor); + } finally { + ui.signalRepositoryOperationComplete(null, getProperty(SUPPRESS_REPOSITORY_EVENTS) == null); + } + return Status.OK_STATUS; + } + + private IStatus doLoad(IProgressMonitor monitor) { + SubMonitor sub = SubMonitor.convert(monitor, ProvUIMessages.LoadMetadataRepositoryJob_ContactSitesProgress, locations.length * 100); + if (sub.isCanceled()) + return Status.CANCEL_STATUS; + for (int i = 0; i < locations.length; i++) { + if (sub.isCanceled()) + return Status.CANCEL_STATUS; + try { + repoCache.add(ui.getSession().getMetadataRepositoryManager().loadRepository(locations[i], sub.newChild(100))); + } catch (ProvisionException e) { + handleLoadFailure(e, locations[i]); + } + } + return getCurrentStatus(); + } + + private void handleLoadFailure(ProvisionException e, URI location) { + if (shouldAccumulateFailures()) { + // Some ProvisionExceptions include an empty multi status with a message. + // Since empty multi statuses have a severity OK, The platform status handler doesn't handle + // this well. We correct this by recreating a status with error severity + // so that the platform status handler does the right thing. + IStatus status = e.getStatus(); + if (status instanceof MultiStatus && ((MultiStatus) status).getChildren().length == 0) + status = new Status(IStatus.ERROR, status.getPlugin(), status.getCode(), status.getMessage(), status.getException()); + if (accumulatedStatus == null) { + accumulatedStatus = new MultiStatus(ProvUIActivator.PLUGIN_ID, ProvisionException.REPOSITORY_NOT_FOUND, new IStatus[] {status}, ProvUIMessages.LoadMetadataRepositoryJob_SitesMissingError, null); + } else { + accumulatedStatus.add(status); + } + ui.getRepositoryTracker().addNotFound(location); + // Always log the complete exception so the detailed stack trace is in the log. + LogHelper.log(e); + } else { + tracker.reportLoadFailure(location, e); + } + } + + private boolean shouldAccumulateFailures() { + return getProperty(LoadMetadataRepositoryJob.SUPPRESS_AUTHENTICATION_JOB_MARKER) != null; + } + + /** + * Report the accumulated status to the repository tracker. If there has been + * no status accumulated, or if the job has been cancelled, do not report + * anything. + */ + public void reportAccumulatedStatus() { + IStatus status = getCurrentStatus(); + if (status.isOK() || status.getSeverity() == IStatus.CANCEL) + return; + // report status + int flags = StatusManager.LOG; + if (ui.getPolicy().getRepositoriesVisible()) + flags = flags | StatusManager.SHOW; + StatusManager.getManager().handle(status, flags); + // Reset the accumulated status so that next time we only report the newly not found repos. + accumulatedStatus = null; + } + + private IStatus getCurrentStatus() { + if (accumulatedStatus != null) { + // If there is only missing repo to report, use the specific message rather than the generic. + if (accumulatedStatus.getChildren().length == 1) + return accumulatedStatus.getChildren()[0]; + return accumulatedStatus; + } + return Status.OK_STATUS; + } + + /* + * (non-Javadoc) + * @see org.eclipse.core.runtime.jobs.Job#belongsTo(java.lang.Object) + */ + public boolean belongsTo(Object family) { + return family == LOAD_FAMILY; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/Policy.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/Policy.java new file mode 100644 index 000000000..ca6512e62 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/Policy.java @@ -0,0 +1,355 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.ui; + +import org.eclipse.equinox.p2.query.IQuery; + +import org.eclipse.core.runtime.Assert; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.p2.engine.query.UserVisibleRootQuery; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.GroupQuery; +import org.eclipse.equinox.p2.operations.ProfileChangeOperation; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.swt.custom.BusyIndicator; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.statushandlers.StatusManager; + +/** + * The Policy class is used to specify application specific policies that + * should be used in the standard p2 UI class libraries. The default policy + * is acquired using the OSGi service model. + * + * Policy allows clients to specify things such as how repositories + * are manipulated in the standard wizards and dialogs, and how the repositories + * or the installation itself should be traversed when displaying content. + * + * In some cases, the Policy is used only to define a default value that can + * be overridden by user choice and subsequently stored in dialog settings. + * + * Client applications should ensure that their Policy is registered before + * any of the p2 UI objects access the default Policy. + * + * @since 2.0 + */ + +public class Policy { + + /** + * A constant indicating that restart should be forced (without + * confirmation) immediately after completion of a provisioning operation. + * + */ + public static final int RESTART_POLICY_FORCE = 1; + + /** + * A constant indicating that the changes should be applied dynamically + * to the profile (without confirmation) immediately after completion of + * a provisioning operation. + */ + public static final int RESTART_POLICY_FORCE_APPLY = 2; + + /** + * A constant indicating that the user should be prompted to + * restart after completion of a provisioning operation. + */ + public static final int RESTART_POLICY_PROMPT = 3; + + /** + * A constant indicating that, where possible, the user should + * be given the option to restart or dynamically apply the changes + * after completion of a provisioning operation. + */ + public static final int RESTART_POLICY_PROMPT_RESTART_OR_APPLY = 4; + + private IQuery visibleAvailableIUQuery = new GroupQuery(); + private IQuery visibleInstalledIUQuery = new UserVisibleRootQuery(); + private boolean groupByCategory = true; + private boolean allowDrilldown = true; + private boolean repositoriesVisible = true; + private boolean showLatestVersionsOnly = true; + private int restartPolicy = RESTART_POLICY_PROMPT_RESTART_OR_APPLY; + private String repoPrefPageId; + private String repoPrefPageName; + + /** + * Answer a boolean indicating whether the caller should continue to work with the + * specified operation. This method is used when an operation has been resolved, but + * the UI may have further restrictions on continuing with it. + * + * @param operation the operation in question. It must already be resolved. + * @param shell the shell to use for any interaction with the user + * @return true if processing of the operation should continue, false if + * not. It is up to the implementor to report any errors to the user when answering false. + */ + public boolean continueWorkingWithOperation(ProfileChangeOperation operation, Shell shell) { + Assert.isTrue(operation.hasResolved()); + IStatus status = operation.getResolutionResult(); + // user cancelled + if (status.getSeverity() == IStatus.CANCEL) + return false; + + // Special case those statuses where we would never want to open a wizard + if (status.getCode() == ProvisioningSession.STATUS_NOTHING_TO_UPDATE) { + ProvUI.reportStatus(status, StatusManager.BLOCK); + return false; + } + + // there is no plan, so we can't continue. Report any reason found + if (operation.getProvisioningPlan() == null && !status.isOK()) { + StatusManager.getManager().handle(status, StatusManager.LOG | StatusManager.SHOW); + return false; + } + + // If the plan requires install handler support, we want to open the old update UI and + // cancel this operation + if (UpdateManagerCompatibility.requiresInstallHandlerSupport(operation.getProvisioningPlan())) { + PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { + public void run() { + Shell shell = ProvUI.getDefaultParentShell(); + MessageDialog dialog = new MessageDialog(shell, ProvUIMessages.Policy_RequiresUpdateManagerTitle, null, ProvUIMessages.Policy_RequiresUpdateManagerMessage, MessageDialog.WARNING, new String[] {ProvUIMessages.LaunchUpdateManagerButton, IDialogConstants.CANCEL_LABEL}, 0); + if (dialog.open() == 0) + BusyIndicator.showWhile(shell.getDisplay(), new Runnable() { + public void run() { + UpdateManagerCompatibility.openInstaller(); + } + }); + } + }); + return false; + } + // Allow the wizard to open otherwise. + return true; + } + + /** + * Return a status that can be used to describe the failure to + * retrieve a profile. + * @return a status describing a failure to retrieve a profile, + * or null if there is no such status. + */ + public IStatus getNoProfileChosenStatus() { + return null; + } + + /** + * Return a query that can be used to obtain the IInstallableUnits that + * should be presented to the user from the software repositories. + * + * @return the query used to retrieve user visible available IUs + */ + public IQuery getVisibleAvailableIUQuery() { + return visibleAvailableIUQuery; + } + + /** + * Set the query that can be used to obtain the IInstallableUnits that + * should be presented to the user. + * + * @param query the query used to retrieve user visible available IUs + */ + public void setVisibleAvailableIUQuery(IQuery query) { + visibleAvailableIUQuery = query; + } + + /** + * Return a query that can be used to obtain the IInstallableUnits in + * the profile that should be presented to the user. + * + * @return the query used to retrieve user visible installed IUs + */ + public IQuery getVisibleInstalledIUQuery() { + return visibleInstalledIUQuery; + } + + /** + * Set the query that can be used to obtain the IInstallableUnits in + * the profile that should be presented to the user. + * + * @param query the query used to retrieve user visible installed IUs + */ + public void setVisibleInstalledIUQuery(IQuery query) { + visibleInstalledIUQuery = query; + } + + /** + * Get the restart policy that should be used when the provisioning UI + * determines that a restart is required. + * + * @return an integer constant describing the restart policy + * + * @see #RESTART_POLICY_FORCE + * @see #RESTART_POLICY_FORCE_APPLY + * @see #RESTART_POLICY_PROMPT + * @see #RESTART_POLICY_PROMPT_RESTART_OR_APPLY + */ + public int getRestartPolicy() { + return restartPolicy; + } + + /** + * Set the restart policy that should be used when the provisioning UI + * determines that a restart is required. + * + * @param restartPolicy an integer constant describing the restart policy + * + * @see #RESTART_POLICY_FORCE + * @see #RESTART_POLICY_FORCE_APPLY + * @see #RESTART_POLICY_PROMPT + * @see #RESTART_POLICY_PROMPT_RESTART_OR_APPLY + */ + public void setRestartPolicy(int restartPolicy) { + this.restartPolicy = restartPolicy; + } + + /** + * Return a boolean indicating whether the repositories should + * be visible to the user, such that the user can add, remove, and + * otherwise manipulate the software site list. + * + * @return true if repositories are visible to the end + * user, false if they are not. + */ + public boolean getRepositoriesVisible() { + return repositoriesVisible; + } + + /** + * Set a boolean indicating whether the repositories should + * be visible to the user, such that the user can add, remove, and + * otherwise manipulate the software site list. + * + * @param visible true if repositories are visible to the end + * user, false if they are not. + */ + public void setRepositoriesVisible(boolean visible) { + this.repositoriesVisible = visible; + } + + /** + * Return a boolean indicating whether only the latest versions of + * updates and available software should be shown to the user. + * + * @return true if only the latest versions are shown, + * false if all versions should be shown. + */ + public boolean getShowLatestVersionsOnly() { + return showLatestVersionsOnly; + } + + /** + * Set a boolean indicating whether only the latest versions of + * updates and available software should be shown to the user. + * + * @param showLatest true if only the latest versions are shown, + * false if all versions should be shown. + */ + public void setShowLatestVersionsOnly(boolean showLatest) { + this.showLatestVersionsOnly = showLatest; + } + + /** + * Return a boolean indicating whether the user should be allowed drill + * down from a visible update or installed item into the requirements. + * + * @return true if drilldown is allowed, + * false if it is not. + */ + public boolean getShowDrilldownRequirements() { + return allowDrilldown; + } + + /** + * Set a boolean indicating whether the user should be allowed drill + * down from a visible update or installed item into the requirements. + * + * @param drilldown true if drilldown is allowed, + * false if it is not. + */ + public void setShowDrilldownRequirements(boolean drilldown) { + this.allowDrilldown = drilldown; + } + + /** + * Return a boolean indicating whether available software should be + * grouped by category. + * + * @return true if items should be grouped by category, + * false if categories should not be shown. + */ + public boolean getGroupByCategory() { + return groupByCategory; + } + + /** + * Set a boolean indicating whether available software should be + * grouped by category. + * + * @param group true if items should be grouped by category, + * false if categories should not be shown. + */ + public void setGroupByCategory(boolean group) { + this.groupByCategory = group; + } + + /** + * Get the id of the preference page that should be used to link to the + * software sites page. + * + * @return the preference page id, or null if there is no + * preference page id showing the software sites. + */ + public String getRepositoryPreferencePageId() { + return repoPrefPageId; + } + + /** + * Set the id of the preference page that should be used to link to the + * software sites page. + * + * @param id the preference page id, or null if there is no + * preference page id showing the software sites. + */ + + public void setRepositoryPreferencePageId(String id) { + this.repoPrefPageId = id; + } + + /** + * Get the localized name of the preference page that should be displayed in + * links to the software sites page. + * + * @return the preference page name, or null if there is no + * preference page. + */ + public String getRepositoryPreferencePageName() { + return repoPrefPageName; + } + + /** + * Set the localized name of the preference page that should be displayed in + * links to the software sites page. This name is ignored if no id is specified + * for the preference page. + * + * @param name the preference page name, or null if there is no + * preference page. + * + * @see Policy#setRepositoryPreferencePageId(String) + */ + + public void setRepositoryPreferencePageName(String name) { + this.repoPrefPageName = name; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/ProvisioningUI.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/ProvisioningUI.java new file mode 100644 index 000000000..bfc562e1b --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/ProvisioningUI.java @@ -0,0 +1,442 @@ +/******************************************************************************* + * Copyright (c) 2009, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +package org.eclipse.equinox.p2.ui; + +import java.net.URI; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.internal.p2.metadata.TranslationSupport; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.dialogs.*; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.IProfileRegistry; +import org.eclipse.equinox.p2.engine.ProvisioningContext; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; +import org.eclipse.jface.dialogs.TitleAreaDialog; +import org.eclipse.jface.preference.PreferenceDialog; +import org.eclipse.jface.wizard.WizardDialog; +import org.eclipse.swt.widgets.*; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.dialogs.PreferencesUtil; + +/** + * ProvisioningUI defines the provisioning session, UI policy, and related services for a + * provisioning UI. + * + * @since 2.0 + * + */ +public class ProvisioningUI { + + /** + * Return the default ProvisioningUI. + * + * @return the default Provisioning UI. + */ + public static ProvisioningUI getDefaultUI() { + return ProvUIActivator.getDefault().getProvisioningUI(); + } + + private Policy policy; + private ProvisioningSession session; + private String profileId; + private ProvisioningOperationRunner runner; + + /** + * Creates a new instance of the provisioning user interface. + * + * @param session The current provisioning session + * @param profileId The profile that this user interface is operating on + * @param policy The user interface policy settings to use + */ + public ProvisioningUI(ProvisioningSession session, String profileId, Policy policy) { + this.policy = policy; + this.profileId = profileId; + if (profileId == null) + this.profileId = IProfileRegistry.SELF; + this.session = session; + this.runner = new ProvisioningOperationRunner(this); + } + + /** + * Return the UI policy used for this instance of the UI. + * + * @return the UI policy, must not be null + */ + public Policy getPolicy() { + return policy; + } + + /** + * Return the provisioning session that should be used to obtain + * provisioning services. + * + * @return the provisioning session, must not be null + */ + public ProvisioningSession getSession() { + return session; + } + + /** + * Return the license manager that should be used to remember + * accepted user licenses. + * @return the license manager. May be null if licenses are not + * to be remembered. + */ + public LicenseManager getLicenseManager() { + return (LicenseManager) ServiceHelper.getService(ProvUIActivator.getContext(), LicenseManager.class.getName()); + } + + /** + * Return the repository tracker that should be used to add, remove, and track the + * statuses of known repositories. + * + * @return the repository tracker, must not be null + */ + public RepositoryTracker getRepositoryTracker() { + return (RepositoryTracker) ServiceHelper.getService(ProvUIActivator.getContext(), RepositoryTracker.class.getName()); + } + + /** + * Return the profile id that should be assumed for this ProvisioningUI if no other + * id is otherwise specified. Some UI classes are assigned a profile id, while others + * are not. For those classes that are not assigned a current profile id, this id can + * be used to obtain one. + * + * @return a profile id + */ + public String getProfileId() { + return profileId; + } + + /** + * Return an install operation that describes installing the specified IInstallableUnits from the + * provided list of repositories. + * + * @param iusToInstall the IInstallableUnits to be installed + * @param repositories the repositories to use for the operation + * @return the install operation + */ + public InstallOperation getInstallOperation(IInstallableUnit[] iusToInstall, URI[] repositories) { + InstallOperation op = new InstallOperation(getSession(), iusToInstall); + op.setProfileId(getProfileId()); + // op.setRootMarkerKey(getPolicy().getQueryContext().getVisibleInstalledIUProperty()); + op.setProvisioningContext(makeProvisioningContext(repositories)); + return op; + } + + /** + * Return an update operation that describes updating the specified IInstallableUnits from the + * provided list of repositories. + * + * @param iusToUpdate the IInstallableUnits to be updated + * @param repositories the repositories to use for the operation + * @return the update operation + */ + public UpdateOperation getUpdateOperation(IInstallableUnit[] iusToUpdate, URI[] repositories) { + UpdateOperation op = new UpdateOperation(getSession(), iusToUpdate); + op.setProfileId(getProfileId()); + // op.setRootMarkerKey(getPolicy().getQueryContext().getVisibleInstalledIUProperty()); + op.setProvisioningContext(makeProvisioningContext(repositories)); + return op; + } + + /** + * Return an uninstall operation that describes uninstalling the specified IInstallableUnits, using + * the supplied repositories to replace any metadata that must be retrieved for the uninstall. + * + * @param iusToUninstall the IInstallableUnits to be installed + * @param repositories the repositories to use for the operation + * @return the uninstall operation + */ + public UninstallOperation getUninstallOperation(IInstallableUnit[] iusToUninstall, URI[] repositories) { + UninstallOperation op = new UninstallOperation(getSession(), iusToUninstall); + op.setProfileId(getProfileId()); + // op.setRootMarkerKey(getPolicy().getQueryContext().getVisibleInstalledIUProperty()); + op.setProvisioningContext(makeProvisioningContext(repositories)); + return op; + } + + private ProvisioningContext makeProvisioningContext(URI[] repos) { + if (repos != null) { + ProvisioningContext context = new ProvisioningContext(repos); + context.setArtifactRepositories(repos); + return context; + } + // look everywhere + return new ProvisioningContext(); + } + + /** + * Open an install wizard for installing the specified IInstallableUnits + * + * @param shell the shell to parent the wizard + * @param initialSelections the IInstallableUnits that should be selected when the wizard opens. May be null. + * @param operation the operation describing the proposed install. If this operation is not null, then a wizard showing + * only the IInstallableUnits described in the operation will be shown. If the operation is null, then a + * wizard allowing the user to browse the repositories will be opened. + * @param job a repository load job that is loading or has already loaded the repositories. Can be used to pass along + * an in-memory repository reference to the wizard. + * + * @return the wizard return code + */ + public int openInstallWizard(Shell shell, IInstallableUnit[] initialSelections, InstallOperation operation, LoadMetadataRepositoryJob job) { + if (operation == null) { + InstallWizard wizard = new InstallWizard(this, operation, initialSelections, job); + WizardDialog dialog = new ProvisioningWizardDialog(shell, wizard); + dialog.create(); + PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IProvHelpContextIds.INSTALL_WIZARD); + return dialog.open(); + } + PreselectedIUInstallWizard wizard = new PreselectedIUInstallWizard(this, operation, initialSelections, job); + WizardDialog dialog = new ProvisioningWizardDialog(shell, wizard); + dialog.create(); + PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IProvHelpContextIds.INSTALL_WIZARD); + return dialog.open(); + } + + /** + * Open an update wizard for the specified update operation. + * + * @param shell the shell to parent the wizard + * @param skipSelectionsPage true if the selection page should be skipped so that the user is + * viewing the resolution results. false if the update selection page should be shown first. + * @param operation the operation describing the proposed update. Must not be null. + * @param job a repository load job that is loading or has already loaded the repositories. Can be used to pass along + * an in-memory repository reference to the wizard. + * + * @return the wizard return code + */ + public int openUpdateWizard(Shell shell, boolean skipSelectionsPage, UpdateOperation operation, LoadMetadataRepositoryJob job) { + UpdateWizard wizard = new UpdateWizard(this, operation, operation.getSelectedUpdates(), job); + wizard.setSkipSelectionsPage(skipSelectionsPage); + WizardDialog dialog = new ProvisioningWizardDialog(shell, wizard); + dialog.create(); + PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IProvHelpContextIds.UPDATE_WIZARD); + return dialog.open(); + } + + /** + * Open an uninstall wizard for the specified uninstall operation. + * + * @param shell the shell to parent the wizard + * @param initialSelections the IInstallableUnits that should be selected when the wizard opens. May be null. + * @param operation the operation describing the proposed uninstall. Must not be null. + * @param job a repository load job that is loading or has already loaded the repositories. Can be used to pass along + * an in-memory repository reference to the wizard. + * + * @return the wizard return code + */ + public int openUninstallWizard(Shell shell, IInstallableUnit[] initialSelections, UninstallOperation operation, LoadMetadataRepositoryJob job) { + UninstallWizard wizard = new UninstallWizard(this, operation, initialSelections, job); + WizardDialog dialog = new ProvisioningWizardDialog(shell, wizard); + dialog.create(); + PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IProvHelpContextIds.UNINSTALL_WIZARD); + return dialog.open(); + } + + /** + * Open a UI that allows the user to manipulate the repositories. + * @param shell the shell that should parent the UI + */ + public void manipulateRepositories(Shell shell) { + if (policy.getRepositoryPreferencePageId() != null) { + PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(shell, policy.getRepositoryPreferencePageId(), null, null); + dialog.open(); + } else { + TitleAreaDialog dialog = new TitleAreaDialog(shell) { + RepositoryManipulationPage page; + + protected Control createDialogArea(Composite parent) { + page = new RepositoryManipulationPage(); + page.setProvisioningUI(ProvisioningUI.this); + page.init(PlatformUI.getWorkbench()); + page.createControl(parent); + this.setTitle(ProvUIMessages.RepositoryManipulationPage_Title); + this.setMessage(ProvUIMessages.RepositoryManipulationPage_Description); + return page.getControl(); + } + + protected boolean isResizable() { + return true; + } + + protected void okPressed() { + if (page.performOk()) + super.okPressed(); + } + + protected void cancelPressed() { + if (page.performCancel()) + super.cancelPressed(); + } + }; + dialog.open(); + } + } + + /** + * Return a shell appropriate for parenting a dialog. + * @return a shell that can be used to parent a dialog. + */ + public Shell getDefaultParentShell() { + return ProvUI.getDefaultParentShell(); + } + + /** + * Schedule a job to execute the supplied ProvisioningOperation. + * + * @param job The operation to execute + * @param errorStyle the flags passed to the StatusManager for error reporting + */ + public void schedule(final ProvisioningJob job, final int errorStyle) { + runner.schedule(job, errorStyle); + } + + /** + * Manage the supplied job as a provisioning operation. This will allow + * the ProvisioningUI to be aware that a provisioning job is running, as well + * as manage the restart behavior for the job. + * + * @param job the job to be managed + * @param jobRestartPolicy an integer constant specifying whether the + * supplied job should cause a restart of the system. The UI Policy's + * restart policy is used in conjunction with this constant to determine + * what actually occurs when a job completes. + * + * @see ProvisioningJob#RESTART_NONE + * @see ProvisioningJob#RESTART_ONLY + * @see ProvisioningJob#RESTART_OR_APPLY + */ + public void manageJob(Job job, final int jobRestartPolicy) { + runner.manageJob(job, jobRestartPolicy); + } + + /** + * Return a boolean indicating whether the receiver has scheduled any operations + * for the profile under management. + * + * @return true if other provisioning operations have been scheduled, + * false if there are no operations scheduled. + */ + public boolean hasScheduledOperations() { + return getSession().hasScheduledOperationsFor(profileId); + } + + /** + * This method is for automated testing only. + * @return the provisioning operation that can suppress restart for automated testing. + * @noreference This method is not intended to be referenced by clients. + */ + public ProvisioningOperationRunner getOperationRunner() { + return runner; + } + + /** + * Signal that a repository operation is about to begin. This allows clients to ignore intermediate + * events until the operation is completed. Callers are responsible for ensuring that + * a corresponding operation ending event is signaled. + */ + public void signalRepositoryOperationStart() { + getSession().getProvisioningEventBus().publishEvent(new RepositoryOperationBeginningEvent(this)); + } + + /** + * Signal that a repository operation has completed. + * + * @param event a {@link RepositoryEvent} that describes the overall operation. May be null, which + * indicates that there was no single event that can describe the operation. + * @param update true if the event should be reflected in the UI, false if it should be ignored. + */ + public void signalRepositoryOperationComplete(RepositoryEvent event, boolean update) { + getSession().getProvisioningEventBus().publishEvent(new RepositoryOperationEndingEvent(this, update, event)); + } + + /** + * Load the specified metadata repository, signaling a repository operation start event + * before loading, and a repository operation complete event after loading. + * + * @param location the location of the repository + * @param notify true if the UI should be updated as a result of the load, false if it should not + * @param monitor the progress monitor to be used + * @return the repository + * @throws ProvisionException if the repository could not be loaded + */ + + public IMetadataRepository loadMetadataRepository(URI location, boolean notify, IProgressMonitor monitor) throws ProvisionException { + IMetadataRepository repo = null; + try { + signalRepositoryOperationStart(); + repo = session.getMetadataRepositoryManager().loadRepository(location, monitor); + // If there is no user nickname assigned to this repo but there is a provider name, then set the nickname. + // This will keep the name in the manager even when the repo is not loaded + String name = session.getMetadataRepositoryManager().getRepositoryProperty(location, IRepository.PROP_NICKNAME); + if (name == null || name.length() == 0) { + name = repo.getName(); + if (name != null && name.length() > 0) + session.getMetadataRepositoryManager().setRepositoryProperty(location, IRepository.PROP_NICKNAME, name); + } + } catch (ProvisionException e) { + getRepositoryTracker().reportLoadFailure(location, e); + } finally { + // We have no idea how many repos may have been touched as a result of loading this one, + // so in theory we would not use a specific repository event to represent it. + // In practice this can cause problems in the UI like losing selections in the repo combo. + // So we signal an add event. + signalRepositoryOperationComplete(new RepositoryEvent(location, IRepository.TYPE_METADATA, RepositoryEvent.ADDED, true), notify); + } + return repo; + } + + /** + * Load the specified artifact repository, signaling a repository operation start event + * before loading, and a repository operation complete event after loading. + * + * @param location the location of the repository + * @param update true if the UI should be updated as a result of the load, false if it should not + * @param monitor the progress monitor to be used + * @return the repository + * @throws ProvisionException if the repository could not be loaded + */ + public IArtifactRepository loadArtifactRepository(URI location, boolean update, IProgressMonitor monitor) throws ProvisionException { + IArtifactRepository repo; + signalRepositoryOperationStart(); + try { + repo = session.getArtifactRepositoryManager().loadRepository(location, monitor); + + // If there is no user nickname assigned to this repo but there is a provider name, then set the nickname. + // This will keep the name in the manager even when the repo is not loaded + String name = session.getArtifactRepositoryManager().getRepositoryProperty(location, IRepository.PROP_NICKNAME); + if (name == null) { + name = session.getArtifactRepositoryManager().getRepositoryProperty(location, IRepository.PROP_NAME); + if (name != null) + session.getArtifactRepositoryManager().setRepositoryProperty(location, IRepository.PROP_NICKNAME, name); + } + } finally { + // We have no idea how many repos may have been touched as a result of loading this one, + // so we do not use a specific repository event to represent it. + signalRepositoryOperationComplete(null, update); + } + return repo; + } + + public TranslationSupport getTranslationSupport() { + // TODO Temporary fix to enable build. + return TranslationSupport.getInstance(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/RepositoryManipulationPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/RepositoryManipulationPage.java new file mode 100644 index 000000000..75a891de1 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/RepositoryManipulationPage.java @@ -0,0 +1,868 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.ui; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.lang.reflect.InvocationTargetException; +import java.net.URI; +import java.util.ArrayList; +import java.util.Hashtable; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.dialogs.*; +import org.eclipse.equinox.internal.p2.ui.model.*; +import org.eclipse.equinox.internal.p2.ui.viewers.*; +import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.jface.dialogs.*; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.jface.viewers.*; +import org.eclipse.jface.window.Window; +import org.eclipse.osgi.util.NLS; +import org.eclipse.swt.SWT; +import org.eclipse.swt.accessibility.AccessibleAdapter; +import org.eclipse.swt.accessibility.AccessibleEvent; +import org.eclipse.swt.custom.BusyIndicator; +import org.eclipse.swt.dnd.*; +import org.eclipse.swt.events.*; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.*; +import org.eclipse.ui.*; +import org.eclipse.ui.dialogs.PatternFilter; +import org.eclipse.ui.progress.IElementCollector; +import org.eclipse.ui.progress.WorkbenchJob; +import org.eclipse.ui.statushandlers.StatusManager; + +/** + * Page that allows users to update, add, remove, import, and + * export repositories. This page can be hosted inside a preference + * dialog or inside its own dialog. + * + * When hosting this page inside a non-preference dialog, some of the + * dialog methods will likely have to call page methods. The following + * snippet shows how to host this page inside a TitleAreaDialog. + *
    + *		TitleAreaDialog dialog = new TitleAreaDialog(shell) {
    + *
    + *			RepositoryManipulationPage page;
    + *
    + *			protected Control createDialogArea(Composite parent) {
    + *				page = new RepositoryManipulationPage();
    + *              page.setProvisioningUI(ProvisioningUI.getDefaultUI());
    + *				page.createControl(parent);
    + *				this.setTitle("Software Sites");
    + *				this.setMessage("The enabled sites will be searched for software.  Disabled sites are ignored.");
    + *				return page.getControl();
    + *			}
    + *
    + *			protected void okPressed() {
    + *				if (page.performOk())
    + *					super.okPressed();
    + *			}
    + *
    + *			protected void cancelPressed() {
    + *				if (page.performCancel())
    + *					super.cancelPressed();
    + *			}
    + *		};
    + *		dialog.open();
    + * 
    + * + * @noextend This class is not intended to be subclassed by clients. + * + * @since 2.0 + */ +public class RepositoryManipulationPage extends PreferencePage implements IWorkbenchPreferencePage, ICopyable { + final static String DEFAULT_FILTER_TEXT = ProvUIMessages.RepositoryManipulationPage_DefaultFilterString; + private final static int FILTER_DELAY = 200; + + StructuredViewerProvisioningListener listener; + TableViewer repositoryViewer; + Table table; + ProvisioningUI ui; + Policy policy; + Display display; + boolean changed = false; + MetadataRepositoryElementComparator comparator; + RepositoryDetailsLabelProvider labelProvider; + RepositoryTracker tracker; + RepositoryTracker localCacheRepoManipulator; + CachedMetadataRepositories input; + Text pattern, details; + PatternFilter filter; + WorkbenchJob filterJob; + Button addButton, removeButton, editButton, refreshButton, disableButton, exportButton; + + class CachedMetadataRepositories extends MetadataRepositories { + Hashtable cachedElements; + + CachedMetadataRepositories() { + super(ui); + setIncludeDisabledRepositories(getPolicy().getRepositoriesVisible()); + } + + public int getQueryType() { + return QueryProvider.METADATA_REPOS; + } + + public void fetchDeferredChildren(Object o, IElementCollector collector, IProgressMonitor monitor) { + if (cachedElements == null || cachedElements.isEmpty()) { + super.fetchDeferredChildren(o, collector, monitor); + // now we know we have children + Object[] children = getChildren(o); + cachedElements = new Hashtable(children.length); + for (int i = 0; i < children.length; i++) { + if (children[i] instanceof MetadataRepositoryElement) + cachedElements.put(URIUtil.toUnencodedString(((MetadataRepositoryElement) children[i]).getLocation()), children[i]); + } + return; + } + // Use the cache rather than fetching children + collector.add(cachedElements.values().toArray(), monitor); + } + + } + + class MetadataRepositoryPatternFilter extends PatternFilter { + MetadataRepositoryPatternFilter() { + setIncludeLeadingWildcard(true); + } + + public boolean isElementVisible(Viewer viewer, Object element) { + if (element instanceof MetadataRepositoryElement) { + return wordMatches(labelProvider.getColumnText(element, RepositoryDetailsLabelProvider.COL_NAME) + " " + labelProvider.getColumnText(element, RepositoryDetailsLabelProvider.COL_LOCATION)); //$NON-NLS-1$ + } + return false; + } + } + + /** + * Create a repository manipulation page that will display the repositories + * available to the user. + */ + public RepositoryManipulationPage() { + this.setProvisioningUI(ProvisioningUI.getDefaultUI()); + } + + /** + * Set the provisioning UI that provides the session, policy, and other + * services for the UI. This method must be called before the contents are + * created or it will have no effect. + * + * @param ui the provisioning UI to use for this page. + */ + public void setProvisioningUI(ProvisioningUI ui) { + this.ui = ui; + this.policy = ui.getPolicy(); + tracker = ui.getRepositoryTracker(); + } + + protected Control createContents(Composite parent) { + display = parent.getDisplay(); + // The help refers to the full-blown dialog. No help if it's read only. + if (policy.getRepositoriesVisible()) + PlatformUI.getWorkbench().getHelpSystem().setHelp(parent.getShell(), IProvHelpContextIds.REPOSITORY_MANIPULATION_DIALOG); + + Composite composite = new Composite(parent, SWT.NONE); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + composite.setLayoutData(gd); + + GridLayout layout = new GridLayout(); + layout.numColumns = policy.getRepositoriesVisible() ? 2 : 1; + layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + composite.setLayout(layout); + + // Filter box + pattern = new Text(composite, SWT.SINGLE | SWT.BORDER | SWT.SEARCH | SWT.CANCEL); + pattern.getAccessible().addAccessibleListener(new AccessibleAdapter() { + public void getName(AccessibleEvent e) { + e.result = DEFAULT_FILTER_TEXT; + } + }); + pattern.setText(DEFAULT_FILTER_TEXT); + pattern.selectAll(); + pattern.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + applyFilter(); + } + }); + + pattern.addKeyListener(new KeyAdapter() { + public void keyPressed(KeyEvent e) { + if (e.keyCode == SWT.ARROW_DOWN) { + if (table.getItemCount() > 0) { + table.setFocus(); + } else if (e.character == SWT.CR) { + return; + } + } + } + }); + + pattern.addFocusListener(new FocusAdapter() { + public void focusGained(FocusEvent e) { + display.asyncExec(new Runnable() { + public void run() { + if (!pattern.isDisposed()) { + if (DEFAULT_FILTER_TEXT.equals(pattern.getText().trim())) { + pattern.selectAll(); + } + } + } + }); + } + }); + gd = new GridData(SWT.FILL, SWT.FILL, true, false); + pattern.setLayoutData(gd); + + // spacer to fill other column + if (policy.getRepositoriesVisible()) + new Label(composite, SWT.NONE); + + // Table of available repositories + repositoryViewer = new TableViewer(composite, SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); + table = repositoryViewer.getTable(); + + // Key listener for delete + table.addKeyListener(new KeyAdapter() { + public void keyPressed(KeyEvent e) { + if (e.keyCode == SWT.DEL) { + removeRepositories(); + } + } + }); + setTableColumns(); + CopyUtils.activateCopy(this, table); + + repositoryViewer.setComparer(new ProvElementComparer()); + comparator = new MetadataRepositoryElementComparator(RepositoryDetailsLabelProvider.COL_NAME); + repositoryViewer.setComparator(comparator); + filter = new MetadataRepositoryPatternFilter(); + repositoryViewer.setFilters(new ViewerFilter[] {filter}); + // We don't need a deferred content provider because we are caching local results before + // actually querying + repositoryViewer.setContentProvider(new ProvElementContentProvider()); + labelProvider = new RepositoryDetailsLabelProvider(); + repositoryViewer.setLabelProvider(labelProvider); + + // Edit the nickname + repositoryViewer.setCellModifier(new ICellModifier() { + public boolean canModify(Object element, String property) { + return element instanceof MetadataRepositoryElement; + } + + public Object getValue(Object element, String property) { + return ((MetadataRepositoryElement) element).getName(); + } + + public void modify(Object element, String property, Object value) { + if (value != null && value.toString().length() >= 0) { + MetadataRepositoryElement repo; + if (element instanceof Item) { + repo = (MetadataRepositoryElement) ((Item) element).getData(); + } else if (element instanceof MetadataRepositoryElement) { + repo = (MetadataRepositoryElement) element; + } else { + return; + } + if (!value.toString().equals(repo.getName())) { + changed = true; + repo.setNickname(value.toString()); + if (comparator.getSortKey() == RepositoryDetailsLabelProvider.COL_NAME) + repositoryViewer.refresh(true); + else + repositoryViewer.update(repo, null); + } + } + } + + }); + repositoryViewer.setColumnProperties(new String[] {"nickname"}); //$NON-NLS-1$ + repositoryViewer.setCellEditors(new CellEditor[] {new TextCellEditor(repositoryViewer.getTable())}); + + repositoryViewer.addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + if (policy.getRepositoriesVisible()) + validateButtons(); + setDetails(); + } + }); + + // Input last + repositoryViewer.setInput(getInput()); + + GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); + data.widthHint = convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_WIDTH); + data.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_HEIGHT); + table.setLayoutData(data); + + // Drop targets and vertical buttons only if repository manipulation is provided. + if (policy.getRepositoriesVisible()) { + DropTarget target = new DropTarget(table, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK); + target.setTransfer(new Transfer[] {URLTransfer.getInstance(), FileTransfer.getInstance()}); + target.addDropListener(new RepositoryManipulatorDropTarget(ui, table)); + + // Vertical buttons + Composite verticalButtonBar = createVerticalButtonBar(composite); + data = new GridData(SWT.FILL, SWT.FILL, false, false); + data.verticalAlignment = SWT.TOP; + data.verticalIndent = 0; + verticalButtonBar.setLayoutData(data); + listener = getViewerProvisioningListener(); + + ProvUI.addProvisioningListener(listener); + composite.addDisposeListener(new DisposeListener() { + public void widgetDisposed(DisposeEvent event) { + ProvUI.removeProvisioningListener(listener); + } + }); + + validateButtons(); + } + + // Details area + details = new Text(composite, SWT.READ_ONLY | SWT.WRAP); + data = new GridData(SWT.FILL, SWT.FILL, true, false); + data.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_SITEDETAILS_HEIGHT); + + details.setLayoutData(data); + + Dialog.applyDialogFont(composite); + return composite; + } + + private Button createVerticalButton(Composite parent, String label, boolean defaultButton) { + Button button = new Button(parent, SWT.PUSH); + button.setText(label); + + GridData data = setVerticalButtonLayoutData(button); + data.horizontalAlignment = GridData.FILL; + + button.setToolTipText(label); + if (defaultButton) { + Shell shell = parent.getShell(); + if (shell != null) { + shell.setDefaultButton(button); + } + } + return button; + } + + private GridData setVerticalButtonLayoutData(Button button) { + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); + Point minSize = button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); + data.widthHint = Math.max(widthHint, minSize.x); + button.setLayoutData(data); + return data; + } + + private void setTableColumns() { + table.setHeaderVisible(true); + String[] columnHeaders; + if (policy.getRepositoriesVisible()) + columnHeaders = new String[] {ProvUIMessages.RepositoryManipulationPage_NameColumnTitle, ProvUIMessages.RepositoryManipulationPage_LocationColumnTitle, ProvUIMessages.RepositoryManipulationPage_EnabledColumnTitle}; + else + columnHeaders = new String[] {ProvUIMessages.RepositoryManipulationPage_NameColumnTitle, ProvUIMessages.RepositoryManipulationPage_LocationColumnTitle}; + for (int i = 0; i < columnHeaders.length; i++) { + TableColumn tc = new TableColumn(table, SWT.NONE, i); + tc.setResizable(true); + tc.setText(columnHeaders[i]); + if (i == RepositoryDetailsLabelProvider.COL_ENABLEMENT) { + tc.setWidth(convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_SMALL_COLUMN_WIDTH)); + tc.setAlignment(SWT.CENTER); + } else if (i == RepositoryDetailsLabelProvider.COL_NAME) { + tc.setWidth(convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_COLUMN_WIDTH)); + } else { + tc.setWidth(convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_PRIMARY_COLUMN_WIDTH)); + } + tc.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + columnSelected((TableColumn) e.widget); + } + + public void widgetSelected(SelectionEvent e) { + columnSelected((TableColumn) e.widget); + } + + }); + // First column only + if (i == 0) { + table.setSortColumn(tc); + table.setSortDirection(SWT.UP); + } + } + } + + private Composite createVerticalButtonBar(Composite parent) { + // Create composite. + Composite composite = new Composite(parent, SWT.NONE); + initializeDialogUnits(composite); + + // create a layout with spacing and margins appropriate for the font + // size. + GridLayout layout = new GridLayout(); + layout.numColumns = 1; + layout.marginWidth = 5; + layout.marginHeight = 0; + layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + composite.setLayout(layout); + + createVerticalButtons(composite); + return composite; + } + + private void createVerticalButtons(Composite parent) { + addButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Add, false); + addButton.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event event) { + addRepository(); + } + }); + + editButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Edit, false); + editButton.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event event) { + changeRepositoryProperties(); + } + }); + + removeButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Remove, false); + removeButton.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event event) { + removeRepositories(); + } + }); + + refreshButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_RefreshConnection, false); + refreshButton.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event event) { + refreshRepository(); + } + }); + + disableButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_DisableButton, false); + disableButton.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event event) { + toggleRepositoryEnablement(); + } + }); + + Button button = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Import, false); + button.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event event) { + importRepositories(); + } + }); + + exportButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Export, false); + exportButton.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event event) { + exportRepositories(); + } + }); + } + + CachedMetadataRepositories getInput() { + if (input == null) + input = new CachedMetadataRepositories(); + return input; + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.preference.PreferencePage#performOk() + */ + public boolean performOk() { + if (changed) + ElementUtils.updateRepositoryUsingElements(getElements(), getShell()); + return super.performOk(); + } + + private StructuredViewerProvisioningListener getViewerProvisioningListener() { + return new StructuredViewerProvisioningListener(repositoryViewer, ProvUIProvisioningListener.PROV_EVENT_METADATA_REPOSITORY) { + protected void repositoryDiscovered(RepositoryEvent e) { + RepositoryManipulationPage.this.safeRefresh(null); + } + + protected void repositoryChanged(RepositoryEvent e) { + RepositoryManipulationPage.this.safeRefresh(null); + } + }; + } + + MetadataRepositoryElement[] getElements() { + return getInput().cachedElements.values().toArray(new MetadataRepositoryElement[getInput().cachedElements.size()]); + } + + MetadataRepositoryElement[] getSelectedElements() { + Object[] items = ((IStructuredSelection) repositoryViewer.getSelection()).toArray(); + ArrayList list = new ArrayList(items.length); + for (int i = 0; i < items.length; i++) { + if (items[i] instanceof MetadataRepositoryElement) + list.add(items[i]); + } + return list.toArray(new MetadataRepositoryElement[list.size()]); + } + + void validateButtons() { + MetadataRepositoryElement[] elements = getSelectedElements(); + exportButton.setEnabled(elements.length > 0); + removeButton.setEnabled(elements.length > 0); + editButton.setEnabled(elements.length == 1); + refreshButton.setEnabled(elements.length == 1); + if (elements.length >= 1) { + if (toggleMeansDisable(elements)) + disableButton.setText(ProvUIMessages.RepositoryManipulationPage_DisableButton); + else + disableButton.setText(ProvUIMessages.RepositoryManipulationPage_EnableButton); + disableButton.setEnabled(true); + } else { + disableButton.setText(ProvUIMessages.RepositoryManipulationPage_EnableButton); + disableButton.setEnabled(false); + } + } + + void addRepository() { + AddRepositoryDialog dialog = new AddRepositoryDialog(getShell(), ui) { + protected RepositoryTracker getRepositoryTracker() { + return RepositoryManipulationPage.this.getLocalCacheRepoTracker(); + } + }; + dialog.setTitle(ProvUIMessages.ColocatedRepositoryManipulator_AddSiteOperationLabel); + dialog.open(); + } + + void refreshRepository() { + final MetadataRepositoryElement[] selected = getSelectedElements(); + final ProvisionException[] fail = new ProvisionException[1]; + final boolean[] remove = new boolean[1]; + remove[0] = false; + if (selected.length != 1) + return; + final URI location = selected[0].getLocation(); + ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell()); + try { + dialog.run(true, true, new IRunnableWithProgress() { + public void run(IProgressMonitor monitor) { + monitor.beginTask(NLS.bind(ProvUIMessages.RepositoryManipulationPage_ContactingSiteMessage, location), 100); + try { + tracker.clearRepositoryNotFound(location); + // If the manager doesn't know this repo, refreshing it will not work. + // We temporarily add it, but we must remove it in case the user cancels out of this page. + if (!includesRepo(tracker.getKnownRepositories(ui.getSession()), location)) { + // Start a batch operation so we can swallow events + remove[0] = true; + ui.signalRepositoryOperationStart(); + tracker.addRepository(location, selected[0].getName(), ui.getSession()); + } + tracker.refreshRepositories(new URI[] {location}, ui.getSession(), monitor); + } catch (OperationCanceledException e) { + // Catch canceled login attempts + fail[0] = new ProvisionException(new Status(IStatus.CANCEL, ProvUIActivator.PLUGIN_ID, ProvUIMessages.RepositoryManipulationPage_RefreshOperationCanceled, e)); + } finally { + // Check if the monitor was canceled + if (fail[0] == null && monitor.isCanceled()) + fail[0] = new ProvisionException(new Status(IStatus.CANCEL, ProvUIActivator.PLUGIN_ID, ProvUIMessages.RepositoryManipulationPage_RefreshOperationCanceled)); + // If we temporarily added a repo so we could read it, remove it. + if (remove[0]) { + tracker.removeRepositories(new URI[] {location}, ui.getSession()); + // stop swallowing events + ui.signalRepositoryOperationComplete(null, false); + } + } + } + }); + } catch (InvocationTargetException e) { + // nothing to report + } catch (InterruptedException e) { + // nothing to report + } + if (fail[0] != null) { + // If the repo was not found, tell ProvUI that we will be reporting it. + // We are going to report problems directly to the status manager because we + // do not want the automatic repo location editing to kick in. + if (fail[0].getStatus().getCode() == ProvisionException.REPOSITORY_NOT_FOUND) { + tracker.addNotFound(location); + } + if (!fail[0].getStatus().matches(IStatus.CANCEL)) { + // An error is only shown if the dialog was not canceled + ProvUI.handleException(fail[0], null, StatusManager.SHOW); + } + } else { + // Confirm that it was successful + MessageDialog.openInformation(getShell(), ProvUIMessages.RepositoryManipulationPage_TestConnectionTitle, NLS.bind(ProvUIMessages.RepositoryManipulationPage_TestConnectionSuccess, URIUtil.toUnencodedString(location))); + } + repositoryViewer.update(selected[0], null); + setDetails(); + } + + boolean includesRepo(URI[] repos, URI repo) { + for (int i = 0; i < repos.length; i++) + if (repos[i].equals(repo)) + return true; + return false; + } + + void toggleRepositoryEnablement() { + MetadataRepositoryElement[] selected = getSelectedElements(); + if (selected.length >= 1) { + boolean enableSites = !toggleMeansDisable(selected); + for (int i = 0; i < selected.length; i++) { + selected[i].setEnabled(enableSites); + input.cachedElements.put(URIUtil.toUnencodedString(selected[i].getLocation()), selected[i]); + } + if (comparator.getSortKey() == RepositoryDetailsLabelProvider.COL_ENABLEMENT) + repositoryViewer.refresh(true); + else + for (int i = 0; i < selected.length; i++) + repositoryViewer.update(selected[i], null); + changed = true; + } + validateButtons(); + } + + void importRepositories() { + BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { + public void run() { + MetadataRepositoryElement[] imported = UpdateManagerCompatibility.importSites(getShell()); + if (imported.length > 0) { + Hashtable repos = getInput().cachedElements; + changed = true; + for (int i = 0; i < imported.length; i++) + repos.put(URIUtil.toUnencodedString(imported[i].getLocation()), imported[i]); + safeRefresh(null); + } + } + }); + } + + void exportRepositories() { + BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { + public void run() { + MetadataRepositoryElement[] elements = getSelectedElements(); + if (elements.length == 0) + elements = getElements(); + UpdateManagerCompatibility.exportSites(getShell(), elements); + } + }); + } + + void changeRepositoryProperties() { + final MetadataRepositoryElement[] selected = getSelectedElements(); + if (selected.length != 1) + return; + RepositoryNameAndLocationDialog dialog = new RepositoryNameAndLocationDialog(getShell(), ui) { + protected String getInitialLocationText() { + return URIUtil.toUnencodedString(selected[0].getLocation()); + } + + protected String getInitialNameText() { + return selected[0].getName(); + } + + }; + int retCode = dialog.open(); + if (retCode == Window.OK) { + selected[0].setNickname(dialog.getName()); + selected[0].setLocation(dialog.getLocation()); + changed = true; + repositoryViewer.update(selected[0], null); + setDetails(); + } + } + + void columnSelected(TableColumn tc) { + TableColumn[] cols = table.getColumns(); + for (int i = 0; i < cols.length; i++) { + if (cols[i] == tc) { + if (i != comparator.getSortKey()) { + comparator.setSortKey(i); + table.setSortColumn(tc); + comparator.sortAscending(); + table.setSortDirection(SWT.UP); + } else { + if (comparator.isAscending()) { + table.setSortDirection(SWT.DOWN); + comparator.sortDescending(); + } else { + table.setSortDirection(SWT.UP); + comparator.sortAscending(); + } + } + repositoryViewer.refresh(); + break; + } + } + } + + void safeRefresh(final MetadataRepositoryElement elementToSelect) { + Runnable runnable = new Runnable() { + public void run() { + repositoryViewer.refresh(); + if (elementToSelect != null) + repositoryViewer.setSelection(new StructuredSelection(elementToSelect), true); + } + }; + if (Display.getCurrent() == null) + display.asyncExec(runnable); + else + runnable.run(); + } + + void applyFilter() { + String text = pattern.getText(); + if (text == DEFAULT_FILTER_TEXT) + text = ""; //$NON-NLS-1$ + if (text.length() == 0) + filter.setPattern(null); + else + filter.setPattern(text); + if (filterJob != null) + filterJob.cancel(); + filterJob = new WorkbenchJob("filter job") { //$NON-NLS-1$ + public IStatus runInUIThread(IProgressMonitor monitor) { + if (monitor.isCanceled()) + return Status.CANCEL_STATUS; + if (!repositoryViewer.getTable().isDisposed()) + repositoryViewer.refresh(); + return Status.OK_STATUS; + } + + }; + filterJob.setSystem(true); + filterJob.schedule(FILTER_DELAY); + } + + void setDetails() { + MetadataRepositoryElement[] selections = getSelectedElements(); + if (selections.length == 1) { + details.setText(selections[0].getDescription()); + } else { + details.setText(""); //$NON-NLS-1$ + } + } + + /* (non-Javadoc) + * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) + */ + public void init(IWorkbench workbench) { + noDefaultAndApplyButton(); + if (ui == null) { + setProvisioningUI(ProvisioningUI.getDefaultUI()); + } + } + + void removeRepositories() { + MetadataRepositoryElement[] selections = getSelectedElements(); + if (selections.length > 0) { + String message = ProvUIMessages.RepositoryManipulationPage_RemoveConfirmMessage; + if (selections.length == 1) + message = NLS.bind(ProvUIMessages.RepositoryManipulationPage_RemoveConfirmSingleMessage, URIUtil.toUnencodedString(selections[0].getLocation())); + if (MessageDialog.openQuestion(getShell(), ProvUIMessages.RepositoryManipulationPage_RemoveConfirmTitle, message)) { + + changed = true; + for (int i = 0; i < selections.length; i++) { + getInput().cachedElements.remove(URIUtil.toUnencodedString(selections[i].getLocation())); + } + safeRefresh(null); + } + } + } + + // Return a repo manipulator that only operates on the local cache. + // Labels and other presentation info are used from the original manipulator. + RepositoryTracker getLocalCacheRepoTracker() { + if (localCacheRepoManipulator == null) + localCacheRepoManipulator = new RepositoryTracker() { + public void addRepository(URI location, String nickname, ProvisioningSession session) { + MetadataRepositoryElement element = (MetadataRepositoryElement) getInput().cachedElements.get(URIUtil.toUnencodedString(location)); + if (element == null) { + element = new MetadataRepositoryElement(getInput(), location, true); + getInput().cachedElements.put(URIUtil.toUnencodedString(location), element); + } + if (nickname != null) + element.setNickname(nickname); + changed = true; + safeRefresh(element); + } + + public URI[] getKnownRepositories(ProvisioningSession session) { + return RepositoryManipulationPage.this.getKnownRepositories(); + } + + public void removeRepositories(URI[] repoLocations, ProvisioningSession session) { + RepositoryManipulationPage.this.removeRepositories(); + } + + protected IStatus validateRepositoryLocationWithManager(ProvisioningSession session, URI location, IProgressMonitor monitor) { + return session.getMetadataRepositoryManager().validateRepositoryLocation(location, monitor); + } + + public void refreshRepositories(URI[] locations, ProvisioningSession session, IProgressMonitor monitor) { + // Nothing to refresh in the local cache + } + }; + return localCacheRepoManipulator; + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.p2.ui.ICopyable#copyToClipboard(org.eclipse.swt.widgets.Control) + */ + public void copyToClipboard(Control activeControl) { + MetadataRepositoryElement[] elements = getSelectedElements(); + if (elements.length == 0) + elements = getElements(); + String text = ""; //$NON-NLS-1$ + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < elements.length; i++) { + buffer.append(labelProvider.getClipboardText(elements[i], CopyUtils.DELIMITER)); + if (i > 0) + buffer.append(CopyUtils.NEWLINE); + } + text = buffer.toString(); + + if (text.length() == 0) + return; + Clipboard clipboard = new Clipboard(PlatformUI.getWorkbench().getDisplay()); + clipboard.setContents(new Object[] {text}, new Transfer[] {TextTransfer.getInstance()}); + clipboard.dispose(); + } + + // If more than half of the selected repos are enabled, toggle means disable. + // Otherwise it means enable. + private boolean toggleMeansDisable(MetadataRepositoryElement[] elements) { + double count = 0; + for (int i = 0; i < elements.length; i++) + if (elements[i].isEnabled()) + count++; + return (count / elements.length) > 0.5; + } + + URI[] getKnownRepositories() { + MetadataRepositoryElement[] elements = getElements(); + URI[] locations = new URI[elements.length]; + for (int i = 0; i < elements.length; i++) + locations[i] = elements[i].getLocation(); + return locations; + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/RevertProfilePage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/RevertProfilePage.java new file mode 100644 index 000000000..80f293827 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/RevertProfilePage.java @@ -0,0 +1,564 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.equinox.p2.ui; + +import org.eclipse.equinox.p2.core.ProvisionException; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.util.*; +import org.eclipse.compare.*; +import org.eclipse.compare.structuremergeviewer.Differencer; +import org.eclipse.compare.structuremergeviewer.IStructureComparator; +import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; +import org.eclipse.equinox.internal.p2.ui.*; +import org.eclipse.equinox.internal.p2.ui.dialogs.CopyUtils; +import org.eclipse.equinox.internal.p2.ui.dialogs.InstalledIUGroup; +import org.eclipse.equinox.internal.p2.ui.model.*; +import org.eclipse.equinox.internal.p2.ui.viewers.*; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.operations.*; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.dialogs.*; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.viewers.*; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.SashForm; +import org.eclipse.swt.dnd.*; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.*; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.about.InstallationPage; +import org.eclipse.ui.menus.AbstractContributionFactory; +import org.eclipse.ui.statushandlers.StatusManager; + +/** + * RevertProfilePage displays a profile's configuration history in + * an Installation Page. Clients can use this class as the implementation + * class for an installationPages extension. + * + * @see InstallationPage + * + * @noextend This class is not intended to be subclassed by clients. + * @noinstantiate This class is not intended to be instantiated by clients. + * @since 2.0 + * + */ +public class RevertProfilePage extends InstallationPage implements ICopyable { + + private static final int REVERT_ID = IDialogConstants.CLIENT_ID; + private static final int DELETE_ID = IDialogConstants.CLIENT_ID + 1; + private static final int COMPARE_ID = IDialogConstants.CLIENT_ID + 2; + TableViewer configsViewer; + TreeViewer configContentsViewer; + IUDetailsLabelProvider labelProvider; + IAction revertAction; + Button revertButton, deleteButton, compareButton; + String profileId; + AbstractContributionFactory factory; + Text detailsArea; + InstalledIUGroup installedIUGroup; + ProvisioningUI ui; + + /* + * (non-Javadoc) + * @see org.eclipse.ui.about.InstallationPage#createPageButtons(org.eclipse.swt.widgets.Composite) + */ + public void createPageButtons(Composite parent) { + if (profileId == null) + return; + compareButton = createButton(parent, COMPARE_ID, ProvUIMessages.RevertProfilePage_CompareLabel); + compareButton.setToolTipText(ProvUIMessages.RevertProfilePage_CompareTooltip); + compareButton.setEnabled(computeCompareEnablement()); + deleteButton = createButton(parent, DELETE_ID, ProvUIMessages.RevertProfilePage_Delete); + deleteButton.setToolTipText(ProvUIMessages.RevertProfilePage_DeleteTooltip); + deleteButton.setEnabled(computeDeleteEnablement()); + revertButton = createButton(parent, REVERT_ID, revertAction.getText()); + revertButton.setToolTipText(revertAction.getToolTipText()); + revertButton.setEnabled(revertAction.isEnabled()); + } + + /* + * (non-Javadoc) + * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) + */ + public void createControl(Composite parent) { + ui = ProvisioningUI.getDefaultUI(); + profileId = ui.getProfileId(); + if (profileId == null) { + IStatus status = ui.getPolicy().getNoProfileChosenStatus(); + if (status != null) + ProvUI.reportStatus(status, StatusManager.LOG); + Text text = new Text(parent, SWT.WRAP | SWT.READ_ONLY); + text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + text.setText(ProvUIMessages.RevertProfilePage_NoProfile); + setControl(text); + return; + } + + initializeDialogUnits(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IProvHelpContextIds.REVERT_CONFIGURATION_WIZARD); + + SashForm sashForm = new SashForm(parent, SWT.VERTICAL); + sashForm.setLayout(new GridLayout()); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + sashForm.setLayoutData(gd); + + createConfigurationsSection(sashForm); + createContentsSection(sashForm); + setControl(sashForm); + + // prime the selection. The selection accesses the + // revert action, so create it also. + createRevertAction(); + } + + private void createConfigurationsSection(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + GridData gd = new GridData(GridData.FILL_BOTH); + composite.setLayoutData(gd); + + Label label = new Label(composite, SWT.NONE); + label.setText(ProvUIMessages.RevertDialog_ConfigsLabel); + configsViewer = new TableViewer(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); + ProvElementContentProvider provider = new ProvElementContentProvider() { + protected void finishedFetchingElements(Object o) { + Object element = configsViewer.getElementAt(0); + if (element != null) + configsViewer.setSelection(new StructuredSelection(element)); + } + }; + configsViewer.setContentProvider(provider); + configsViewer.setLabelProvider(new ProvElementLabelProvider()); + configsViewer.setComparator(new ViewerComparator() { + // We override the ViewerComparator so that we don't get the labels of the elements + // for comparison, but rather get the timestamps and compare them. + // Reverse sorting is used so that newest is first. + public int compare(Viewer viewer, Object o1, Object o2) { + if (o1 instanceof RollbackProfileElement && o2 instanceof RollbackProfileElement) { + long timestamp1 = ((RollbackProfileElement) o1).getTimestamp(); + long timestamp2 = ((RollbackProfileElement) o2).getTimestamp(); + if (timestamp1 > timestamp2) + return -1; + return 1; + } + // this is naive (doesn't consult the label provider), but shouldn't happen + return o2.toString().compareTo(o1.toString()); + } + }); + configsViewer.setInput(getInput()); + + configsViewer.addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + handleSelectionChanged((IStructuredSelection) event.getSelection()); + } + + }); + CopyUtils.activateCopy(this, configsViewer.getControl()); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + configsViewer.getControl().setLayoutData(gd); + } + + private void createContentsSection(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + GridData gd = new GridData(GridData.FILL_BOTH); + composite.setLayoutData(gd); + + Label label = new Label(composite, SWT.NONE); + label.setText(ProvUIMessages.RevertDialog_ConfigContentsLabel); + configContentsViewer = new TreeViewer(composite, SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); + IUComparator comparator = new IUComparator(IUComparator.IU_NAME); + comparator.useColumnConfig(ProvUI.getIUColumnConfig()); + configContentsViewer.setComparator(comparator); + configContentsViewer.setComparer(new ProvElementComparer()); + configContentsViewer.setContentProvider(new DeferredQueryContentProvider()); + + // columns before labels or you get a blank table + setTreeColumns(configContentsViewer.getTree()); + labelProvider = new IUDetailsLabelProvider(); + configContentsViewer.setLabelProvider(labelProvider); + + gd = new GridData(GridData.FILL_BOTH); + configContentsViewer.getControl().setLayoutData(gd); + CopyUtils.activateCopy(this, configContentsViewer.getControl()); + } + + private void createRevertAction() { + revertAction = new Action() { + public void run() { + boolean result = MessageDialog.openQuestion(getShell(), ProvUIMessages.RevertDialog_Title, ProvUIMessages.RevertDialog_ConfirmRestartMessage); + if (!result) + return; + boolean finish = revert(); + if (finish) { + getPageContainer().closeModalContainers(); + } + } + }; + revertAction.setText(ProvUIMessages.RevertProfilePage_RevertLabel); + revertAction.setToolTipText(ProvUIMessages.RevertProfilePage_RevertTooltip); + } + + private Object getInput() { + ProfileSnapshots element = new ProfileSnapshots(profileId); + return element; + } + + protected void buttonPressed(int buttonId) { + switch (buttonId) { + case REVERT_ID : + revertAction.run(); + break; + case COMPARE_ID : + compare(); + break; + case DELETE_ID : + deleteSelectedSnapshots(); + break; + } + } + + void handleSelectionChanged(IStructuredSelection selection) { + if (!selection.isEmpty()) { + if (selection.size() == 1) { + final Object selected = selection.getFirstElement(); + if (selected instanceof RollbackProfileElement) { + Object[] elements = configContentsViewer.getExpandedElements(); + configContentsViewer.getTree().setRedraw(false); + configContentsViewer.setInput(selected); + configContentsViewer.setExpandedElements(elements); + configContentsViewer.getTree().setRedraw(true); + boolean isNotCurrentProfile = !((RollbackProfileElement) selected).isCurrentProfile(); + revertAction.setEnabled(isNotCurrentProfile); + if (revertButton != null) + revertButton.setEnabled(isNotCurrentProfile); + if (deleteButton != null) + deleteButton.setEnabled(isNotCurrentProfile); + if (compareButton != null) + compareButton.setEnabled(false); + return; + } + } else { + // multiple selections, can't revert or look at details + revertAction.setEnabled(false); + if (revertButton != null) { + revertButton.setEnabled(false); + } + configContentsViewer.setInput(null); + deleteButton.setEnabled(computeDeleteEnablement()); + compareButton.setEnabled(computeCompareEnablement()); + return; + } + } + // Nothing is selected + configContentsViewer.setInput(null); + revertAction.setEnabled(false); + if (revertButton != null) + revertButton.setEnabled(false); + if (deleteButton != null) + deleteButton.setEnabled(computeDeleteEnablement()); + } + + boolean computeDeleteEnablement() { + // delete is permitted if none of the selected elements are the current profile + boolean okToDelete = true; + Iterator iter = ((IStructuredSelection) configsViewer.getSelection()).iterator(); + while (iter.hasNext()) { + Object selected = iter.next(); + // If it's not a recognized element or if it is the current profile, we can't delete. Stop iterating. + if (!(selected instanceof RollbackProfileElement) || ((RollbackProfileElement) selected).isCurrentProfile()) { + okToDelete = false; + break; + } + } + return okToDelete; + } + + boolean computeCompareEnablement() { + // compare is enabled if there are two elements selected + Object[] selection = ((IStructuredSelection) configsViewer.getSelection()).toArray(); + if (selection.length == 2) { + for (int i = 0; i < selection.length; i++) { + if (!(selection[i] instanceof RollbackProfileElement)) + return false; + } + return true; + } + return false; + } + + private void setTreeColumns(Tree tree) { + IUColumnConfig[] columns = ProvUI.getIUColumnConfig(); + tree.setHeaderVisible(true); + + for (int i = 0; i < columns.length; i++) { + TreeColumn tc = new TreeColumn(tree, SWT.NONE, i); + tc.setResizable(true); + tc.setText(columns[i].getColumnTitle()); + tc.setWidth(columns[i].getWidthInPixels(tree)); + } + } + + private IProfile getSelectedSnapshot() { + Object selected = ((IStructuredSelection) configsViewer.getSelection()).getFirstElement(); + if (selected != null && selected instanceof RollbackProfileElement) + return ((RollbackProfileElement) selected).getProfileSnapshot(new NullProgressMonitor()); + return null; + } + + private RollbackProfileElement[] getRollbackProfileElementsToCompare() { + // expecting two items selected + RollbackProfileElement[] result = new RollbackProfileElement[2]; + IStructuredSelection selection = ((IStructuredSelection) configsViewer.getSelection()); + int i = 0; + for (Object selected : selection.toList()) { + if (selected != null && selected instanceof RollbackProfileElement) { + result[i++] = (RollbackProfileElement) selected; + } + if (i == 2) + break; + } + return result; + } + + boolean revert() { + final IProfile snapshot = getSelectedSnapshot(); + if (snapshot == null) + return false; + final IProvisioningPlan[] plan = new IProvisioningPlan[1]; + IRunnableWithProgress runnable = new IRunnableWithProgress() { + public void run(IProgressMonitor monitor) { + IProfile currentProfile; + currentProfile = getSession().getProfileRegistry().getProfile(profileId); + plan[0] = getSession().getPlanner().getDiffPlan(currentProfile, snapshot, monitor); + } + }; + ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell()); + try { + dialog.run(true, true, runnable); + } catch (InvocationTargetException e) { + ProvUI.handleException(e.getCause(), null, StatusManager.SHOW | StatusManager.LOG); + } catch (InterruptedException e) { + // nothing to report + } + // the dialog does not throw OperationCanceledException so we have to + // check the monitor + if (dialog.getProgressMonitor().isCanceled()) + return false; + + boolean reverted = false; + if (plan[0] != null) { + if (plan[0].getStatus().isOK()) { + // We use a default provisioning context (all repos) because we have no other + // way currently to figure out which sites the user wants to contact + ProfileModificationJob op = new ProfileModificationJob(ProvUIMessages.RevertDialog_RevertOperationLabel, getSession(), profileId, plan[0], new ProvisioningContext()); + // we want to force a restart (not allow apply changes) + op.setRestartPolicy(ProvisioningJob.RESTART_ONLY); + ui.schedule(op, StatusManager.SHOW | StatusManager.LOG); + reverted = true; + } else if (plan[0].getStatus().getSeverity() != IStatus.CANCEL) { + ProvUI.reportStatus(plan[0].getStatus(), StatusManager.LOG | StatusManager.SHOW); + // This message has no effect in an installation dialog + // setMessage(ProvUIMessages.ProfileModificationWizardPage_UnexpectedError, IMessageProvider.ERROR); + } + } + return reverted; + } + + void compare() { + final RollbackProfileElement[] rpe = getRollbackProfileElementsToCompare(); + CompareUI.openCompareDialog(new ProfileCompareEditorInput(rpe)); + } + + private class ProfileCompareEditorInput extends CompareEditorInput { + private Object root; + private ProvElementNode l; + private ProvElementNode r; + + public ProfileCompareEditorInput(RollbackProfileElement[] rpe) { + super(new CompareConfiguration()); + Assert.isTrue(rpe.length == 2); + l = new ProvElementNode(rpe[0]); + r = new ProvElementNode(rpe[1]); + } + + protected Object prepareInput(IProgressMonitor monitor) { + initLabels(); + Differencer d = new Differencer(); + root = d.findDifferences(false, monitor, null, null, l, r); + return root; + } + + private void initLabels() { + CompareConfiguration cc = getCompareConfiguration(); + cc.setLeftEditable(false); + cc.setRightEditable(false); + cc.setLeftLabel(l.getName()); + cc.setLeftImage(l.getImage()); + cc.setRightLabel(r.getName()); + cc.setRightImage(r.getImage()); + } + + public String getOKButtonLabel() { + return IDialogConstants.OK_LABEL; + } + } + + private class ProvElementNode implements IStructureComparator, ITypedElement, IStreamContentAccessor { + private ProvElement pe; + private IInstallableUnit iu; + final static String BLANK = ""; //$NON-NLS-1$ + private String id = BLANK; + + public ProvElementNode(Object input) { + pe = (ProvElement) input; + iu = (IInstallableUnit) ProvUI.getAdapter(pe, IInstallableUnit.class); + if (iu != null) { + id = iu.getId(); + } + } + + public Object[] getChildren() { + Set children = new HashSet(); + if (pe instanceof RollbackProfileElement) { + Object[] c = ((RollbackProfileElement) pe).getChildren(null); + for (int i = 0; i < c.length; i++) { + children.add(new ProvElementNode(c[i])); + } + } else if (pe instanceof InstalledIUElement) { + Object[] c = ((InstalledIUElement) pe).getChildren(null); + for (int i = 0; i < c.length; i++) { + children.add(new ProvElementNode(c[i])); + } + } + return children.toArray(); + } + + /** + * Implementation based on id. + * @param other the object to compare this ProvElementNode against. + * @return true if the ProvElementNodesare equal; false otherwise. + */ + public boolean equals(Object other) { + if (other instanceof ProvElementNode) + return id.equals(((ProvElementNode) other).id); + return super.equals(other); + } + + /** + * Implementation based on id. + * @return a hash code for this object. + */ + public int hashCode() { + return id.hashCode(); + } + + public Image getImage() { + return pe.getImage(null); + } + + public String getName() { + if (iu != null) { + return iu.getProperty(IInstallableUnit.PROP_NAME, null); + } + return pe.getLabel(null); + } + + public String getType() { + return ITypedElement.UNKNOWN_TYPE; + } + + public InputStream getContents() { + String contents = BLANK; + if (iu != null) { + contents = iu.getVersion().toString(); + } + return new ByteArrayInputStream(contents.getBytes()); + } + } + + /* + * (non-Javadoc) + * @see org.eclipse.equinox.p2.ui.ICopyable#copyToClipboard(org.eclipse.swt.widgets.Control) + */ + public void copyToClipboard(Control activeControl) { + String text = ""; //$NON-NLS-1$ + if (activeControl == configContentsViewer.getControl()) { + text = CopyUtils.getIndentedClipboardText(((IStructuredSelection) configContentsViewer.getSelection()).toArray(), labelProvider); + } else if (activeControl == configsViewer.getControl()) { + Object[] elements = ((IStructuredSelection) configsViewer.getSelection()).toArray(); + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < elements.length; i++) { + if (elements[i] instanceof RollbackProfileElement) { + if (i > 0) + buffer.append(CopyUtils.NEWLINE); + buffer.append(((RollbackProfileElement) elements[i]).getLabel(elements[i])); + } + } + text = buffer.toString(); + } else + return; + if (text.length() == 0) + return; + Clipboard clipboard = new Clipboard(PlatformUI.getWorkbench().getDisplay()); + clipboard.setContents(new Object[] {text}, new Transfer[] {TextTransfer.getInstance()}); + clipboard.dispose(); + } + + void deleteSelectedSnapshots() { + IStructuredSelection selection = (IStructuredSelection) configsViewer.getSelection(); + if (selection.isEmpty()) + return; + String title = selection.size() == 1 ? ProvUIMessages.RevertProfilePage_DeleteSingleConfigurationTitle : ProvUIMessages.RevertProfilePage_DeleteMultipleConfigurationsTitle; + String confirmMessage = selection.size() == 1 ? ProvUIMessages.RevertProfilePage_ConfirmDeleteSingleConfig : ProvUIMessages.RevertProfilePage_ConfirmDeleteMultipleConfigs; + if (MessageDialog.openConfirm(configsViewer.getControl().getShell(), title, confirmMessage)) { + Iterator iter = selection.iterator(); + while (iter.hasNext()) { + Object selected = iter.next(); + // If it is a recognized element and it is not the current profile, then it can be deleted. + if (selected instanceof RollbackProfileElement && !((RollbackProfileElement) selected).isCurrentProfile()) { + RollbackProfileElement snapshot = (RollbackProfileElement) selected; + IProfileRegistry registry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.SERVICE_NAME); + if (registry != null) { + try { + registry.removeProfile(profileId, snapshot.getTimestamp()); + configsViewer.refresh(); + } catch (ProvisionException e) { + ProvUI.handleException(e, null, StatusManager.SHOW | StatusManager.LOG); + } + } + } + } + } + } + + ProvisioningSession getSession() { + return getProvisioningUI().getSession(); + } + + ProvisioningUI getProvisioningUI() { + return ProvisioningUI.getDefaultUI(); + } +} diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/package.html b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/package.html new file mode 100644 index 000000000..8dced36e6 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/package.html @@ -0,0 +1,39 @@ + + + + + + + Package-level Javadoc + + +Provides provisioning user interface classes that can be used for assembling +a provisioning UI. +

    +Package Specification

    +

    +This package consists of several kinds of classes: +

      +
    • ProvisioningUI is the hub of the UI. It is used to access the underlying +provisioning session and its services, as well as all services registered by the UI. +It also provides utility methods that allow clients to create provisioning operations +or launch provisioning wizards. +
    • +
    • Policy defines those aspects of the provisioning UI that can be configured +by clients. +
    • +
    • LicenseManager describes a service which accepts or rejects +licenses and remembers the accepted licenses. Clients should register +an implementation of LicenseManager in order to remember the +licenses. +
    • +
    • Various pages define reusable pages that can be hosted inside wizards +and dialogs. In general, the pages are meant to be contributed by extension point. +In some cases, direct instantiation of the pages is permitted. See the individual page +javadoc for usage. +
    • +
    +

    +@since 2.0 + + diff --git a/bundles/org.eclipse.equinox.p2.updatechecker/.classpath b/bundles/org.eclipse.equinox.p2.updatechecker/.classpath index 6f3b481ac..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.updatechecker/.classpath +++ b/bundles/org.eclipse.equinox.p2.updatechecker/.classpath @@ -1,6 +1,6 @@ - + diff --git a/bundles/org.eclipse.equinox.p2.updatechecker/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.updatechecker/.settings/org.eclipse.jdt.core.prefs index 5247d61b0..e515fdb64 100644 --- a/bundles/org.eclipse.equinox.p2.updatechecker/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.updatechecker/.settings/org.eclipse.jdt.core.prefs @@ -1,329 +1,329 @@ -#Thu Oct 09 08:15:31 EDT 2008 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert -org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning -org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false -org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false -org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +#Wed Dec 30 07:21:17 CET 2009 +eclipse.preferences.version=1 +org.eclipse.jdt.core.builder.cleanOutputFolder=clean +org.eclipse.jdt.core.builder.duplicateResourceTask=warning +org.eclipse.jdt.core.builder.invalidClasspath=abort +org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch +org.eclipse.jdt.core.circularClasspath=error +org.eclipse.jdt.core.classpath.exclusionPatterns=enabled +org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.doc.comment.support=enabled +org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=public -org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=warning -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fieldHiding=warning -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning -org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert -org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=error +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=warning +org.eclipse.jdt.core.compiler.problem.invalidJavadoc=error +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private +org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=enabled +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public +org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=public +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.formatter.comment.format_source_code=true -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=warning -org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=warning -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -org.eclipse.jdt.core.classpath.exclusionPatterns=enabled +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=warning +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=enabled +org.eclipse.jdt.core.compiler.problem.unusedImport=error +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.5 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 -org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert -org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.formatter.comment.format_header=false -org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.comment.line_length=80 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert -org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert -org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.builder.cleanOutputFolder=clean -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=enabled -org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert -org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=false -org.eclipse.jdt.core.formatter.continuation_indentation=2 -org.eclipse.jdt.core.compiler.problem.invalidJavadoc=error -org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 -org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line -org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.incompleteClasspath=error -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=enabled -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false org.eclipse.jdt.core.formatter.comment.format_block_comments=false -org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert -org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=insert +org.eclipse.jdt.core.formatter.comment.format_header=false org.eclipse.jdt.core.formatter.comment.format_html=true -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning -org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=error -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=false +org.eclipse.jdt.core.formatter.comment.format_line_comments=false +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=false +org.eclipse.jdt.core.formatter.comment.indent_root_tags=false +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert -org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.comment.line_length=80 +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert -org.eclipse.jdt.core.circularClasspath=error -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning -org.eclipse.jdt.core.formatter.tabulation.char=tab -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert -org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert -org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false -org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false -org.eclipse.jdt.core.formatter.compact_else_if=true -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert -org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert -org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore -org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true -org.eclipse.jdt.core.compiler.problem.discouragedReference=error -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 -org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert -org.eclipse.jdt.core.formatter.comment.format_line_comments=false -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert -org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert -org.eclipse.jdt.core.formatter.comment.indent_parameter_description=false -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=enabled -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert -org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.comment.indent_root_tags=false -org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enabled -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert -org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false -org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true -org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.blank_lines_before_package=0 org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert -org.eclipse.jdt.core.formatter.indent_empty_lines=false -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert -org.eclipse.jdt.core.compiler.problem.unusedImport=error -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert -org.eclipse.jdt.core.builder.invalidClasspath=abort -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.incompatibleJDKLevel=ignore -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false org.eclipse.jdt.core.formatter.lineSplit=800 -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled -org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 -org.eclipse.jdt.core.compiler.source=1.3 -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false +org.eclipse.jdt.core.formatter.tabulation.char=tab org.eclipse.jdt.core.formatter.tabulation.size=4 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert -org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert -org.eclipse.jdt.core.builder.duplicateResourceTask=warning -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=insert -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.compiler.doc.comment.support=enabled -org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.compiler.compliance=1.4 -org.eclipse.jdt.core.formatter.blank_lines_after_package=1 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert -org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.incompatibleJDKLevel=ignore +org.eclipse.jdt.core.incompleteClasspath=error diff --git a/bundles/org.eclipse.equinox.p2.updatechecker/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.updatechecker/META-INF/MANIFEST.MF index 1758c15cc..63480f100 100644 --- a/bundles/org.eclipse.equinox.p2.updatechecker/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.updatechecker/META-INF/MANIFEST.MF @@ -7,17 +7,19 @@ Bundle-Localization: plugin Bundle-Version: 1.1.0.qualifier Bundle-Activator: org.eclipse.equinox.internal.p2.updatechecker.Activator Import-Package: org.eclipse.equinox.internal.p2.core.helpers, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, - org.eclipse.equinox.internal.provisional.p2.core, - org.eclipse.equinox.internal.provisional.p2.repository, org.eclipse.equinox.internal.provisional.p2.director, - org.eclipse.equinox.internal.provisional.p2.engine, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.engine, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.metadata, org.osgi.framework;version="1.4.0" -Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, - J2SE-1.4 +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, + CDC-1.1/Foundation-1.1 Export-Package: org.eclipse.equinox.internal.p2.updatechecker;x-internal:=true, org.eclipse.equinox.internal.provisional.p2.updatechecker;x-friends:="org.eclipse.equinox.p2.ui.sdk.scheduler" Require-Bundle: org.eclipse.equinox.common;bundle-version="[3.3.0,4.0)" diff --git a/bundles/org.eclipse.equinox.p2.updatechecker/build.properties b/bundles/org.eclipse.equinox.p2.updatechecker/build.properties index dc77b9c16..ca5030900 100644 --- a/bundles/org.eclipse.equinox.p2.updatechecker/build.properties +++ b/bundles/org.eclipse.equinox.p2.updatechecker/build.properties @@ -15,3 +15,5 @@ bin.includes = META-INF/,\ about.html,\ plugin.properties src.includes = about.html +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.updatechecker/src/org/eclipse/equinox/internal/p2/updatechecker/UpdateChecker.java b/bundles/org.eclipse.equinox.p2.updatechecker/src/org/eclipse/equinox/internal/p2/updatechecker/UpdateChecker.java index 32f765f3a..894909865 100644 --- a/bundles/org.eclipse.equinox.p2.updatechecker/src/org/eclipse/equinox/internal/p2/updatechecker/UpdateChecker.java +++ b/bundles/org.eclipse.equinox.p2.updatechecker/src/org/eclipse/equinox/internal/p2/updatechecker/UpdateChecker.java @@ -10,24 +10,21 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.updatechecker; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; - -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; - import java.net.URI; import java.text.SimpleDateFormat; import java.util.*; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.core.helpers.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.engine.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; import org.eclipse.equinox.internal.provisional.p2.updatechecker.*; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.engine.*; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; /** * Default implementation of {@link IUpdateChecker}. @@ -42,7 +39,7 @@ public class UpdateChecker implements IUpdateChecker { /** * Map of IUpdateListener->UpdateCheckThread. */ - private HashMap checkers = new HashMap(); + private HashMap checkers = new HashMap(); IProfileRegistry profileRegistry; IPlanner planner; @@ -52,9 +49,9 @@ public class UpdateChecker implements IUpdateChecker { long poll, delay; IUpdateListener listener; String profileId; - Query query; + IQuery query; - UpdateCheckThread(String profileId, Query query, long delay, long poll, IUpdateListener listener) { + UpdateCheckThread(String profileId, IQuery query, long delay, long poll, IUpdateListener listener) { this.poll = poll; this.delay = delay; this.profileId = profileId; @@ -96,7 +93,7 @@ public class UpdateChecker implements IUpdateChecker { /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.p2.updatechecker.IUpdateChecker#addUpdateCheck(java.lang.String, long, long, org.eclipse.equinox.internal.provisional.p2.updatechecker.IUpdateListener) */ - public void addUpdateCheck(String profileId, Query query, long delay, long poll, IUpdateListener listener) { + public void addUpdateCheck(String profileId, IQuery query, long delay, long poll, IUpdateListener listener) { if (checkers.containsKey(listener)) return; trace("Adding update checker for " + profileId + " at " + getTimeStamp()); //$NON-NLS-1$ //$NON-NLS-2$ @@ -116,31 +113,31 @@ public class UpdateChecker implements IUpdateChecker { * Return the array of ius in the profile that have updates * available. */ - IInstallableUnit[] checkForUpdates(String profileId, Query query) { + IInstallableUnit[] checkForUpdates(String profileId, IQuery query) { IProfile profile = getProfileRegistry().getProfile(profileId); - ArrayList iusWithUpdates = new ArrayList(); + ArrayList iusWithUpdates = new ArrayList(); if (profile == null) return new IInstallableUnit[0]; ProvisioningContext context = new ProvisioningContext(getAvailableRepositories()); if (query == null) query = InstallableUnitQuery.ANY; - Iterator iter = profile.query(query, new Collector(), null).iterator(); + Iterator iter = profile.query(query, null).iterator(); while (iter.hasNext()) { - IInstallableUnit iu = (IInstallableUnit) iter.next(); + IInstallableUnit iu = iter.next(); IInstallableUnit[] replacements = getPlanner().updatesFor(iu, context, null); if (replacements.length > 0) iusWithUpdates.add(iu); } - return (IInstallableUnit[]) iusWithUpdates.toArray(new IInstallableUnit[iusWithUpdates.size()]); + return iusWithUpdates.toArray(new IInstallableUnit[iusWithUpdates.size()]); } /** * Returns the list of metadata repositories that are currently available. */ private URI[] getAvailableRepositories() { - IMetadataRepositoryManager repoMgr = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.class.getName()); + IMetadataRepositoryManager repoMgr = (IMetadataRepositoryManager) ServiceHelper.getService(Activator.getContext(), IMetadataRepositoryManager.SERVICE_NAME); URI[] repositories = repoMgr.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); - ArrayList available = new ArrayList(); + ArrayList available = new ArrayList(); for (int i = 0; i < repositories.length; i++) { try { repoMgr.loadRepository(repositories[i], null); @@ -149,7 +146,7 @@ public class UpdateChecker implements IUpdateChecker { LogHelper.log(e.getStatus()); } } - return (URI[]) available.toArray(new URI[available.size()]); + return available.toArray(new URI[available.size()]); } void trace(String message) { @@ -165,7 +162,7 @@ public class UpdateChecker implements IUpdateChecker { IPlanner getPlanner() { if (planner == null) { - planner = (IPlanner) ServiceHelper.getService(Activator.getContext(), IPlanner.class.getName()); + planner = (IPlanner) ServiceHelper.getService(Activator.getContext(), IPlanner.SERVICE_NAME); if (planner == null) { throw new IllegalStateException("Provisioning system has not been initialized"); //$NON-NLS-1$ } @@ -175,7 +172,7 @@ public class UpdateChecker implements IUpdateChecker { IProfileRegistry getProfileRegistry() { if (profileRegistry == null) { - profileRegistry = (IProfileRegistry) ServiceHelper.getService(Activator.getContext(), IProfileRegistry.class.getName()); + profileRegistry = (IProfileRegistry) ServiceHelper.getService(Activator.getContext(), IProfileRegistry.SERVICE_NAME); if (profileRegistry == null) { throw new IllegalStateException("Provisioning system has not been initialized"); //$NON-NLS-1$ } diff --git a/bundles/org.eclipse.equinox.p2.updatechecker/src/org/eclipse/equinox/internal/provisional/p2/updatechecker/IUpdateChecker.java b/bundles/org.eclipse.equinox.p2.updatechecker/src/org/eclipse/equinox/internal/provisional/p2/updatechecker/IUpdateChecker.java index 20e8466c1..31c6e5618 100644 --- a/bundles/org.eclipse.equinox.p2.updatechecker/src/org/eclipse/equinox/internal/provisional/p2/updatechecker/IUpdateChecker.java +++ b/bundles/org.eclipse.equinox.p2.updatechecker/src/org/eclipse/equinox/internal/provisional/p2/updatechecker/IUpdateChecker.java @@ -10,7 +10,8 @@ *******************************************************************************/ package org.eclipse.equinox.internal.provisional.p2.updatechecker; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQuery; /** * An update checker periodically polls for updates to specified profiles and @@ -41,7 +42,7 @@ public interface IUpdateChecker { * @param listener The listener to be notified of updates * @see #removeUpdateCheck(IUpdateListener) */ - public abstract void addUpdateCheck(String profileId, Query iusToCheckQuery, long delay, long poll, IUpdateListener listener); + public abstract void addUpdateCheck(String profileId, IQuery iusToCheckQuery, long delay, long poll, IUpdateListener listener); /** * Removes an update listener from the set of listeners registered with this update @@ -50,7 +51,7 @@ public interface IUpdateChecker { * no effect. * * @param listener The listener to remove - * @see #addUpdateCheck(String, Query, long, long, IUpdateListener) + * @see #addUpdateCheck(String, IQuery, long, long, IUpdateListener) */ public abstract void removeUpdateCheck(IUpdateListener listener); diff --git a/bundles/org.eclipse.equinox.p2.updatechecker/src/org/eclipse/equinox/internal/provisional/p2/updatechecker/UpdateEvent.java b/bundles/org.eclipse.equinox.p2.updatechecker/src/org/eclipse/equinox/internal/provisional/p2/updatechecker/UpdateEvent.java index 187b32cbf..6a6297852 100644 --- a/bundles/org.eclipse.equinox.p2.updatechecker/src/org/eclipse/equinox/internal/provisional/p2/updatechecker/UpdateEvent.java +++ b/bundles/org.eclipse.equinox.p2.updatechecker/src/org/eclipse/equinox/internal/provisional/p2/updatechecker/UpdateEvent.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.equinox.internal.provisional.p2.updatechecker; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; /** * An UpdateEvent describes what IU's have updates for a given profile. diff --git a/bundles/org.eclipse.equinox.p2.updatesite/.classpath b/bundles/org.eclipse.equinox.p2.updatesite/.classpath index 2fbb7a23e..64c5e31b7 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/.classpath +++ b/bundles/org.eclipse.equinox.p2.updatesite/.classpath @@ -1,6 +1,6 @@ - + diff --git a/bundles/org.eclipse.equinox.p2.updatesite/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.equinox.p2.updatesite/.settings/org.eclipse.jdt.core.prefs index f9e494258..43911f588 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.equinox.p2.updatesite/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Tue Mar 31 14:49:21 EDT 2009 +#Mon Dec 28 00:21:51 CET 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.builder.cleanOutputFolder=clean org.eclipse.jdt.core.builder.duplicateResourceTask=warning @@ -8,26 +8,26 @@ org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch org.eclipse.jdt.core.circularClasspath=error org.eclipse.jdt.core.classpath.exclusionPatterns=enabled org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.maxProblemPerUnit=1000 org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning org.eclipse.jdt.core.compiler.problem.deadCode=warning org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=error +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning org.eclipse.jdt.core.compiler.problem.emptyStatement=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=warning @@ -55,6 +55,7 @@ org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=public org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning @@ -93,7 +94,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=enab org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 diff --git a/bundles/org.eclipse.equinox.p2.updatesite/.settings/org.eclipse.jdt.launching.prefs b/bundles/org.eclipse.equinox.p2.updatesite/.settings/org.eclipse.jdt.launching.prefs new file mode 100644 index 000000000..ff827d560 --- /dev/null +++ b/bundles/org.eclipse.equinox.p2.updatesite/.settings/org.eclipse.jdt.launching.prefs @@ -0,0 +1,3 @@ +#Sun Dec 06 23:05:15 EST 2009 +eclipse.preferences.version=1 +org.eclipse.jdt.launching.PREF_STRICTLY_COMPATIBLE_JRE_NOT_AVAILABLE=warning diff --git a/bundles/org.eclipse.equinox.p2.updatesite/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.p2.updatesite/META-INF/MANIFEST.MF index 052eee2ec..bc52dc44f 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.p2.updatesite/META-INF/MANIFEST.MF @@ -4,28 +4,33 @@ Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-SymbolicName: org.eclipse.equinox.p2.updatesite;singleton:=true Bundle-Localization: plugin -Bundle-Version: 1.0.100.qualifier +Bundle-Version: 1.0.200.qualifier Bundle-Activator: org.eclipse.equinox.internal.p2.updatesite.Activator Bundle-ActivationPolicy: lazy Import-Package: javax.xml.parsers, org.eclipse.equinox.app;version="1.0.0";resolution:=optional, + org.eclipse.equinox.internal.p2.artifact.repository.simple, org.eclipse.equinox.internal.p2.core.helpers, + org.eclipse.equinox.internal.p2.metadata, + org.eclipse.equinox.internal.p2.metadata.query, org.eclipse.equinox.internal.p2.publisher.eclipse, org.eclipse.equinox.internal.p2.repository, org.eclipse.equinox.internal.p2.repository.helpers, - org.eclipse.equinox.internal.provisional.p2.artifact.repository, - org.eclipse.equinox.internal.provisional.p2.core, org.eclipse.equinox.internal.provisional.p2.core.eventbus, org.eclipse.equinox.internal.provisional.p2.metadata, - org.eclipse.equinox.internal.provisional.p2.metadata.query, - org.eclipse.equinox.internal.provisional.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.p2.repository, - org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository, - org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository, - org.eclipse.equinox.internal.provisional.spi.p2.repository, + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.metadata.query, org.eclipse.equinox.p2.publisher, org.eclipse.equinox.p2.publisher.actions, org.eclipse.equinox.p2.publisher.eclipse, + org.eclipse.equinox.p2.query, + org.eclipse.equinox.p2.repository, + org.eclipse.equinox.p2.repository.artifact, + org.eclipse.equinox.p2.repository.artifact.spi, + org.eclipse.equinox.p2.repository.metadata, + org.eclipse.equinox.p2.repository.metadata.spi, + org.eclipse.equinox.p2.repository.spi, org.eclipse.equinox.security.storage, org.eclipse.equinox.spi.p2.publisher, org.eclipse.osgi.service.resolver;version="1.2.0", @@ -33,16 +38,17 @@ Import-Package: javax.xml.parsers, org.eclipse.osgi.util;version="1.1.0", org.osgi.framework;version="1.3.0", org.osgi.util.tracker;version="1.3.0", + org.w3c.dom, org.xml.sax, - org.xml.sax.helpers, - org.w3c.dom + org.xml.sax.helpers Require-Bundle: org.eclipse.ecf.filetransfer, org.eclipse.ecf, org.eclipse.equinox.common;bundle-version="[3.3.0,4.0.0)", org.eclipse.equinox.p2.metadata.repository;bundle-version="0.1.0", org.eclipse.equinox.p2.artifact.repository;bundle-version="0.1.0", org.eclipse.core.jobs;bundle-version="[3.2.0,4.0.0)" -Bundle-RequiredExecutionEnvironment: J2SE-1.4, +Bundle-RequiredExecutionEnvironment: J2SE-1.5, + J2SE-1.4, CDC-1.1/Foundation-1.1 Export-Package: org.eclipse.equinox.internal.p2.updatesite;x-friends:="org.eclipse.pde.build", org.eclipse.equinox.internal.p2.updatesite.artifact;x-internal:=true, diff --git a/bundles/org.eclipse.equinox.p2.updatesite/build.properties b/bundles/org.eclipse.equinox.p2.updatesite/build.properties index f6b01e53f..c5640282b 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/build.properties +++ b/bundles/org.eclipse.equinox.p2.updatesite/build.properties @@ -16,3 +16,5 @@ bin.includes = META-INF/,\ plugin.properties,\ about.html src.includes = about.html +javacTarget=jsr14 +javacSource=1.5 diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/CategoryXMLAction.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/CategoryXMLAction.java index 5321d13da..fafe4e912 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/CategoryXMLAction.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/CategoryXMLAction.java @@ -9,9 +9,10 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.updatesite; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.net.URI; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.p2.publisher.IPublisherInfo; import org.eclipse.equinox.p2.publisher.IPublisherResult; diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/DefaultSiteParser.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/DefaultSiteParser.java index ac5e456ab..cdc70b705 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/DefaultSiteParser.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/DefaultSiteParser.java @@ -58,15 +58,15 @@ public class DefaultSiteParser extends DefaultHandler { private boolean DESCRIPTION_SITE_ALREADY_SEEN = false; // Current object stack (used to hold the current object we are // populating in this plugin descriptor - Stack objectStack = new Stack(); + Stack objectStack = new Stack(); private SAXParser parser; // Current State Information - Stack stateStack = new Stack(); + Stack stateStack = new Stack(); // List of string keys for translated strings - private final List messageKeys = new ArrayList(4); + private final List messageKeys = new ArrayList(4); private MultiStatus status; private final URI siteLocation; @@ -130,8 +130,8 @@ public class DefaultSiteParser extends DefaultHandler { public DefaultSiteParser(URI siteLocation) { super(); this.siteLocation = siteLocation; - stateStack = new Stack(); - objectStack = new Stack(); + stateStack = new Stack(); + objectStack = new Stack(); status = null; DESCRIPTION_SITE_ALREADY_SEEN = false; try { @@ -155,7 +155,7 @@ public class DefaultSiteParser extends DefaultHandler { public void characters(char[] ch, int start, int length) { String text = new String(ch, start, length); //only push if description - int state = ((Integer) stateStack.peek()).intValue(); + int state = stateStack.peek().intValue(); if (state == STATE_DESCRIPTION_SITE || state == STATE_DESCRIPTION_CATEGORY_DEF) objectStack.push(text); @@ -171,7 +171,7 @@ public class DefaultSiteParser extends DefaultHandler { String text = null; URLEntry info = null; - int state = ((Integer) stateStack.peek()).intValue(); + int state = stateStack.peek().intValue(); switch (state) { case STATE_IGNORED_ELEMENT : case STATE_ARCHIVE : @@ -501,7 +501,7 @@ public class DefaultSiteParser extends DefaultHandler { */ public SiteModel parse(InputStream in) throws SAXException, IOException { stateStack.push(new Integer(STATE_INITIAL)); - currentState = ((Integer) stateStack.peek()).intValue(); + currentState = stateStack.peek().intValue(); parser.parse(new InputSource(in), this); if (objectStack.isEmpty()) throw new SAXException(Messages.DefaultSiteParser_NoSiteTag); @@ -511,7 +511,7 @@ public class DefaultSiteParser extends DefaultHandler { return site; } String stack = ""; //$NON-NLS-1$ - Iterator iter = objectStack.iterator(); + Iterator iter = objectStack.iterator(); while (iter.hasNext()) { stack = stack + iter.next().toString() + "\r\n"; //$NON-NLS-1$ } @@ -797,7 +797,7 @@ public class DefaultSiteParser extends DefaultHandler { internalErrorUnknownTag(NLS.bind(Messages.DefaultSiteParser_UnknownStartState, (new String[] {getState(currentState)}))); break; } - int newState = ((Integer) stateStack.peek()).intValue(); + int newState = stateStack.peek().intValue(); if (newState != STATE_IGNORED_ELEMENT) currentState = newState; diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/DigestParser.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/DigestParser.java index af0e3ba73..9a0809483 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/DigestParser.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/DigestParser.java @@ -36,7 +36,7 @@ public class DigestParser extends DefaultHandler { private final static SAXParserFactory parserFactory = SAXParserFactory.newInstance(); private SAXParser parser; - private final List features = new ArrayList(); + private final List features = new ArrayList(); private final FeatureManifestParser featureHandler = new FeatureManifestParser(false); public DigestParser() { @@ -82,7 +82,7 @@ public class DigestParser extends DefaultHandler { return null; is = new BufferedInputStream(jar.getInputStream(entry)); parser.parse(new InputSource(is), this); - return (Feature[]) features.toArray(new Feature[features.size()]); + return features.toArray(new Feature[features.size()]); } catch (IOException e) { LogHelper.log(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.ErrorReadingDigest, location), e)); } catch (SAXException e) { diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/LocalUpdateSiteAction.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/LocalUpdateSiteAction.java index 6fd9d0e0b..04b9f66ba 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/LocalUpdateSiteAction.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/LocalUpdateSiteAction.java @@ -10,6 +10,8 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.updatesite; +import org.eclipse.equinox.p2.publisher.IPublisherAction; + import java.io.File; import java.util.ArrayList; import org.eclipse.core.runtime.*; @@ -71,12 +73,12 @@ public class LocalUpdateSiteAction implements IPublisherAction { protected IPublisherAction[] createActions() { createAdvice(); - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList(); // create an action that just publishes the raw bundles and features IPublisherAction action = new MergeResultsAction(new IPublisherAction[] {createFeaturesAction(), createBundlesAction()}, IPublisherResult.MERGE_ALL_NON_ROOT); result.add(action); result.add(createSiteXMLAction()); - return (IPublisherAction[]) result.toArray(new IPublisherAction[result.size()]); + return result.toArray(new IPublisherAction[result.size()]); } private IPublisherAction createSiteXMLAction() { diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/RemoteFeaturesAction.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/RemoteFeaturesAction.java index 64e568e61..26434ef8e 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/RemoteFeaturesAction.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/RemoteFeaturesAction.java @@ -10,11 +10,12 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.updatesite; +import org.eclipse.equinox.p2.core.ProvisionException; + import java.util.*; import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.*; import org.eclipse.equinox.p2.publisher.eclipse.*; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; @@ -48,7 +49,7 @@ public class RemoteFeaturesAction extends FeaturesAction { } protected void generateFeatureIUs(Feature[] featureList, IPublisherResult result) { - Properties extraProperties = new Properties(); + Map extraProperties = new HashMap(); extraProperties.put(IInstallableUnit.PROP_PARTIAL_IU, Boolean.TRUE.toString()); for (int i = 0; i < featureList.length; i++) { Feature feature = featureList[i]; @@ -56,7 +57,7 @@ public class RemoteFeaturesAction extends FeaturesAction { for (int j = 0; j < featureEntries.length; j++) { FeatureEntry entry = featureEntries[j]; if (entry.isPlugin() && !entry.isRequires()) { - Dictionary mockManifest = new Properties(); + Dictionary mockManifest = new Hashtable(); mockManifest.put("Manifest-Version", "1.0"); //$NON-NLS-1$ //$NON-NLS-2$ mockManifest.put("Bundle-ManifestVersion", "2"); //$NON-NLS-1$ //$NON-NLS-2$ mockManifest.put("Bundle-SymbolicName", entry.getId()); //$NON-NLS-1$ @@ -69,7 +70,7 @@ public class RemoteFeaturesAction extends FeaturesAction { } } IInstallableUnit featureIU = createFeatureJarIU(feature, new PublisherInfo()); - List childIUs = new ArrayList(); + List childIUs = new ArrayList(); childIUs.add(featureIU); IInstallableUnit groupIU = createGroupIU(feature, childIUs, new PublisherInfo()); result.addIU(featureIU, IPublisherResult.ROOT); diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/RemoteUpdateSiteAction.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/RemoteUpdateSiteAction.java index 428c06122..f7278e23e 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/RemoteUpdateSiteAction.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/RemoteUpdateSiteAction.java @@ -10,6 +10,8 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.updatesite; +import org.eclipse.equinox.p2.publisher.IPublisherAction; + import java.util.ArrayList; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.Tracing; @@ -55,10 +57,10 @@ public class RemoteUpdateSiteAction implements IPublisherAction { } protected IPublisherAction[] createActions() { - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList(); result.add(new RemoteFeaturesAction(updateSite)); result.add(createSiteXMLAction()); - return (IPublisherAction[]) result.toArray(new IPublisherAction[result.size()]); + return result.toArray(new IPublisherAction[result.size()]); } private IPublisherAction createSiteXMLAction() { diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteCategory.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteCategory.java index 131016e6e..06ed2a961 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteCategory.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteCategory.java @@ -12,8 +12,7 @@ package org.eclipse.equinox.internal.p2.updatesite; import java.net.MalformedURLException; import java.net.URL; -import java.util.Comparator; -import java.util.Map; +import java.util.*; /** * A category in an update site. @@ -22,11 +21,11 @@ import java.util.Map; */ public class SiteCategory { - private static Comparator comp; + private static Comparator comp; private String description; private String label; private String name; - private Map localizations; + private Map> localizations; /** * Returns a comparator for category models. @@ -34,19 +33,16 @@ public class SiteCategory { * @return comparator * @since 2.0 */ - public static Comparator getComparator() { + public static Comparator getComparator() { if (comp == null) { - comp = new Comparator() { + comp = new Comparator() { /* * @see Comparator#compare(Object,Object) * Returns 0 if versions are equal. * Returns -1 if object1 is after than object2. * Returns +1 if object1 is before than object2. */ - public int compare(Object o1, Object o2) { - - SiteCategory cat1 = (SiteCategory) o1; - SiteCategory cat2 = (SiteCategory) o2; + public int compare(SiteCategory cat1, SiteCategory cat2) { if (cat1.equals(cat2)) return 0; @@ -108,7 +104,7 @@ public class SiteCategory { * @return a map from locale to property set * @since 3.4 */ - public Map getLocalizations() { + public Map> getLocalizations() { return this.localizations; } @@ -181,7 +177,7 @@ public class SiteCategory { * @param localizations as a map from locale to property set * @since 3.4 */ - public void setLocalizations(Map localizations) { + public void setLocalizations(Map> localizations) { this.localizations = localizations; } diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteFeature.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteFeature.java index 3ad51042a..0a70eba90 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteFeature.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteFeature.java @@ -26,7 +26,7 @@ public class SiteFeature { private String arch; // performance private URL base; - private List /* of String*/categoryNames; + private List categoryNames; private String featureId; private String featureVersion; private String label; @@ -99,7 +99,7 @@ public class SiteFeature { */ public void addCategoryName(String categoryName) { if (this.categoryNames == null) - this.categoryNames = new ArrayList(); + this.categoryNames = new ArrayList(); if (!this.categoryNames.contains(categoryName)) this.categoryNames.add(categoryName); } @@ -180,7 +180,7 @@ public class SiteFeature { if (categoryNames == null) return new String[0]; - return (String[]) categoryNames.toArray(new String[0]); + return categoryNames.toArray(new String[0]); } /** @@ -337,7 +337,7 @@ public class SiteFeature { if (categoryNames == null) this.categoryNames = null; else - this.categoryNames = new ArrayList(Arrays.asList(categoryNames)); + this.categoryNames = new ArrayList(Arrays.asList(categoryNames)); } /** diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteModel.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteModel.java index d0bd69475..ec7b4a184 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteModel.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteModel.java @@ -22,16 +22,16 @@ import org.eclipse.equinox.p2.publisher.eclipse.URLEntry; */ public class SiteModel { - private List /*of ArchiveReferenceModel*/archiveReferences; + private List archiveReferences; /** * Map of String (category id) -> SiteCategory */ - private Map categories; + private Map categories; private URLEntry description; /** * Map of String (feature id) -> SiteFeature */ - private List features; + private List features; private URI locationURI; private String locationURIString; private String mirrorsURIString; @@ -39,8 +39,8 @@ public class SiteModel { private String type; private URLEntry[] associateSites; private String digestURIString; - private List messageKeys; - private Map localizations; + private List messageKeys; + private Map> localizations; /** * Creates an uninitialized site model object. @@ -60,7 +60,7 @@ public class SiteModel { */ public void addArchive(URLEntry archiveReference) { if (this.archiveReferences == null) - this.archiveReferences = new ArrayList(); + this.archiveReferences = new ArrayList(); if (!this.archiveReferences.contains(archiveReference)) this.archiveReferences.add(archiveReference); } @@ -72,7 +72,7 @@ public class SiteModel { */ public void addCategory(SiteCategory category) { if (categories == null) - categories = new HashMap(); + categories = new HashMap(); if (!categories.containsKey(category.getName())) { categories.put(category.getName(), category); if (localizations != null && !localizations.isEmpty()) @@ -87,7 +87,7 @@ public class SiteModel { */ public void addFeature(SiteFeature featureReference) { if (this.features == null) - this.features = new ArrayList(); + this.features = new ArrayList(); this.features.add(featureReference); } @@ -103,7 +103,7 @@ public class SiteModel { if (archiveReferences == null || archiveReferences.size() == 0) return new URLEntry[0]; - return (URLEntry[]) archiveReferences.toArray(new URLEntry[0]); + return archiveReferences.toArray(new URLEntry[0]); } public URLEntry[] getAssociatedSites() { @@ -119,7 +119,7 @@ public class SiteModel { public SiteCategory[] getCategories() { if (categories == null || categories.size() == 0) return new SiteCategory[0]; - return (SiteCategory[]) categories.values().toArray(new SiteCategory[0]); + return categories.values().toArray(new SiteCategory[0]); } /** @@ -127,7 +127,7 @@ public class SiteModel { * @return the category with the given name, or null */ public SiteCategory getCategory(String name) { - return (SiteCategory) (categories == null ? null : categories.get(name)); + return (categories == null ? null : categories.get(name)); } /** @@ -147,7 +147,7 @@ public class SiteModel { public SiteFeature[] getFeatures() { if (features == null || features.size() == 0) return new SiteFeature[0]; - return (SiteFeature[]) features.toArray(new SiteFeature[0]); + return features.toArray(new SiteFeature[0]); } /** @@ -157,7 +157,7 @@ public class SiteModel { * @return a map from locale to property set * @since 3.4 */ - public Map getLocalizations() { + public Map> getLocalizations() { return this.localizations; } @@ -192,7 +192,7 @@ public class SiteModel { * @return the list of keys for translatable strings; may be null * @since 3.4 */ - public List getMessageKeys() { + public List getMessageKeys() { return messageKeys; } @@ -236,13 +236,11 @@ public class SiteModel { * @param localizations as a map from locale to property set * @since 3.4 */ - public void setLocalizations(Map localizations) { + public void setLocalizations(Map> localizations) { this.localizations = localizations; if (localizations != null && !localizations.isEmpty() && // categories != null && !categories.isEmpty()) { - for (Iterator catIter = categories.entrySet().iterator(); catIter.hasNext();) { - Map.Entry entry = (Map.Entry) catIter.next(); - SiteCategory category = (SiteCategory) entry.getValue(); + for (SiteCategory category : categories.values()) { category.setLocalizations(localizations); } } @@ -264,7 +262,7 @@ public class SiteModel { * @param keys for translatable strings * @since 3.4 */ - public void setMessageKeys(List keys) { + public void setMessageKeys(List keys) { this.messageKeys = keys; } diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteXMLAction.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteXMLAction.java index 2a3fdfc8f..dc12af6cc 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteXMLAction.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteXMLAction.java @@ -10,23 +10,24 @@ ******************************************************************************/ package org.eclipse.equinox.internal.p2.updatesite; -import org.eclipse.equinox.internal.provisional.p2.metadata.Version; -import org.eclipse.equinox.internal.provisional.p2.metadata.VersionRange; - import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.*; +import java.util.Map.Entry; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.provisional.p2.core.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.*; +import org.eclipse.equinox.internal.p2.metadata.query.LatestIUVersionQuery; +import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.*; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.p2.publisher.*; import org.eclipse.equinox.p2.publisher.eclipse.URLEntry; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.spi.p2.publisher.LocalizationHelper; import org.eclipse.equinox.spi.p2.publisher.PublisherHelper; @@ -38,7 +39,7 @@ public class SiteXMLAction extends AbstractPublisherAction { static final private String QUALIFIER = "qualifier"; //$NON-NLS-1$ protected UpdateSite updateSite; private SiteCategory defaultCategory; - private HashSet defaultCategorySet; + private HashSet defaultCategorySet; protected URI location; private String categoryQualifier = null; @@ -73,7 +74,7 @@ public class SiteXMLAction extends AbstractPublisherAction { defaultCategory.setDescription("Default category for otherwise uncategorized features"); //$NON-NLS-1$ defaultCategory.setLabel("Uncategorized"); //$NON-NLS-1$ defaultCategory.setName("Default"); //$NON-NLS-1$ - defaultCategorySet = new HashSet(1); + defaultCategorySet = new HashSet(1); defaultCategorySet.add(defaultCategory); } @@ -92,24 +93,22 @@ public class SiteXMLAction extends AbstractPublisherAction { } private IStatus generateCategories(IPublisherInfo info, IPublisherResult results, IProgressMonitor monitor) { - Map categoriesToFeatureIUs = new HashMap(); - Map featuresToCategories = getFeatureToCategoryMappings(info); - for (Iterator i = featuresToCategories.keySet().iterator(); i.hasNext();) { + Map> categoriesToFeatureIUs = new HashMap>(); + Map> featuresToCategories = getFeatureToCategoryMappings(info); + for (SiteFeature feature : featuresToCategories.keySet()) { if (monitor.isCanceled()) return Status.CANCEL_STATUS; - SiteFeature feature = (SiteFeature) i.next(); IInstallableUnit iu = getFeatureIU(feature, info, results); if (iu == null) continue; - Set categories = (Set) featuresToCategories.get(feature); + Set categories = featuresToCategories.get(feature); // if there are no categories for this feature then add it to the default category. if (categories == null || categories.isEmpty()) categories = defaultCategorySet; - for (Iterator it = categories.iterator(); it.hasNext();) { - SiteCategory category = (SiteCategory) it.next(); - Set featureIUs = (Set) categoriesToFeatureIUs.get(category); + for (SiteCategory category : categories) { + Set featureIUs = categoriesToFeatureIUs.get(category); if (featureIUs == null) { - featureIUs = new HashSet(); + featureIUs = new HashSet(); categoriesToFeatureIUs.put(category, featureIUs); } featureIUs.add(iu); @@ -122,45 +121,43 @@ public class SiteXMLAction extends AbstractPublisherAction { private IInstallableUnit getFeatureIU(SiteFeature feature, IPublisherInfo publisherInfo, IPublisherResult results) { String id = feature.getFeatureIdentifier() + ".feature.group"; //$NON-NLS-1$ String versionString = feature.getFeatureVersion(); - Version version = versionString != null && versionString.length() > 0 ? new Version(versionString) : Version.emptyVersion; - Query query = null; - Collector collector = null; + Version version = versionString != null && versionString.length() > 0 ? Version.create(versionString) : Version.emptyVersion; + IQuery query = null; if (version.equals(Version.emptyVersion)) { - query = new CompositeQuery(new Query[] {new InstallableUnitQuery(id), new LatestIUVersionQuery()}); - collector = new Collector(); - } else if (version.getQualifier() != null && version.getQualifier().endsWith(QUALIFIER)) { - final String v = versionString.substring(0, versionString.indexOf(QUALIFIER)); - Query qualifierQuery = new InstallableUnitQuery(id) { - private String qualifierVersion = v.endsWith(".") ? v.substring(0, v.length() - 1) : v; //$NON-NLS-1$ - - public boolean isMatch(Object object) { - if (super.isMatch(object)) { - IInstallableUnit candidate = (IInstallableUnit) object; - return candidate.getVersion().toString().startsWith(qualifierVersion); - } - return false; - } - }; - query = new CompositeQuery(new Query[] {qualifierQuery, new LatestIUVersionQuery()}); - collector = new Collector(); + query = new PipedQuery(new InstallableUnitQuery(id), new LatestIUVersionQuery()); } else { - query = new InstallableUnitQuery(id, version); - collector = new Collector() { - public boolean accept(Object object) { - super.accept(object); - return false; //stop searching once we've found one - } - }; + String qualifier; + try { + qualifier = Version.toOSGiVersion(version).getQualifier(); + } catch (UnsupportedOperationException e) { + qualifier = null; + } + if (qualifier != null && qualifier.endsWith(QUALIFIER)) { + final String v = versionString.substring(0, versionString.indexOf(QUALIFIER)); + IQuery qualifierQuery = new InstallableUnitQuery(id) { + private String qualifierVersion = v.endsWith(".") ? v.substring(0, v.length() - 1) : v; //$NON-NLS-1$ + + public boolean isMatch(IInstallableUnit candidate) { + if (super.isMatch(candidate)) { + return candidate.getVersion().toString().startsWith(qualifierVersion); + } + return false; + } + }; + query = new PipedQuery(qualifierQuery, new LatestIUVersionQuery()); + } else { + query = new LimitQuery(new InstallableUnitQuery(id, version), 1); + } } - collector = results.query(query, collector, null); - if (collector.size() == 0) - collector = publisherInfo.getMetadataRepository().query(query, collector, null); - if (collector.size() == 0 && publisherInfo.getContextMetadataRepository() != null) - collector = publisherInfo.getContextMetadataRepository().query(query, collector, null); + IQueryResult queryResult = results.query(query, null); + if (queryResult.isEmpty()) + queryResult = publisherInfo.getMetadataRepository().query(query, null); + if (queryResult.isEmpty() && publisherInfo.getContextMetadataRepository() != null) + queryResult = publisherInfo.getContextMetadataRepository().query(query, null); - if (collector.size() == 1) - return (IInstallableUnit) collector.iterator().next(); + if (!queryResult.isEmpty()) + return queryResult.iterator().next(); return null; } @@ -169,8 +166,8 @@ public class SiteXMLAction extends AbstractPublisherAction { * if available. Returns an empty map if there is not site.xml, or no categories. * @return A map of SiteFeature -> Set. */ - protected Map getFeatureToCategoryMappings(IPublisherInfo info) { - HashMap mappings = new HashMap(); + protected Map> getFeatureToCategoryMappings(IPublisherInfo info) { + HashMap> mappings = new HashMap>(); if (updateSite == null) return mappings; SiteModel site = updateSite.getSite(); @@ -199,12 +196,12 @@ public class SiteXMLAction extends AbstractPublisherAction { File siteFile = URIUtil.toFile(updateSite.getLocation()); if (siteFile != null && siteFile.exists()) { File siteParent = siteFile.getParentFile(); - List messageKeys = site.getMessageKeys(); + List messageKeys = site.getMessageKeys(); if (siteParent.isDirectory()) { - String[] keyStrings = (String[]) messageKeys.toArray(new String[messageKeys.size()]); + String[] keyStrings = messageKeys.toArray(new String[messageKeys.size()]); site.setLocalizations(LocalizationHelper.getDirPropertyLocalizations(siteParent, "site", null, keyStrings)); //$NON-NLS-1$ } else if (siteFile.getName().endsWith(".jar")) { //$NON-NLS-1$ - String[] keyStrings = (String[]) messageKeys.toArray(new String[messageKeys.size()]); + String[] keyStrings = messageKeys.toArray(new String[messageKeys.size()]); site.setLocalizations(LocalizationHelper.getJarPropertyLocalizations(siteParent, "site", null, keyStrings)); //$NON-NLS-1$ } } @@ -213,7 +210,7 @@ public class SiteXMLAction extends AbstractPublisherAction { for (int i = 0; i < features.length; i++) { //add a mapping for each category this feature belongs to String[] categoryNames = features[i].getCategoryNames(); - Set categories = new HashSet(); + Set categories = new HashSet(); mappings.put(features[i], categories); for (int j = 0; j < categoryNames.length; j++) { SiteCategory category = site.getCategory(categoryNames[j]); @@ -251,10 +248,9 @@ public class SiteXMLAction extends AbstractPublisherAction { * @param categoriesToFeatures Map of SiteCategory ->Set (Feature IUs in that category). * @param result The generator result being built */ - protected void generateCategoryIUs(Map categoriesToFeatures, IPublisherResult result) { - for (Iterator it = categoriesToFeatures.keySet().iterator(); it.hasNext();) { - SiteCategory category = (SiteCategory) it.next(); - result.addIU(createCategoryIU(category, (Set) categoriesToFeatures.get(category), null), IPublisherResult.NON_ROOT); + protected void generateCategoryIUs(Map> categoriesToFeatures, IPublisherResult result) { + for (SiteCategory category : categoriesToFeatures.keySet()) { + result.addIU(createCategoryIU(category, categoriesToFeatures.get(category), null), IPublisherResult.NON_ROOT); } } @@ -265,7 +261,7 @@ public class SiteXMLAction extends AbstractPublisherAction { * @param parentCategory The parent category, or null * @return an IU representing the category */ - public IInstallableUnit createCategoryIU(SiteCategory category, Set featureIUs, IInstallableUnit parentCategory) { + public IInstallableUnit createCategoryIU(SiteCategory category, Set featureIUs, IInstallableUnit parentCategory) { InstallableUnitDescription cat = new MetadataFactory.InstallableUnitDescription(); cat.setSingleton(true); String categoryId = buildCategoryId(category.getName()); @@ -276,9 +272,8 @@ public class SiteXMLAction extends AbstractPublisherAction { cat.setProperty(IInstallableUnit.PROP_NAME, label != null ? label : category.getName()); cat.setProperty(IInstallableUnit.PROP_DESCRIPTION, category.getDescription()); - ArrayList reqsConfigurationUnits = new ArrayList(featureIUs.size()); - for (Iterator iterator = featureIUs.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); + ArrayList reqsConfigurationUnits = new ArrayList(featureIUs.size()); + for (IInstallableUnit iu : featureIUs) { VersionRange range = new VersionRange(iu.getVersion(), true, iu.getVersion(), true); reqsConfigurationUnits.add(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, iu.getId(), range, iu.getFilter(), false, false)); } @@ -286,30 +281,28 @@ public class SiteXMLAction extends AbstractPublisherAction { if (parentCategory != null) { reqsConfigurationUnits.add(MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, parentCategory.getId(), VersionRange.emptyRange, parentCategory.getFilter(), false, false)); } - cat.setRequiredCapabilities((IRequiredCapability[]) reqsConfigurationUnits.toArray(new IRequiredCapability[reqsConfigurationUnits.size()])); + cat.setRequiredCapabilities(reqsConfigurationUnits.toArray(new IRequirement[reqsConfigurationUnits.size()])); // Create set of provided capabilities - ArrayList providedCapabilities = new ArrayList(); + ArrayList providedCapabilities = new ArrayList(); providedCapabilities.add(PublisherHelper.createSelfCapability(categoryId, cat.getVersion())); - Map localizations = category.getLocalizations(); + Map> localizations = category.getLocalizations(); if (localizations != null) { - for (Iterator iter = localizations.keySet().iterator(); iter.hasNext();) { - Locale locale = (Locale) iter.next(); - Properties translatedStrings = (Properties) localizations.get(locale); - Enumeration propertyKeys = translatedStrings.propertyNames(); - while (propertyKeys.hasMoreElements()) { - String nextKey = (String) propertyKeys.nextElement(); - cat.setProperty(locale.toString() + '.' + nextKey, translatedStrings.getProperty(nextKey)); + for (Entry> locEntry : localizations.entrySet()) { + Locale locale = locEntry.getKey(); + Map translatedStrings = locEntry.getValue(); + for (Entry e : translatedStrings.entrySet()) { + cat.setProperty(locale.toString() + '.' + e.getKey(), e.getValue()); } providedCapabilities.add(PublisherHelper.makeTranslationCapability(categoryId, locale)); } } - cat.setCapabilities((IProvidedCapability[]) providedCapabilities.toArray(new IProvidedCapability[providedCapabilities.size()])); + cat.setCapabilities(providedCapabilities.toArray(new IProvidedCapability[providedCapabilities.size()])); cat.setArtifacts(new IArtifactKey[0]); - cat.setProperty(IInstallableUnit.PROP_TYPE_CATEGORY, "true"); //$NON-NLS-1$ + cat.setProperty(InstallableUnitDescription.PROP_TYPE_CATEGORY, "true"); //$NON-NLS-1$ return MetadataFactory.createInstallableUnit(cat); } diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/UpdateSite.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/UpdateSite.java index 461d38ce3..5b6a821f1 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/UpdateSite.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/UpdateSite.java @@ -10,6 +10,10 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.updatesite; +import org.eclipse.equinox.p2.core.ProvisionException; + +import org.eclipse.equinox.p2.publisher.eclipse.Feature; + import java.io.*; import java.net.*; import java.util.HashMap; @@ -21,7 +25,6 @@ import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.publisher.eclipse.FeatureParser; import org.eclipse.equinox.internal.p2.repository.AuthenticationFailedException; import org.eclipse.equinox.internal.p2.repository.RepositoryTransport; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.p2.publisher.eclipse.*; import org.eclipse.osgi.util.NLS; import org.xml.sax.SAXException; @@ -50,9 +53,9 @@ public class UpdateSite { * Some variables for caching. */ // map of String (URI.toString()) to UpdateSite - private static Map siteCache = new HashMap(); + private static Map siteCache = new HashMap(); // map of String (featureID_featureVersion) to Feature - private Map featureCache = new HashMap(); + private Map featureCache = new HashMap(); /* * Return a URI based on the given URI, which points to a site.xml file. @@ -81,7 +84,7 @@ public class UpdateSite { public static synchronized UpdateSite loadCategoryFile(URI location, IProgressMonitor monitor) throws ProvisionException { if (location == null) return null; - UpdateSite result = (UpdateSite) siteCache.get(location.toString()); + UpdateSite result = siteCache.get(location.toString()); if (result != null) return result; InputStream input = null; @@ -119,7 +122,7 @@ public class UpdateSite { public static synchronized UpdateSite load(URI location, IProgressMonitor monitor) throws ProvisionException { if (location == null) return null; - UpdateSite result = (UpdateSite) siteCache.get(location.toString()); + UpdateSite result = siteCache.get(location.toString()); if (result != null) return result; InputStream input = null; @@ -436,7 +439,7 @@ public class UpdateSite { */ public synchronized Feature[] loadFeatures(IProgressMonitor monitor) throws ProvisionException { if (!featureCache.isEmpty()) - return (Feature[]) featureCache.values().toArray(new Feature[featureCache.size()]); + return featureCache.values().toArray(new Feature[featureCache.size()]); Feature[] result = loadFeaturesFromDigest(monitor); return result == null ? loadFeaturesFromSite(monitor) : result; } @@ -477,7 +480,7 @@ public class UpdateSite { Feature[] features = new DigestParser().parse(digestFile, digestURI); if (features == null) return null; - Map tmpFeatureCache = new HashMap(features.length); + Map tmpFeatureCache = new HashMap(features.length); for (int i = 0; i < features.length; i++) { String key = features[i].getId() + VERSION_SEPARATOR + features[i].getVersion(); tmpFeatureCache.put(key, features[i]); @@ -518,7 +521,7 @@ public class UpdateSite { private Feature[] loadFeaturesFromSite(IProgressMonitor monitor) throws ProvisionException { SiteFeature[] siteFeatures = site.getFeatures(); FeatureParser featureParser = new FeatureParser(); - Map tmpFeatureCache = new HashMap(siteFeatures.length); + Map tmpFeatureCache = new HashMap(siteFeatures.length); for (int i = 0; i < siteFeatures.length; i++) { if (monitor.isCanceled()) { @@ -546,13 +549,13 @@ public class UpdateSite { } } featureCache = tmpFeatureCache; - return (Feature[]) featureCache.values().toArray(new Feature[featureCache.size()]); + return featureCache.values().toArray(new Feature[featureCache.size()]); } /* * Load the features that are included by the given feature. */ - private void loadIncludedFeatures(Feature feature, FeatureParser featureParser, Map features, IProgressMonitor monitor) throws ProvisionException { + private void loadIncludedFeatures(Feature feature, FeatureParser featureParser, Map features, IProgressMonitor monitor) throws ProvisionException { FeatureEntry[] featureEntries = feature.getEntries(); for (int i = 0; i < featureEntries.length; i++) { if (monitor.isCanceled()) diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/artifact/UpdateSiteArtifactRepository.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/artifact/UpdateSiteArtifactRepository.java index 517816bb6..d8ba4e035 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/artifact/UpdateSiteArtifactRepository.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/artifact/UpdateSiteArtifactRepository.java @@ -15,9 +15,10 @@ import java.net.URI; import java.util.Map; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; +import org.eclipse.equinox.p2.query.*; +import org.eclipse.equinox.p2.repository.artifact.*; public class UpdateSiteArtifactRepository implements IArtifactRepository { @@ -56,10 +57,6 @@ public class UpdateSiteArtifactRepository implements IArtifactRepository { return delegate.getArtifactDescriptors(key); } - public IArtifactKey[] getArtifactKeys() { - return delegate.getArtifactKeys(); - } - public IStatus getArtifacts(IArtifactRequest[] requests, IProgressMonitor monitor) { return delegate.getArtifacts(requests, monitor); } @@ -97,7 +94,7 @@ public class UpdateSiteArtifactRepository implements IArtifactRepository { return delegate.getName(); } - public Map getProperties() { + public Map getProperties() { return delegate.getProperties(); } @@ -133,7 +130,20 @@ public class UpdateSiteArtifactRepository implements IArtifactRepository { throw new UnsupportedOperationException("Repository not modifiable: " + location); //$NON-NLS-1$ } + @SuppressWarnings("rawtypes") public Object getAdapter(Class adapter) { return delegate.getAdapter(adapter); } + + public IArtifactDescriptor createArtifactDescriptor(IArtifactKey key) { + return delegate.createArtifactDescriptor(key); + } + + public IQueryable descriptorQueryable() { + return delegate.descriptorQueryable(); + } + + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return delegate.query(query, monitor); + } } diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/artifact/UpdateSiteArtifactRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/artifact/UpdateSiteArtifactRepositoryFactory.java index 1a1f2b281..fea37bd60 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/artifact/UpdateSiteArtifactRepositoryFactory.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/artifact/UpdateSiteArtifactRepositoryFactory.java @@ -14,19 +14,20 @@ package org.eclipse.equinox.internal.p2.updatesite.artifact; import java.net.URI; import java.util.*; import org.eclipse.core.runtime.*; +import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactDescriptor; +import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepositoryFactory; import org.eclipse.equinox.internal.p2.updatesite.Activator; import org.eclipse.equinox.internal.p2.updatesite.UpdateSite; import org.eclipse.equinox.internal.p2.updatesite.metadata.Messages; import org.eclipse.equinox.internal.p2.updatesite.metadata.UpdateSiteMetadataRepositoryFactory; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.*; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepDescriptor; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.ArtifactRepositoryFactory; -import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.SimpleArtifactRepositoryFactory; +import org.eclipse.equinox.p2.core.ProvisionException; +import org.eclipse.equinox.p2.metadata.IArtifactKey; import org.eclipse.equinox.p2.publisher.eclipse.*; +import org.eclipse.equinox.p2.repository.IRepository; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.artifact.*; +import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactRepositoryFactory; +import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; import org.eclipse.osgi.util.NLS; public class UpdateSiteArtifactRepositoryFactory extends ArtifactRepositoryFactory { @@ -34,13 +35,12 @@ public class UpdateSiteArtifactRepositoryFactory extends ArtifactRepositoryFacto /* (non-Javadoc) * @see org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.ArtifactRepositoryFactory#create(java.net.URL, java.lang.String, java.lang.String, java.util.Map) */ - public IArtifactRepository create(URI location, String name, String type, Map properties) { + public IArtifactRepository create(URI location, String name, String type, Map properties) { return null; } private static final String PROP_ARTIFACT_REFERENCE = "artifact.reference"; //$NON-NLS-1$ private static final String PROP_FORCE_THREADING = "eclipse.p2.force.threading"; //$NON-NLS-1$ - private static final String PROP_FORMAT_PACKED = "packed"; //$NON-NLS-1$ private static final String PROP_SITE_CHECKSUM = "site.checksum"; //$NON-NLS-1$ private static final String PROTOCOL_FILE = "file"; //$NON-NLS-1$ @@ -74,6 +74,7 @@ public class UpdateSiteArtifactRepositoryFactory extends ArtifactRepositoryFacto public IArtifactRepository loadRepository(URI location, IProgressMonitor monitor) { URI localRepositoryURL = UpdateSiteMetadataRepositoryFactory.getLocalRepositoryLocation(location); SimpleArtifactRepositoryFactory factory = new SimpleArtifactRepositoryFactory(); + factory.setAgent(getAgent()); try { return factory.load(localRepositoryURL, 0, monitor); } catch (ProvisionException e) { @@ -85,7 +86,7 @@ public class UpdateSiteArtifactRepositoryFactory extends ArtifactRepositoryFacto public void initializeRepository(IArtifactRepository repository, URI location, IProgressMonitor monitor) throws ProvisionException { UpdateSite updateSite = UpdateSite.load(location, monitor); - String savedChecksum = (String) repository.getProperties().get(PROP_SITE_CHECKSUM); + String savedChecksum = repository.getProperties().get(PROP_SITE_CHECKSUM); if (savedChecksum != null && savedChecksum.equals(updateSite.getChecksum())) return; @@ -101,24 +102,24 @@ public class UpdateSiteArtifactRepositoryFactory extends ArtifactRepositoryFacto private void generateArtifactDescriptors(UpdateSite updateSite, IArtifactRepository repository, IProgressMonitor monitor) throws ProvisionException { final String PACK_EXT = ".pack.gz"; //$NON-NLS-1$ Feature[] features = updateSite.loadFeatures(monitor); - Set allSiteArtifacts = new HashSet(); + Set allSiteArtifacts = new HashSet(); boolean packSupported = updateSite.getSite().isPack200Supported(); for (int i = 0; i < features.length; i++) { Feature feature = features[i]; IArtifactKey featureKey = FeaturesAction.createFeatureArtifactKey(feature.getId(), feature.getVersion()); - ArtifactDescriptor featureArtifactDescriptor = new ArtifactDescriptor(featureKey); + SimpleArtifactDescriptor featureArtifactDescriptor = new SimpleArtifactDescriptor(featureKey); URI featureURL = updateSite.getFeatureURI(feature.getId(), feature.getVersion()); featureArtifactDescriptor.setRepositoryProperty(PROP_ARTIFACT_REFERENCE, featureURL.toString()); allSiteArtifacts.add(featureArtifactDescriptor); if (packSupported) { // Update site supports pack200, create a packed descriptor - featureArtifactDescriptor = new ArtifactDescriptor(featureKey); + featureArtifactDescriptor = new SimpleArtifactDescriptor(featureKey); featureURL = updateSite.getFeatureURI(feature.getId(), feature.getVersion()); featureArtifactDescriptor.setRepositoryProperty(PROP_ARTIFACT_REFERENCE, featureURL.toString() + PACK_EXT); - ProcessingStepDescriptor[] steps = new ProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; //$NON-NLS-1$ + IProcessingStepDescriptor[] steps = new IProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; //$NON-NLS-1$ featureArtifactDescriptor.setProcessingSteps(steps); - featureArtifactDescriptor.setProperty(IArtifactDescriptor.FORMAT, PROP_FORMAT_PACKED); + featureArtifactDescriptor.setProperty(IArtifactDescriptor.FORMAT, IArtifactDescriptor.FORMAT_PACKED); allSiteArtifacts.add(featureArtifactDescriptor); } @@ -127,7 +128,7 @@ public class UpdateSiteArtifactRepositoryFactory extends ArtifactRepositoryFacto FeatureEntry entry = featureEntries[j]; if (entry.isPlugin() && !entry.isRequires()) { IArtifactKey key = BundlesAction.createBundleArtifactKey(entry.getId(), entry.getVersion()); - ArtifactDescriptor artifactDescriptor = new ArtifactDescriptor(key); + SimpleArtifactDescriptor artifactDescriptor = new SimpleArtifactDescriptor(key); URI pluginURL = updateSite.getPluginURI(entry); artifactDescriptor.setRepositoryProperty(PROP_ARTIFACT_REFERENCE, pluginURL.toString()); allSiteArtifacts.add(artifactDescriptor); @@ -135,19 +136,19 @@ public class UpdateSiteArtifactRepositoryFactory extends ArtifactRepositoryFacto if (packSupported) { // Update site supports pack200, create a packed descriptor key = BundlesAction.createBundleArtifactKey(entry.getId(), entry.getVersion()); - artifactDescriptor = new ArtifactDescriptor(key); + artifactDescriptor = new SimpleArtifactDescriptor(key); pluginURL = updateSite.getPluginURI(entry); artifactDescriptor.setRepositoryProperty(PROP_ARTIFACT_REFERENCE, pluginURL.toString() + PACK_EXT); - ProcessingStepDescriptor[] steps = new ProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; //$NON-NLS-1$ + IProcessingStepDescriptor[] steps = new IProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; //$NON-NLS-1$ artifactDescriptor.setProcessingSteps(steps); - artifactDescriptor.setProperty(IArtifactDescriptor.FORMAT, PROP_FORMAT_PACKED); + artifactDescriptor.setProperty(IArtifactDescriptor.FORMAT, IArtifactDescriptor.FORMAT_PACKED); allSiteArtifacts.add(artifactDescriptor); } } } } - IArtifactDescriptor[] descriptors = (IArtifactDescriptor[]) allSiteArtifacts.toArray(new IArtifactDescriptor[allSiteArtifacts.size()]); + IArtifactDescriptor[] descriptors = allSiteArtifacts.toArray(new IArtifactDescriptor[allSiteArtifacts.size()]); repository.addDescriptors(descriptors); } } diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/metadata/UpdateSiteMetadataRepository.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/metadata/UpdateSiteMetadataRepository.java index 34dd890d3..311304235 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/metadata/UpdateSiteMetadataRepository.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/metadata/UpdateSiteMetadataRepository.java @@ -13,10 +13,10 @@ package org.eclipse.equinox.internal.p2.updatesite.metadata; import java.net.URI; import java.util.Map; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Query; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; +import org.eclipse.equinox.p2.metadata.IInstallableUnit; +import org.eclipse.equinox.p2.query.IQuery; +import org.eclipse.equinox.p2.query.IQueryResult; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; public class UpdateSiteMetadataRepository implements IMetadataRepository { @@ -43,7 +43,7 @@ public class UpdateSiteMetadataRepository implements IMetadataRepository { throw new UnsupportedOperationException("Repository not modifiable: " + location); //$NON-NLS-1$ } - public boolean removeInstallableUnits(Query query, IProgressMonitor monitor) { + public boolean removeInstallableUnits(IInstallableUnit[] installableUnits, IProgressMonitor monitor) { throw new UnsupportedOperationException("Repository not modifiable: " + location); //$NON-NLS-1$ } @@ -59,7 +59,7 @@ public class UpdateSiteMetadataRepository implements IMetadataRepository { return delegate.getName(); } - public Map getProperties() { + public Map getProperties() { return delegate.getProperties(); } @@ -95,11 +95,12 @@ public class UpdateSiteMetadataRepository implements IMetadataRepository { throw new UnsupportedOperationException("Repository not modifiable: " + location); //$NON-NLS-1$ } + @SuppressWarnings("rawtypes") public Object getAdapter(Class adapter) { return delegate.getAdapter(adapter); } - public Collector query(Query query, Collector collector, IProgressMonitor monitor) { - return delegate.query(query, collector, monitor); + public IQueryResult query(IQuery query, IProgressMonitor monitor) { + return delegate.query(query, monitor); } } \ No newline at end of file diff --git a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/metadata/UpdateSiteMetadataRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/metadata/UpdateSiteMetadataRepositoryFactory.java index 528739500..7314e1492 100644 --- a/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/metadata/UpdateSiteMetadataRepositoryFactory.java +++ b/bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/metadata/UpdateSiteMetadataRepositoryFactory.java @@ -12,6 +12,12 @@ *******************************************************************************/ package org.eclipse.equinox.internal.p2.updatesite.metadata; +import org.eclipse.equinox.internal.p2.metadata.repository.SimpleMetadataRepositoryFactory; + +import org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory; + +import org.eclipse.equinox.p2.core.ProvisionException; + import java.io.File; import java.io.FileNotFoundException; import java.net.URI; @@ -21,12 +27,9 @@ import org.eclipse.ecf.filetransfer.UserCancelledException; import org.eclipse.equinox.internal.p2.metadata.repository.LocalMetadataRepository; import org.eclipse.equinox.internal.p2.repository.AuthenticationFailedException; import org.eclipse.equinox.internal.p2.updatesite.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory; -import org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.SimpleMetadataRepositoryFactory; import org.eclipse.equinox.p2.publisher.*; +import org.eclipse.equinox.p2.repository.IRepositoryManager; +import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.osgi.util.NLS; public class UpdateSiteMetadataRepositoryFactory extends MetadataRepositoryFactory { @@ -40,9 +43,9 @@ public class UpdateSiteMetadataRepositoryFactory extends MetadataRepositoryFacto } /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.MetadataRepositoryFactory#create(java.net.URL, java.lang.String, java.lang.String, java.util.Map) + * @see org.eclipse.equinox.p2.repository.metadata.spi.MetadataRepositoryFactory#create(java.net.URL, java.lang.String, java.lang.String, java.util.Map) */ - public IMetadataRepository create(URI location, String name, String type, Map properties) { + public IMetadataRepository create(URI location, String name, String type, Map properties) { return null; } @@ -91,6 +94,7 @@ public class UpdateSiteMetadataRepositoryFactory extends MetadataRepositoryFacto public IMetadataRepository loadRepository(URI location, IProgressMonitor monitor) { URI localRepositoryURL = getLocalRepositoryLocation(location); SimpleMetadataRepositoryFactory factory = new SimpleMetadataRepositoryFactory(); + factory.setAgent(getAgent()); try { return factory.load(localRepositoryURL, 0, monitor); } catch (ProvisionException e) { @@ -102,7 +106,7 @@ public class UpdateSiteMetadataRepositoryFactory extends MetadataRepositoryFacto public void initializeRepository(IMetadataRepository repository, URI location, IProgressMonitor monitor) throws ProvisionException { UpdateSite updateSite = UpdateSite.load(location, monitor); - String savedChecksum = (String) repository.getProperties().get(PROP_SITE_CHECKSUM); + String savedChecksum = repository.getProperties().get(PROP_SITE_CHECKSUM); if (savedChecksum != null && savedChecksum.equals(updateSite.getChecksum())) return; repository.setProperty(PROP_SITE_CHECKSUM, updateSite.getChecksum()); diff --git a/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/.project b/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/.project index bbddddcf3..4de3c836f 100644 --- a/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/.project +++ b/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/.project @@ -25,6 +25,11 @@ + + org.eclipse.pde.ds.core.builder + + + org.eclipse.pde.PluginNature diff --git a/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/META-INF/MANIFEST.MF index df3e02c57..ef29ba0fa 100644 --- a/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/META-INF/MANIFEST.MF @@ -4,7 +4,6 @@ Bundle-Name: %bundleName Bundle-SymbolicName: org.eclipse.equinox.simpleconfigurator.manipulator;singleton:=true Bundle-Version: 1.0.200.qualifier Bundle-Localization: plugin -Bundle-Activator: org.eclipse.equinox.internal.simpleconfigurator.manipulator.Activator Bundle-ActivationPolicy: lazy Import-Package: org.eclipse.equinox.internal.frameworkadmin.equinox, org.eclipse.equinox.internal.frameworkadmin.utils, @@ -18,3 +17,4 @@ Export-Package: org.eclipse.equinox.internal.provisional.simpleconfigurator.mani Bundle-RequiredExecutionEnvironment: CDC-1.1/Foundation-1.1, J2SE-1.4 Require-Bundle: org.eclipse.equinox.common;bundle-version="3.5.0" +Service-Component: OSGI-INF/configurator.xml diff --git a/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/OSGI-INF/configurator.xml b/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/OSGI-INF/configurator.xml new file mode 100644 index 000000000..181e07a8f --- /dev/null +++ b/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/OSGI-INF/configurator.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/build.properties b/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/build.properties index ac72e5e75..3d8dfe4be 100644 --- a/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/build.properties +++ b/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/build.properties @@ -1,18 +1,9 @@ -############################################################################### -# Copyright (c) 2005, 2007 IBM Corporation and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# IBM Corporation - initial API and implementation -############################################################################### -source.. = src/ output.. = bin/ bin.includes = META-INF/,\ .,\ about.html,\ - plugin.properties -qualifier=context + plugin.properties,\ + OSGI-INF/ src.includes = about.html +qualifier = context +source.. = src/ diff --git a/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/src/org/eclipse/equinox/internal/provisional/simpleconfigurator/manipulator/SimpleConfiguratorManipulator.java b/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/src/org/eclipse/equinox/internal/provisional/simpleconfigurator/manipulator/SimpleConfiguratorManipulator.java index 2a990d947..4a96d468c 100644 --- a/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/src/org/eclipse/equinox/internal/provisional/simpleconfigurator/manipulator/SimpleConfiguratorManipulator.java +++ b/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/src/org/eclipse/equinox/internal/provisional/simpleconfigurator/manipulator/SimpleConfiguratorManipulator.java @@ -1,8 +1,8 @@ /******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. All rights reserved. This - * program and the accompanying materials are made available under the terms of - * the Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html + * Copyright (c) 2008, 2009 IBM Corporation and others. All rights reserved. + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: IBM Corporation - initial API and implementation *******************************************************************************/ @@ -21,20 +21,20 @@ public interface SimpleConfiguratorManipulator extends ConfiguratorManipulator { * service with ConfiguratorManipulator.SERVICE_PROP_KEY_CONFIGURATOR_BUNDLESYMBOLICNAME = * SERVICE_PROP_VALUE_CONFIGURATOR_SYMBOLICNAME. */ - public static final String SERVICE_PROP_VALUE_CONFIGURATOR_SYMBOLICNAME = "org.eclipse.equinox.simpleconfigurator"; + public static final String SERVICE_PROP_VALUE_CONFIGURATOR_SYMBOLICNAME = "org.eclipse.equinox.simpleconfigurator"; //$NON-NLS-1$ /** * * @param url * @param launcherLocation - * @return + * @return The loaded configuration * @throws IOException */ public BundleInfo[] loadConfiguration(URL url, File launcherLocation) throws IOException; /** * - * @param bundleConfiguration + * @param configuration * @param outputFile * @param base * @throws IOException diff --git a/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/src/org/eclipse/equinox/internal/simpleconfigurator/manipulator/Activator.java b/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/src/org/eclipse/equinox/internal/simpleconfigurator/manipulator/Activator.java deleted file mode 100644 index e8bcfa9e2..000000000 --- a/bundles/org.eclipse.equinox.simpleconfigurator.manipulator/src/org/eclipse/equinox/internal/simpleconfigurator/manipulator/Activator.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.simpleconfigurator.manipulator; - -import java.util.Dictionary; -import java.util.Hashtable; -import org.eclipse.equinox.internal.provisional.configuratormanipulator.ConfiguratorManipulator; -import org.eclipse.equinox.internal.provisional.simpleconfigurator.manipulator.SimpleConfiguratorManipulator; -import org.osgi.framework.*; - -public class Activator implements BundleActivator { - final static boolean DEBUG = true; - private static volatile BundleContext context; - private ServiceRegistration registration; - - static BundleContext getContext() { - return context; - } - - private void registerConfiguratorManipulator() { - Dictionary props = new Hashtable(); - props.put(ConfiguratorManipulator.SERVICE_PROP_KEY_CONFIGURATOR_BUNDLESYMBOLICNAME, SimpleConfiguratorManipulator.SERVICE_PROP_VALUE_CONFIGURATOR_SYMBOLICNAME); - props.put(Constants.SERVICE_VENDOR, "Eclipse.org"); //$NON-NLS-1$ - SimpleConfiguratorManipulatorImpl manipulator = new SimpleConfiguratorManipulatorImpl(); - String[] clazzes = new String[] {ConfiguratorManipulator.class.getName(), SimpleConfiguratorManipulator.class.getName()}; - registration = context.registerService(clazzes, manipulator, props); - } - - public void start(BundleContext bundleContext) throws Exception { - Activator.context = bundleContext; - registerConfiguratorManipulator(); - } - - public void stop(BundleContext bundleContext) throws Exception { - if (registration != null) - registration.unregister(); - Activator.context = null; - } -} diff --git a/bundles/org.eclipse.equinox.simpleconfigurator/META-INF/MANIFEST.MF b/bundles/org.eclipse.equinox.simpleconfigurator/META-INF/MANIFEST.MF index b9a031031..c46f6d1e7 100644 --- a/bundles/org.eclipse.equinox.simpleconfigurator/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.equinox.simpleconfigurator/META-INF/MANIFEST.MF @@ -17,6 +17,7 @@ Import-Package: org.eclipse.osgi.framework.console;version="1.0.0";resolution:=o Export-Package: org.eclipse.equinox.internal.provisional.configurator; x-friends:="org.eclipse.equinox.p2.reconciler.dropins, org.eclipse.equinox.p2.console, + org.eclipse.equinox.p2.operations, org.eclipse.equinox.p2.ui, org.eclipse.equinox.p2.director", org.eclipse.equinox.internal.simpleconfigurator;x-internal:=true, diff --git a/bundles/org.eclipse.equinox.simpleconfigurator/src/org/eclipse/equinox/internal/simpleconfigurator/console/ApplyCommand.java b/bundles/org.eclipse.equinox.simpleconfigurator/src/org/eclipse/equinox/internal/simpleconfigurator/console/ApplyCommand.java index da5f020ce..b4bb8b0d5 100644 --- a/bundles/org.eclipse.equinox.simpleconfigurator/src/org/eclipse/equinox/internal/simpleconfigurator/console/ApplyCommand.java +++ b/bundles/org.eclipse.equinox.simpleconfigurator/src/org/eclipse/equinox/internal/simpleconfigurator/console/ApplyCommand.java @@ -12,7 +12,6 @@ package org.eclipse.equinox.internal.simpleconfigurator.console; import java.io.IOException; import java.net.URL; - import org.eclipse.equinox.internal.provisional.configurator.Configurator; import org.eclipse.osgi.framework.console.CommandInterpreter; import org.osgi.framework.BundleContext; diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/.settings/org.eclipse.jdt.core.prefs b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/.settings/org.eclipse.jdt.core.prefs index 88da5d43a..8f8669add 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/.settings/org.eclipse.jdt.core.prefs +++ b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/.settings/org.eclipse.jdt.core.prefs @@ -1,7 +1,7 @@ #Thu Mar 12 11:04:59 PDT 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/META-INF/MANIFEST.MF b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/META-INF/MANIFEST.MF index 5c908b502..5796e7571 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/META-INF/MANIFEST.MF +++ b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/META-INF/MANIFEST.MF @@ -7,7 +7,8 @@ Bundle-Activator: org.eclipse.equinox.p2.examples.rcp.cloud.Activator Bundle-Localization: plugin Require-Bundle: org.eclipse.ui, org.eclipse.core.runtime, - org.eclipse.equinox.p2.ui;bundle-version="1.0.100", + org.eclipse.equinox.p2.operations;bundle-version="2.0.0", + org.eclipse.equinox.p2.ui;bundle-version="2.0.0", org.eclipse.equinox.p2.metadata;bundle-version="1.0.0", org.eclipse.equinox.p2.metadata.repository;bundle-version="1.0.0", org.eclipse.equinox.p2.artifact.repository;bundle-version="1.0.0", diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/Activator.java b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/Activator.java index c12d07d85..c0589471a 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/Activator.java +++ b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/Activator.java @@ -1,8 +1,7 @@ package org.eclipse.equinox.p2.examples.rcp.cloud; -import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; import org.eclipse.equinox.p2.examples.rcp.cloud.p2.CloudPolicy; +import org.eclipse.equinox.p2.ui.Policy; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/CloudPolicy.java b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/CloudPolicy.java index bc962fb16..c5b754f93 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/CloudPolicy.java +++ b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/CloudPolicy.java @@ -10,8 +10,7 @@ *******************************************************************************/ package org.eclipse.equinox.p2.examples.rcp.cloud.p2; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.IUViewQueryContext; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.p2.ui.Policy; /** * CloudPolicy defines the RCP Cloud Example policies for the p2 UI. The policy @@ -21,12 +20,10 @@ import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; */ public class CloudPolicy extends Policy { public CloudPolicy() { - // XXX User has no access to manipulate repositories - setRepositoryManipulator(null); - + // XXX User has no visibility for repos + setRepositoriesVisible(false); + // XXX Default view is by category - IUViewQueryContext queryContext = new IUViewQueryContext( - IUViewQueryContext.AVAILABLE_VIEW_BY_CATEGORY); - setQueryContext(queryContext); + setGroupByCategory(true); } } diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/InstallNewSoftwareHandler.java b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/InstallNewSoftwareHandler.java index 9e08c2e2b..a7e9b7921 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/InstallNewSoftwareHandler.java +++ b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/InstallNewSoftwareHandler.java @@ -1,22 +1,17 @@ /******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.p2.examples.rcp.cloud.p2; -import org.eclipse.equinox.internal.provisional.p2.ui.IProvHelpContextIds; -import org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.InstallWizard; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.ProvisioningWizardDialog; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.wizard.WizardDialog; -import org.eclipse.ui.PlatformUI; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; /** * InstallNewSoftwareHandler invokes the install wizard @@ -32,21 +27,25 @@ public class InstallNewSoftwareHandler extends PreloadingRepositoryHandler { super(); } - protected void doExecute(String profileId, QueryableMetadataRepositoryManager manager) { - InstallWizard wizard = new InstallWizard(Policy.getDefault(), profileId, null, null, manager); - WizardDialog dialog = new ProvisioningWizardDialog(getShell(), wizard); - dialog.create(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IProvHelpContextIds.INSTALL_WIZARD); - - dialog.open(); + protected void doExecute(LoadMetadataRepositoryJob job) { + getProvisioningUI().openInstallWizard(getShell(), null, null, job); } protected boolean waitForPreload() { - // If there is no way for the user to manipulate repositories, - // then we may as well wait for existing repos to load so that - // content is available. If the user can manipulate the - // repositories, then we don't wait, because we don't know which - // ones they want to work with. - return Policy.getDefault().getRepositoryManipulator() == null; + // If the user cannot see repositories, then we may as well wait + // for existing repos to load so that content is available. + // If the user can manipulate the repositories, then we don't wait, + // because we don't know which ones they want to work with. + return !getProvisioningUI().getPolicy().getRepositoriesVisible(); + } + + protected void setLoadJobProperties(Job loadJob) { + super.setLoadJobProperties(loadJob); + // If we are doing a background load, we do not wish to authenticate, as the + // user is unaware that loading was needed + if (!waitForPreload()) { + loadJob.setProperty(LoadMetadataRepositoryJob.SUPPRESS_AUTHENTICATION_JOB_MARKER, Boolean.toString(true)); + loadJob.setProperty(LoadMetadataRepositoryJob.SUPPRESS_REPOSITORY_EVENTS, Boolean.toString(true)); + } } } diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/Messages.java b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/Messages.java deleted file mode 100644 index 2e228a737..000000000 --- a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/Messages.java +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.p2.examples.rcp.cloud.p2; - -import org.eclipse.osgi.util.NLS; - -public class Messages extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.equinox.p2.examples.rcp.cloud.p2.messages"; //$NON-NLS-1$ - static { - // load message values from bundle file - NLS.initializeMessages(BUNDLE_NAME, Messages.class); - } - public static String InstallNewSoftwareHandler_LoadRepositoryJobLabel; - public static String UpdateHandler_NoSitesMessage; - public static String UpdateHandler_NoSitesTitle; -} diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/PreloadingRepositoryHandler.java b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/PreloadingRepositoryHandler.java index 8b2213a0c..66aa00c4a 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/PreloadingRepositoryHandler.java +++ b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/PreloadingRepositoryHandler.java @@ -12,28 +12,22 @@ package org.eclipse.equinox.p2.examples.rcp.cloud.p2; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.runtime.*; -import org.eclipse.core.runtime.jobs.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.swt.custom.BusyIndicator; +import org.eclipse.core.runtime.jobs.IJobChangeEvent; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.core.runtime.jobs.JobChangeAdapter; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; /** - * PreloadingRepositoryHandler provides background loading of repositories - * before executing the provisioning handler. + * PreloadingRepositoryHandler provides background loading of + * repositories before executing the provisioning handler. * * @since 3.5 */ abstract class PreloadingRepositoryHandler extends AbstractHandler { - Object LOAD_FAMILY = new Object(); - /** * The constructor. */ @@ -45,46 +39,26 @@ abstract class PreloadingRepositoryHandler extends AbstractHandler { * Execute the command. */ public Object execute(ExecutionEvent event) { - final String profileId = IProfileRegistry.SELF; - BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { - public void run() { - doExecuteAndLoad(profileId, preloadRepositories()); - } - }); + doExecuteAndLoad(); return null; } - void doExecuteAndLoad(final String profileId, boolean preloadRepositories) { - // cancel any load that is already running - Job.getJobManager().cancel(LOAD_FAMILY); - final QueryableMetadataRepositoryManager queryableManager = new QueryableMetadataRepositoryManager( - Policy.getDefault().getQueryContext(), false); - if (preloadRepositories) { - Job loadJob = new Job( - Messages.InstallNewSoftwareHandler_LoadRepositoryJobLabel) { - - protected IStatus run(IProgressMonitor monitor) { - queryableManager.loadAll(monitor); - return Status.OK_STATUS; - } - - public boolean belongsTo(Object family) { - return family == LOAD_FAMILY; - } - - }; + void doExecuteAndLoad() { + if (preloadRepositories()) { + //cancel any load that is already running + Job.getJobManager().cancel(LoadMetadataRepositoryJob.LOAD_FAMILY); + final LoadMetadataRepositoryJob loadJob = new LoadMetadataRepositoryJob(getProvisioningUI()); + setLoadJobProperties(loadJob); if (waitForPreload()) { loadJob.addJobChangeListener(new JobChangeAdapter() { public void done(IJobChangeEvent event) { if (PlatformUI.isWorkbenchRunning()) if (event.getResult().isOK()) { - PlatformUI.getWorkbench().getDisplay() - .asyncExec(new Runnable() { - public void run() { - doExecute(profileId, - queryableManager); - } - }); + PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { + public void run() { + doExecute(loadJob); + } + }); } } }); @@ -95,15 +69,14 @@ abstract class PreloadingRepositoryHandler extends AbstractHandler { loadJob.setSystem(true); loadJob.setUser(false); loadJob.schedule(); - doExecute(profileId, queryableManager); + doExecute(null); } } else { - doExecute(profileId, queryableManager); + doExecute(null); } } - protected abstract void doExecute(String profileId, - QueryableMetadataRepositoryManager manager); + protected abstract void doExecute(LoadMetadataRepositoryJob job); protected boolean preloadRepositories() { return true; @@ -113,12 +86,19 @@ abstract class PreloadingRepositoryHandler extends AbstractHandler { return true; } + protected void setLoadJobProperties(Job loadJob) { + loadJob.setProperty(LoadMetadataRepositoryJob.ACCUMULATE_LOAD_ERRORS, Boolean.toString(true)); + } + + protected ProvisioningUI getProvisioningUI() { + return ProvisioningUI.getDefaultUI(); + } + /** * Return a shell appropriate for parenting dialogs of this handler. - * * @return a Shell */ protected Shell getShell() { - return ProvUI.getDefaultParentShell(); + return getProvisioningUI().getDefaultParentShell(); } } diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/UpdateHandler.java b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/UpdateHandler.java index 1668b09b3..77db223a1 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/UpdateHandler.java +++ b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/UpdateHandler.java @@ -10,22 +10,9 @@ *******************************************************************************/ package org.eclipse.equinox.p2.examples.rcp.cloud.p2; -import java.util.Collection; -import java.util.Iterator; - -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ElementQueryDescriptor; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.UpdateAction; -import org.eclipse.equinox.internal.provisional.p2.ui.model.ProfileElement; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.operations.UpdateOperation; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; /** * UpdateHandler invokes the check for updates UI @@ -36,59 +23,22 @@ public class UpdateHandler extends PreloadingRepositoryHandler { boolean hasNoRepos = false; - /** - * The constructor. - */ - public UpdateHandler() { - // constructor - } - - protected void doExecute(String profileId, QueryableMetadataRepositoryManager manager) { + protected void doExecute(LoadMetadataRepositoryJob job) { if (hasNoRepos) { - boolean goToSites = MessageDialog.openQuestion(getShell(), Messages.UpdateHandler_NoSitesTitle, Messages.UpdateHandler_NoSitesMessage); - if (goToSites) { - Policy.getDefault().getRepositoryManipulator().manipulateRepositories(getShell()); - } return; } - // get the profile roots - ElementQueryDescriptor queryDescriptor = Policy.getDefault().getQueryProvider().getQueryDescriptor(new ProfileElement(null, profileId)); - Collection collection = queryDescriptor.performQuery(null); - final IInstallableUnit[] roots = new IInstallableUnit[collection.size()]; - Iterator iter = collection.iterator(); - int i = 0; - while (iter.hasNext()) { - roots[i] = (IInstallableUnit) ProvUI.getAdapter(iter.next(), IInstallableUnit.class); - i++; + UpdateOperation operation = getProvisioningUI().getUpdateOperation(null, null); + // check for updates + operation.resolveModal(null); + if (getProvisioningUI().getPolicy().continueWorkingWithOperation(operation, getShell())) { + getProvisioningUI().openUpdateWizard(getShell(), true, operation, job); } - // now create an update action whose selection is all the roots - UpdateAction action = new UpdateAction(Policy.getDefault(), new ISelectionProvider() { - - public void addSelectionChangedListener(ISelectionChangedListener listener) { - // not dynamic - } - - public ISelection getSelection() { - return new StructuredSelection(roots); - } - - public void removeSelectionChangedListener(ISelectionChangedListener listener) { - // not dynamic - } - - public void setSelection(ISelection selection) { - // not mutable - - } - }, profileId, false); - action.setRepositoryManager(manager); - action.run(); } protected boolean preloadRepositories() { hasNoRepos = false; - RepositoryManipulator repoMan = Policy.getDefault().getRepositoryManipulator(); - if (repoMan != null && repoMan.getKnownRepositories().length == 0) { + RepositoryTracker repoMan = getProvisioningUI().getRepositoryTracker(); + if (repoMan.getKnownRepositories(getProvisioningUI().getSession()).length == 0) { hasNoRepos = true; return false; } diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/messages.properties b/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/messages.properties deleted file mode 100644 index e16c86732..000000000 --- a/examples/org.eclipse.equinox.p2.examples.rcp.cloud/src/org/eclipse/equinox/p2/examples/rcp/cloud/p2/messages.properties +++ /dev/null @@ -1,15 +0,0 @@ -############################################################################### -# Copyright (c) 2009 IBM Corporation and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# IBM Corporation - initial API and implementation -############################################################################### - - -InstallNewSoftwareHandler_LoadRepositoryJobLabel=Contacting Software Sites -UpdateHandler_NoSitesMessage=There are no update sites to search. Do you wish to open the "Available Software Sites" preferences? -UpdateHandler_NoSitesTitle=No Updates Found diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/.settings/org.eclipse.jdt.core.prefs b/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/.settings/org.eclipse.jdt.core.prefs index 337c4649f..92bb3f369 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/.settings/org.eclipse.jdt.core.prefs +++ b/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/.settings/org.eclipse.jdt.core.prefs @@ -1,7 +1,7 @@ #Mon Mar 16 12:12:08 PDT 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/META-INF/MANIFEST.MF b/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/META-INF/MANIFEST.MF index 8f4e5b0d1..6ee61c3c6 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/META-INF/MANIFEST.MF +++ b/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/META-INF/MANIFEST.MF @@ -6,15 +6,9 @@ Bundle-Version: 1.0.0.qualifier Bundle-Activator: org.eclipse.equinox.p2.examples.rcp.prestartupdate.Activator Require-Bundle: org.eclipse.ui, org.eclipse.core.runtime, - org.eclipse.equinox.p2.metadata;bundle-version="1.0.0", - org.eclipse.equinox.p2.metadata.repository;bundle-version="1.0.0", - org.eclipse.equinox.p2.artifact.repository;bundle-version="1.0.0", - org.eclipse.equinox.p2.repository;bundle-version="1.0.0", - org.eclipse.equinox.p2.extensionlocation;bundle-version="1.0.100", - org.eclipse.equinox.p2.updatesite;bundle-version="1.0.0", - org.eclipse.equinox.p2.director;bundle-version="1.0.100", - org.eclipse.equinox.p2.engine;bundle-version="1.0.100", - org.eclipse.equinox.p2.core;bundle-version="1.0.100", + org.eclipse.equinox.p2.core, + org.eclipse.equinox.p2.metadata, + org.eclipse.equinox.p2.operations, org.eclipse.ecf;bundle-version="3.0.0", org.eclipse.ecf.filetransfer;bundle-version="3.0.0", org.eclipse.ecf.identity;bundle-version="3.0.0", diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/src/org/eclipse/equinox/p2/examples/rcp/prestartupdate/ApplicationWorkbenchAdvisor.java b/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/src/org/eclipse/equinox/p2/examples/rcp/prestartupdate/ApplicationWorkbenchAdvisor.java index c5f04b9b9..2ebb4ff39 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/src/org/eclipse/equinox/p2/examples/rcp/prestartupdate/ApplicationWorkbenchAdvisor.java +++ b/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/src/org/eclipse/equinox/p2/examples/rcp/prestartupdate/ApplicationWorkbenchAdvisor.java @@ -1,33 +1,52 @@ package org.eclipse.equinox.p2.examples.rcp.prestartupdate; +import java.lang.reflect.InvocationTargetException; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jface.dialogs.ProgressMonitorDialog; +import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.application.IWorkbenchWindowConfigurer; import org.eclipse.ui.application.WorkbenchAdvisor; import org.eclipse.ui.application.WorkbenchWindowAdvisor; /** - * This workbench advisor creates the window advisor, and specifies - * the perspective id for the initial window. + * This workbench advisor creates the window advisor, and specifies the + * perspective id for the initial window. */ public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { - public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) { - return new ApplicationWorkbenchWindowAdvisor(configurer); - } - - /* - * (non-Javadoc) - * @see org.eclipse.ui.application.WorkbenchAdvisor#preStartup() - */ - public void preStartup() { - // XXX check for updates before starting up. - // If an update is performed, restart. - if (P2Util.checkForUpdates()) - PlatformUI.getWorkbench().restart(); - } - + public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor( + IWorkbenchWindowConfigurer configurer) { + return new ApplicationWorkbenchWindowAdvisor(configurer); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.application.WorkbenchAdvisor#preStartup() + */ + public void preStartup() { + // XXX check for updates before starting up. + // If an update is performed, restart. + + IRunnableWithProgress runnable = new IRunnableWithProgress() { + public void run(IProgressMonitor monitor) + throws InvocationTargetException, InterruptedException { + if (P2Util.checkForUpdates(monitor)) + PlatformUI.getWorkbench().restart(); + } + }; + try { + new ProgressMonitorDialog(null).run(true, true, runnable); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + } + } + public String getInitialWindowPerspectiveId() { return Perspective.ID; - } - + } + } diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/src/org/eclipse/equinox/p2/examples/rcp/prestartupdate/P2Util.java b/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/src/org/eclipse/equinox/p2/examples/rcp/prestartupdate/P2Util.java index 7ba13903b..404e33eb8 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/src/org/eclipse/equinox/p2/examples/rcp/prestartupdate/P2Util.java +++ b/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/src/org/eclipse/equinox/p2/examples/rcp/prestartupdate/P2Util.java @@ -11,183 +11,46 @@ package org.eclipse.equinox.p2.examples.rcp.prestartupdate; -import java.lang.reflect.InvocationTargetException; -import java.net.URI; -import java.util.ArrayList; -import java.util.Iterator; - import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.director.IPlanner; -import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; -import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan; -import org.eclipse.equinox.internal.provisional.p2.engine.DefaultPhaseSet; -import org.eclipse.equinox.internal.provisional.p2.engine.IEngine; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; -import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; -import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager; -import org.eclipse.jface.dialogs.ProgressMonitorDialog; -import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.equinox.p2.core.IProvisioningAgent; +import org.eclipse.equinox.p2.operations.ProvisioningJob; +import org.eclipse.equinox.p2.operations.ProvisioningSession; +import org.eclipse.equinox.p2.operations.UpdateOperation; public class P2Util { // XXX Check for updates to this application and return true if // we have installed updates and need a restart. - // This method is intentionally long and ugly in order to provide - // "one-stop-shopping" for how to check for and perform an update. - static boolean checkForUpdates() { - // Before we show a progress dialog, at least find out that we have - // installed content and repos to check. - final IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper - .getService(Activator.bundleContext, IProfileRegistry.class - .getName()); - if (profileRegistry == null) - return false; - final IProfile profile = profileRegistry - .getProfile(IProfileRegistry.SELF); - if (profile == null) - return false; - - // We are going to look for updates to all IU's in the profile. A - // different query could be used if we are looking for updates to - // a subset. For example, the p2 UI only looks for updates to those - // IU's marked with a special property. - final org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector collector = profile.query(InstallableUnitQuery.ANY, - new Collector(), null); - if (collector.isEmpty()) - return false; - final IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper + static boolean checkForUpdates(IProgressMonitor monitor) { + IProvisioningAgent agent = (IProvisioningAgent) ServiceHelper .getService(Activator.bundleContext, - IMetadataRepositoryManager.class.getName()); - if (manager == null) - return false; - final URI[] reposToSearch = manager - .getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); - if (reposToSearch.length == 0) - return false; - final IPlanner planner = (IPlanner) ServiceHelper.getService( - Activator.bundleContext, IPlanner.class.getName()); - if (planner == null) - return false; - // Looking in all known repositories for updates for each IU in the profile - final boolean[] didWeUpdate = new boolean[1]; - didWeUpdate[0] = false; - IRunnableWithProgress runnable = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) - throws InvocationTargetException, InterruptedException { - // We'll break progress up into 4 steps. - // 1. Load repos - it is not strictly necessary to do this. - // The planner will do it for us. However, burying this - // in the planner's progress reporting will not - // show enough progress initially, so we do it manually. - // 2. Get update list - // 3. Build a profile change request and get a provisioning plan - // 4. Perform the provisioning plan. - SubMonitor sub = SubMonitor.convert(monitor, - "Checking for application updates...", 400); - // 1. Load repos - SubMonitor loadMonitor = sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS); - for (int i=0; i 0) { - iusWithUpdates.add(iu); - if (replacements.length == 1) - replacementIUs.add(replacements[0]); - else { - IInstallableUnit repl = replacements[0]; - for (int i = 1; i < replacements.length; i++) - if (replacements[i].getVersion().compareTo( - repl.getVersion()) > 0) - repl = replacements[i]; - replacementIUs.add(repl); - } - } - } - // Did we find any updates? - if (iusWithUpdates.size() == 0) { - sub.done(); - } else { - if (sub.isCanceled()) - throw new InterruptedException(); - // 3. Build a profile change request and get a provisioning plan - ProfileChangeRequest changeRequest = new ProfileChangeRequest( - profile); - changeRequest - .removeInstallableUnits((IInstallableUnit[]) iusWithUpdates - .toArray(new IInstallableUnit[iusWithUpdates - .size()])); - changeRequest - .addInstallableUnits((IInstallableUnit[]) replacementIUs - .toArray(new IInstallableUnit[replacementIUs - .size()])); - ProvisioningPlan plan = planner.getProvisioningPlan( - changeRequest, pc, sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS)); - if (plan.getStatus().getSeverity() == IStatus.CANCEL) - throw new InterruptedException(); - if (plan.getStatus().getSeverity() != IStatus.ERROR) { - IEngine engine = (IEngine) ServiceHelper.getService( - Activator.bundleContext, IEngine.class - .getName()); - IArtifactRepositoryManager artifactMgr = (IArtifactRepositoryManager) ServiceHelper - .getService(Activator.bundleContext, - IArtifactRepositoryManager.class - .getName()); - if (engine != null && artifactMgr != null) { - // 4. Perform the provisioning plan - pc - .setArtifactRepositories(artifactMgr - .getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL)); - IStatus status = engine.perform(profile, - new DefaultPhaseSet(), plan.getOperands(), - pc, sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS)); - if (status.getSeverity() == IStatus.CANCEL) - throw new InterruptedException(); - if (status.getSeverity() != IStatus.ERROR) { - didWeUpdate[0] = true; - } - } - } - } + IProvisioningAgent.SERVICE_NAME); + if (agent == null) + return false; + ProvisioningSession session = new ProvisioningSession(agent); + // the default update operation looks for updates to the currently + // running profile, using the default profile root marker. To change + // which installable units are being updated, use the more detailed + // constructors. + UpdateOperation operation = new UpdateOperation(session); + + SubMonitor sub = SubMonitor.convert(monitor, + "Checking for application updates...", 200); + IStatus status = operation.resolveModal(sub.newChild(100)); + if (status.getSeverity() == IStatus.CANCEL) + throw new OperationCanceledException(); + if (status.getSeverity() != IStatus.ERROR) { + ProvisioningJob job = operation.getProvisioningJob(null); + status = job.runModal(sub.newChild(100)); + if (status.getSeverity() == IStatus.CANCEL) + throw new OperationCanceledException(); + if (status.getSeverity() != IStatus.ERROR) { + return true; } - }; - try { - new ProgressMonitorDialog(null).run(true, true, runnable); - } catch (InvocationTargetException e) { - e.printStackTrace(); - return false; - } catch (InterruptedException e) { - return false; } - return didWeUpdate[0]; + return false; } } diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/.settings/org.eclipse.jdt.core.prefs b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/.settings/org.eclipse.jdt.core.prefs index 6f414e032..1be1d28ec 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/.settings/org.eclipse.jdt.core.prefs +++ b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/.settings/org.eclipse.jdt.core.prefs @@ -1,7 +1,7 @@ #Mon Mar 16 12:11:08 PDT 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=jsr14 org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/META-INF/MANIFEST.MF b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/META-INF/MANIFEST.MF index e0ee6e8b3..8f48754d0 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/META-INF/MANIFEST.MF +++ b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/META-INF/MANIFEST.MF @@ -8,7 +8,8 @@ Bundle-Activator: org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility.Activa Require-Bundle: org.eclipse.ui, org.eclipse.core.runtime, org.eclipse.equinox.ds, - org.eclipse.equinox.p2.ui;bundle-version="1.0.100", + org.eclipse.equinox.p2.operations;bundle-version="2.0.0", + org.eclipse.equinox.p2.ui;bundle-version="2.0.0", org.eclipse.equinox.p2.metadata;bundle-version="1.0.0", org.eclipse.equinox.p2.metadata.repository;bundle-version="1.0.0", org.eclipse.equinox.p2.artifact.repository;bundle-version="1.0.0", diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/AllIUsAreVisiblePolicy.java b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/AllIUsAreVisiblePolicy.java index 752421038..e722f2ddf 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/AllIUsAreVisiblePolicy.java +++ b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/AllIUsAreVisiblePolicy.java @@ -10,9 +10,8 @@ *******************************************************************************/ package org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility.p2; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.ColocatedRepositoryManipulator; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.IUViewQueryContext; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; +import org.eclipse.equinox.p2.metadata.query.InstallableUnitQuery; +import org.eclipse.equinox.p2.ui.Policy; /** * AllIUsAreVisiblePolicy redefines the IU visibility. In this @@ -24,16 +23,11 @@ import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; public class AllIUsAreVisiblePolicy extends Policy { public AllIUsAreVisiblePolicy() { // XXX Use the pref-based repository manipulator - setRepositoryManipulator(new ColocatedRepositoryManipulator(this, PreferenceConstants.PREF_PAGE_SITES)); + setRepositoryPreferencePageId(PreferenceConstants.PREF_PAGE_SITES); - // XXX Create an IUViewQueryContext to change the visibility of the IUs shown in the UI. - // XXX Show the flat (non-categorized) view by default. - IUViewQueryContext context = new IUViewQueryContext(IUViewQueryContext.AVAILABLE_VIEW_FLAT); // XXX All available IU's should be shown, not just groups/features - context.setVisibleAvailableIUProperty(null); + setVisibleAvailableIUQuery(InstallableUnitQuery.ANY); // XXX All installed IU's should be shown, not just the user-installed. - context.setVisibleInstalledIUProperty(null); - - setQueryContext(context); + setVisibleInstalledIUQuery(InstallableUnitQuery.ANY); } } diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/InstallNewSoftwareHandler.java b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/InstallNewSoftwareHandler.java index 4dca71781..96e3758b9 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/InstallNewSoftwareHandler.java +++ b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/InstallNewSoftwareHandler.java @@ -1,22 +1,17 @@ /******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: + * Copyright (c) 2008, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility.p2; -import org.eclipse.equinox.internal.provisional.p2.ui.IProvHelpContextIds; -import org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.InstallWizard; -import org.eclipse.equinox.internal.provisional.p2.ui.dialogs.ProvisioningWizardDialog; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.wizard.WizardDialog; -import org.eclipse.ui.PlatformUI; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; /** * InstallNewSoftwareHandler invokes the install wizard @@ -32,21 +27,25 @@ public class InstallNewSoftwareHandler extends PreloadingRepositoryHandler { super(); } - protected void doExecute(String profileId, QueryableMetadataRepositoryManager manager) { - InstallWizard wizard = new InstallWizard(Policy.getDefault(), profileId, null, null, manager); - WizardDialog dialog = new ProvisioningWizardDialog(getShell(), wizard); - dialog.create(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IProvHelpContextIds.INSTALL_WIZARD); - - dialog.open(); + protected void doExecute(LoadMetadataRepositoryJob job) { + getProvisioningUI().openInstallWizard(getShell(), null, null, job); } protected boolean waitForPreload() { - // If there is no way for the user to manipulate repositories, - // then we may as well wait for existing repos to load so that - // content is available. If the user can manipulate the - // repositories, then we don't wait, because we don't know which - // ones they want to work with. - return Policy.getDefault().getRepositoryManipulator() == null; + // If the user cannot see repositories, then we may as well wait + // for existing repos to load so that content is available. + // If the user can manipulate the repositories, then we don't wait, + // because we don't know which ones they want to work with. + return !getProvisioningUI().getPolicy().getRepositoriesVisible(); + } + + protected void setLoadJobProperties(Job loadJob) { + super.setLoadJobProperties(loadJob); + // If we are doing a background load, we do not wish to authenticate, as the + // user is unaware that loading was needed + if (!waitForPreload()) { + loadJob.setProperty(LoadMetadataRepositoryJob.SUPPRESS_AUTHENTICATION_JOB_MARKER, Boolean.toString(true)); + loadJob.setProperty(LoadMetadataRepositoryJob.SUPPRESS_REPOSITORY_EVENTS, Boolean.toString(true)); + } } } diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/Messages.java b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/Messages.java index 8713ba269..5a480f75d 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/Messages.java +++ b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/Messages.java @@ -19,7 +19,6 @@ public class Messages extends NLS { // load message values from bundle file NLS.initializeMessages(BUNDLE_NAME, Messages.class); } - public static String InstallNewSoftwareHandler_LoadRepositoryJobLabel; public static String UpdateHandler_NoSitesMessage; public static String UpdateHandler_NoSitesTitle; public static String ProvisioningPreferencePage_AlwaysOpenWizard; diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/PreloadingRepositoryHandler.java b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/PreloadingRepositoryHandler.java index dec8d9bd7..552bc3b6c 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/PreloadingRepositoryHandler.java +++ b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/PreloadingRepositoryHandler.java @@ -12,28 +12,22 @@ package org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility.p2; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.runtime.*; -import org.eclipse.core.runtime.jobs.*; -import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; -import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.swt.custom.BusyIndicator; +import org.eclipse.core.runtime.jobs.IJobChangeEvent; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.core.runtime.jobs.JobChangeAdapter; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; +import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; /** - * PreloadingRepositoryHandler provides background loading of repositories - * before executing the provisioning handler. + * PreloadingRepositoryHandler provides background loading of + * repositories before executing the provisioning handler. * * @since 3.5 */ abstract class PreloadingRepositoryHandler extends AbstractHandler { - Object LOAD_FAMILY = new Object(); - /** * The constructor. */ @@ -45,46 +39,26 @@ abstract class PreloadingRepositoryHandler extends AbstractHandler { * Execute the command. */ public Object execute(ExecutionEvent event) { - final String profileId = IProfileRegistry.SELF; - BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { - public void run() { - doExecuteAndLoad(profileId, preloadRepositories()); - } - }); + doExecuteAndLoad(); return null; } - void doExecuteAndLoad(final String profileId, boolean preloadRepositories) { - // cancel any load that is already running - Job.getJobManager().cancel(LOAD_FAMILY); - final QueryableMetadataRepositoryManager queryableManager = new QueryableMetadataRepositoryManager( - Policy.getDefault().getQueryContext(), false); - if (preloadRepositories) { - Job loadJob = new Job( - Messages.InstallNewSoftwareHandler_LoadRepositoryJobLabel) { - - protected IStatus run(IProgressMonitor monitor) { - queryableManager.loadAll(monitor); - return Status.OK_STATUS; - } - - public boolean belongsTo(Object family) { - return family == LOAD_FAMILY; - } - - }; + void doExecuteAndLoad() { + if (preloadRepositories()) { + //cancel any load that is already running + Job.getJobManager().cancel(LoadMetadataRepositoryJob.LOAD_FAMILY); + final LoadMetadataRepositoryJob loadJob = new LoadMetadataRepositoryJob(getProvisioningUI()); + setLoadJobProperties(loadJob); if (waitForPreload()) { loadJob.addJobChangeListener(new JobChangeAdapter() { public void done(IJobChangeEvent event) { if (PlatformUI.isWorkbenchRunning()) if (event.getResult().isOK()) { - PlatformUI.getWorkbench().getDisplay() - .asyncExec(new Runnable() { - public void run() { - doExecute(profileId, - queryableManager); - } - }); + PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { + public void run() { + doExecute(loadJob); + } + }); } } }); @@ -95,15 +69,14 @@ abstract class PreloadingRepositoryHandler extends AbstractHandler { loadJob.setSystem(true); loadJob.setUser(false); loadJob.schedule(); - doExecute(profileId, queryableManager); + doExecute(null); } } else { - doExecute(profileId, queryableManager); + doExecute(null); } } - protected abstract void doExecute(String profileId, - QueryableMetadataRepositoryManager manager); + protected abstract void doExecute(LoadMetadataRepositoryJob job); protected boolean preloadRepositories() { return true; @@ -113,12 +86,19 @@ abstract class PreloadingRepositoryHandler extends AbstractHandler { return true; } + protected void setLoadJobProperties(Job loadJob) { + loadJob.setProperty(LoadMetadataRepositoryJob.ACCUMULATE_LOAD_ERRORS, Boolean.toString(true)); + } + + protected ProvisioningUI getProvisioningUI() { + return ProvisioningUI.getDefaultUI(); + } + /** * Return a shell appropriate for parenting dialogs of this handler. - * * @return a Shell */ protected Shell getShell() { - return ProvUI.getDefaultParentShell(); + return getProvisioningUI().getDefaultParentShell(); } } diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/ProvisioningPreferencePage.java b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/ProvisioningPreferencePage.java index 9a049f939..b6cd2b8c4 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/ProvisioningPreferencePage.java +++ b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/ProvisioningPreferencePage.java @@ -18,8 +18,13 @@ import org.eclipse.jface.preference.PreferencePage; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.*; -import org.eclipse.ui.*; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Group; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; +import org.eclipse.ui.PlatformUI; /** * Preference page for general provisioning preferences. diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/UpdateHandler.java b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/UpdateHandler.java index 891be7e10..b9e2fcdec 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/UpdateHandler.java +++ b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/UpdateHandler.java @@ -10,22 +10,10 @@ *******************************************************************************/ package org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility.p2; -import java.util.Collection; -import java.util.Iterator; - -import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.internal.provisional.p2.ui.ElementQueryDescriptor; -import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI; -import org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager; -import org.eclipse.equinox.internal.provisional.p2.ui.actions.UpdateAction; -import org.eclipse.equinox.internal.provisional.p2.ui.model.ProfileElement; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy; -import org.eclipse.equinox.internal.provisional.p2.ui.policy.RepositoryManipulator; +import org.eclipse.equinox.p2.operations.RepositoryTracker; +import org.eclipse.equinox.p2.operations.UpdateOperation; +import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.viewers.StructuredSelection; /** * UpdateHandler invokes the check for updates UI @@ -36,59 +24,28 @@ public class UpdateHandler extends PreloadingRepositoryHandler { boolean hasNoRepos = false; - /** - * The constructor. - */ - public UpdateHandler() { - // constructor - } - - protected void doExecute(String profileId, QueryableMetadataRepositoryManager manager) { + protected void doExecute(LoadMetadataRepositoryJob job) { if (hasNoRepos) { - boolean goToSites = MessageDialog.openQuestion(getShell(), Messages.UpdateHandler_NoSitesTitle, Messages.UpdateHandler_NoSitesMessage); - if (goToSites) { - Policy.getDefault().getRepositoryManipulator().manipulateRepositories(getShell()); + if (getProvisioningUI().getPolicy().getRepositoriesVisible()) { + boolean goToSites = MessageDialog.openQuestion(getShell(), Messages.UpdateHandler_NoSitesTitle, Messages.UpdateHandler_NoSitesMessage); + if (goToSites) { + getProvisioningUI().manipulateRepositories(getShell()); + } } return; } - // get the profile roots - ElementQueryDescriptor queryDescriptor = Policy.getDefault().getQueryProvider().getQueryDescriptor(new ProfileElement(null, profileId)); - Collection collection = queryDescriptor.performQuery(null); - final IInstallableUnit[] roots = new IInstallableUnit[collection.size()]; - Iterator iter = collection.iterator(); - int i = 0; - while (iter.hasNext()) { - roots[i] = (IInstallableUnit) ProvUI.getAdapter(iter.next(), IInstallableUnit.class); - i++; + UpdateOperation operation = getProvisioningUI().getUpdateOperation(null, null); + // check for updates + operation.resolveModal(null); + if (getProvisioningUI().getPolicy().continueWorkingWithOperation(operation, getShell())) { + getProvisioningUI().openUpdateWizard(getShell(), true, operation, job); } - // now create an update action whose selection is all the roots - UpdateAction action = new UpdateAction(Policy.getDefault(), new ISelectionProvider() { - - public void addSelectionChangedListener(ISelectionChangedListener listener) { - // not dynamic - } - - public ISelection getSelection() { - return new StructuredSelection(roots); - } - - public void removeSelectionChangedListener(ISelectionChangedListener listener) { - // not dynamic - } - - public void setSelection(ISelection selection) { - // not mutable - - } - }, profileId, false); - action.setRepositoryManager(manager); - action.run(); } protected boolean preloadRepositories() { hasNoRepos = false; - RepositoryManipulator repoMan = Policy.getDefault().getRepositoryManipulator(); - if (repoMan != null && repoMan.getKnownRepositories().length == 0) { + RepositoryTracker repoMan = getProvisioningUI().getRepositoryTracker(); + if (repoMan.getKnownRepositories(getProvisioningUI().getSession()).length == 0) { hasNoRepos = true; return false; } diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/messages.properties b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/messages.properties index 21475c188..3da5a90c0 100644 --- a/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/messages.properties +++ b/examples/org.eclipse.equinox.p2.examples.rcp.sdkbundlevisibility/src/org/eclipse/equinox/p2/examples/rcp/sdkbundlevisibility/p2/messages.properties @@ -10,7 +10,6 @@ ############################################################################### -InstallNewSoftwareHandler_LoadRepositoryJobLabel=Contacting Software Sites UpdateHandler_NoSitesMessage=There are no update sites to search. Do you wish to open the "Available Software Sites" preferences? UpdateHandler_NoSitesTitle=No Updates Found ProvisioningPreferencePage_AlwaysOpenWizard=&Open the wizard anyway to review or change selections diff --git a/org.eclipse.equinox.p2.releng/R3_6_api_cleanup_projectSet.psf b/org.eclipse.equinox.p2.releng/R3_6_api_cleanup_projectSet.psf new file mode 100644 index 000000000..5f1fff49d --- /dev/null +++ b/org.eclipse.equinox.p2.releng/R3_6_api_cleanup_projectSet.psf @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/org.eclipse.equinox.p2.releng/buildtime-features/org.eclipse.equinox.p2.user.ui/feature.xml b/org.eclipse.equinox.p2.releng/buildtime-features/org.eclipse.equinox.p2.user.ui/feature.xml index cb727763f..85790cce3 100644 --- a/org.eclipse.equinox.p2.releng/buildtime-features/org.eclipse.equinox.p2.user.ui/feature.xml +++ b/org.eclipse.equinox.p2.releng/buildtime-features/org.eclipse.equinox.p2.user.ui/feature.xml @@ -315,4 +315,11 @@ version="3.1.0.qualifier" unpack="false"/> + + diff --git a/org.eclipse.equinox.p2.releng/mylyn-discovery.psf b/org.eclipse.equinox.p2.releng/mylyn-discovery.psf new file mode 100644 index 000000000..1f964816c --- /dev/null +++ b/org.eclipse.equinox.p2.releng/mylyn-discovery.psf @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/org.eclipse.equinox.p2.releng/p2_users_R_3_6_api_cleanup_projectSet.psf b/org.eclipse.equinox.p2.releng/p2_users_R_3_6_api_cleanup_projectSet.psf new file mode 100644 index 000000000..d1774ff89 --- /dev/null +++ b/org.eclipse.equinox.p2.releng/p2_users_R_3_6_api_cleanup_projectSet.psf @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/org.eclipse.equinox.p2.releng/projectSet-extssh.psf b/org.eclipse.equinox.p2.releng/projectSet-extssh.psf index cdf823829..a97d4fa92 100644 --- a/org.eclipse.equinox.p2.releng/projectSet-extssh.psf +++ b/org.eclipse.equinox.p2.releng/projectSet-extssh.psf @@ -27,6 +27,7 @@ + @@ -37,7 +38,6 @@ - diff --git a/org.eclipse.equinox.p2.releng/projectSet.psf b/org.eclipse.equinox.p2.releng/projectSet.psf index 5671b707d..02580064e 100644 --- a/org.eclipse.equinox.p2.releng/projectSet.psf +++ b/org.eclipse.equinox.p2.releng/projectSet.psf @@ -27,6 +27,7 @@ + @@ -37,7 +38,6 @@ - -- cgit v1.2.3